repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
LucianoPolit/RepositoryKit | Source/Core/Networking.swift | 1 | 4824 | //
// Networking.swift
//
// Copyright (c) 2016-2017 Luciano Polit <[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 PromiseKit
// MARK: - Main
/// It is needed to be considered a *Networking Recipe* by a *Repository*.
public protocol Networking {
/// The url of the server.
var url: String { get }
/**
Creates a promise with the response of a request for the specified method, url, parameters and headers.
- Parameter method: The HTTP method.
- Parameter path: The path of the URL.
- Parameter parameters: The parameters.
- Parameter headers: The HTTP headers.
- Returns: A promise of `Any`.
*/
func request(method: HTTPMethod,
path: String,
parameters: [String: Any]?,
headers: [String: String]?) -> Promise<Any>
}
// MARK: - Util
extension Networking {
/**
Creates a promise with the response of a request for the specified method, url, parameters and headers.
- Parameter method: The HTTP method.
- Parameter path: The path of the URL.
- Parameter parameters: The parameters (nil by default).
- Parameter headers: The HTTP headers (nil by default).
- Returns: A promise of `DictionaryEntity`.
*/
public func request(method: HTTPMethod,
path: String, parameters: [String: Any]? = nil,
headers: [String: String]? = nil) -> Promise<DictionaryEntity> {
return request(method: method, path: path, parameters: parameters, headers: headers)
.then { (result: Any) in
Promise { success, failure in
guard let value = result as? DictionaryEntity else {
failure(Error.casting)
return
}
success(value)
}
}
}
/**
Creates a promise with the response of a request for the specified method, url, parameters and headers.
- Parameter method: The HTTP method.
- Parameter path: The path of the URL.
- Parameter parameters: The parameters (nil by default).
- Parameter headers: The HTTP headers (nil by default).
- Returns: A promise of an `Array` of `DictionaryEntity`.
*/
public func request(method: HTTPMethod,
path: String, parameters: [String: Any]? = nil,
headers: [String: String]? = nil) -> Promise<[DictionaryEntity]> {
return request(method: method, path: path, parameters: parameters, headers: headers)
.then { (result: Any) in
Promise { success, failure in
guard let value = result as? [DictionaryEntity] else {
failure(Error.casting)
return
}
success(value)
}
}
}
/**
Creates a promise with the response of a request for the specified method, url, parameters and headers.
- Parameter method: The HTTP method.
- Parameter path: The path of the URL.
- Parameter parameters: The parameters (nil by default).
- Parameter headers: The HTTP headers (nil by default).
- Returns: A promise of `Void`.
*/
public func request(method: HTTPMethod,
path: String, parameters: [String: Any]? = nil,
headers: [String: String]? = nil) -> Promise<Void> {
return request(method: method, path: path, parameters: parameters, headers: headers)
.then { (result: Any) -> Void in }
}
}
| mit | 94f17d8db852b1ea7554fa6233335f97 | 36.107692 | 108 | 0.601783 | 4.795229 | false | false | false | false |
apple/swift-numerics | Sources/_TestSupport/Interval.swift | 1 | 1467 | //===--- Interval.swift ---------------------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020 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
//
//===----------------------------------------------------------------------===//
// A not-particularly-clever floating-point iterval that is iterable for the
// purposes of testing.
public struct Interval<Element>: Sequence where Element: FloatingPoint {
let lower: Element
let upper: Element
public init(from: Element, through: Element) {
precondition(from <= through)
lower = from
upper = through
}
public init(from: Element, to: Element) {
self.init(from: from, through: to.nextDown)
}
public func makeIterator() -> Iterator {
Iterator(self)
}
public struct Iterator: IteratorProtocol {
let interval: Interval
var nextOutput: Element?
init(_ interval: Interval) {
self.interval = interval
self.nextOutput = interval.lower
}
public mutating func next() -> Element? {
let result = nextOutput
if nextOutput == interval.upper { nextOutput = nil }
else { nextOutput = nextOutput?.nextUp }
return result
}
}
}
| apache-2.0 | 5e1aeea16873e47368c34ddfa6679e89 | 27.764706 | 80 | 0.615542 | 4.598746 | false | false | false | false |
marcelganczak/swift-js-transpiler | test/weheartswift/tuples-enums-2.swift | 1 | 537 | print("TODO")
/*enum CoinType: Int {
case penny = 1
case nickle = 5
case dime = 10
case quarter = 25
}
var moneyArray:[(Int,CoinType)] = [(10,.penny),
(15,.nickle),
(3,.quarter),
(20,.penny),
(3,.dime),
(7,.quarter)]
var totalMoney = 0
for (amount, coinType) in moneyArray {
totalMoney += amount * coinType.rawValue
}
print(totalMoney)*/ | mit | 43740435bc8f66dc7386dc6fa848ed38 | 22.391304 | 48 | 0.418994 | 4.296 | false | false | false | false |
LYM-mg/MGDYZB | MGDYZB简单封装版/MGDYZB/Class/Home/Controller/HomeViewController.swift | 1 | 6586 | //
// HomeViewController.swift
// MGDYZB
//
// Created by ming on 16/10/25.
// Copyright © 2016年 ming. All rights reserved.
// 简书:http://www.jianshu.com/users/57b58a39b70e/latest_articles
// github: https://github.com/LYM-mg
import UIKit
private let kTitlesViewH : CGFloat = 40
class HomeViewController: UIViewController {
var isFirst: Bool = false // 第一次启动
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
automaticallyAdjustsScrollViewInsets = false
// 1.创建UI
setUpMainView()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// 第一次启动
if (isFirst == false) {
self.navigationController!.navigationBar.isHidden = true
let window = UIApplication.shared.keyWindow
// 添加启动页的图片
let welcomeImage = UIImageView(frame: window!.bounds)
welcomeImage.image = getWelcomeImage()
window!.addSubview(welcomeImage)
window!.bringSubviewToFront(welcomeImage) // 把背景图放在最上层
welcomeImage.alpha = 0.99 //这里alpha的值和下面alpha的值不能设置为相同的,否则动画相当于瞬间执行完,启动页之后动画瞬间消失。这里alpha设为0.99,动画就不会有一闪而过的效果,而是一种类似于静态背景的效果。设为0,动画就相当于是淡入的效果了。
// UIViewAnimationOptionCurveEaseOut
UIView.animateKeyframes(withDuration: 2.5, delay: 0 , options: .calculationModeCubic, animations: { () -> Void in
welcomeImage.layer.transform = CATransform3DMakeScale(1.5, 1.5, 1.5)
// welcomeImage.transform = CGAffineTransformMakeScale(1.3, 1.3)
welcomeImage.alpha = 0.01
}, completion: { (finished) -> Void in
UIView.animate(withDuration: 1.0, animations: { () -> Void in
self.navigationController!.navigationBar.isHidden = false
welcomeImage.removeFromSuperview()
})
})
isFirst = true
}
}
/**
* 获取启动页的图片
*/
func getWelcomeImage() -> UIImage {
let viewSize = UIApplication.shared.keyWindow!.bounds.size
// 竖屏 UIInterfaceOrientationPortrait
let viewOrientation = "Portrait"
var launchImageName = ""
// print(NSBundle.mainBundle().infoDictionary)
let info = Bundle.main.infoDictionary
let imagesDict = info!["UILaunchImages"] as! [[String: AnyObject]]
for dict in imagesDict {
let imageSize = NSCoder.cgSize(for: dict["UILaunchImageSize"] as! String)
if imageSize.equalTo(viewSize) && viewOrientation == dict["UILaunchImageOrientation"] as! String {
launchImageName = dict["UILaunchImageName"] as! String
}
}
return UIImage(named: launchImageName)!
}
// MARK: - lazy
fileprivate lazy var homeTitlesView: HomeTitlesView = { [weak self] in
let titleFrame = CGRect(x: 0, y: MGNavHeight, width: kScreenW, height: kTitlesViewH)
let titles = ["推荐", "游戏", "娱乐", "趣玩"]
let tsView = HomeTitlesView(frame: titleFrame, titles: titles)
tsView.deledate = self
return tsView
}()
fileprivate lazy var homeContentView: HomeContentView = { [weak self] in
// 1.确定内容的frame
let contentH = kScreenH - MGNavHeight - kTitlesViewH - kTabbarH
let contentFrame = CGRect(x: 0, y: MGNavHeight+kTitlesViewH, width: kScreenW, height: contentH)
// 2.确定所有的子控制器
var childVcs = [UIViewController]()
childVcs.append(RecommendViewController())
childVcs.append(GameViewController())
childVcs.append(AmuseViewController())
childVcs.append(FunnyViewController())
let contentView = HomeContentView(frame: contentFrame, childVcs: childVcs, parentViewController: self)
contentView.delegate = self
return contentView
}()
}
// MARK: - 初始化UI
extension HomeViewController {
fileprivate func setUpMainView() {
setUpNavgationBar()
view.addSubview(homeTitlesView)
view.addSubview(homeContentView)
}
}
// MARK:- 遵守 HomeTitlesViewDelegate 协议
extension HomeViewController : HomeTitlesViewDelegate {
func HomeTitlesViewDidSetlected(_ homeTitlesView: HomeTitlesView, selectedIndex: Int) {
homeContentView.setCurrentIndex(selectedIndex)
}
}
// MARK:- 遵守 HomeContentViewDelegate 协议
extension HomeViewController : HomeContentViewDelegate {
func HomeContentViewDidScroll(_ contentView: HomeContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int) {
homeTitlesView.setTitleWithProgress(progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
}
}
// MARK:- 导航栏相关
extension HomeViewController {
fileprivate func setUpNavgationBar() {
// 1.设置左侧的Item
navigationItem.leftBarButtonItem = UIBarButtonItem.createItem("logo")
// 2.设置右侧的Item
let size = CGSize(width: 40, height: 40)
let historyItem = UIBarButtonItem(imageName: "image_my_history", highImageName: "Image_my_history_click", size: size, target: self, action: #selector(self.historyClick(_:)))
let searchItem = UIBarButtonItem(imageName: "btn_search", highImageName: "btn_search_clicked", size: size, target: self, action: #selector(HomeViewController.seachClick(_:)))
let qrcodeItem = UIBarButtonItem(imageName: "Image_scan", highImageName: "Image_scan_click", size: size, target: self, action: #selector(self.scanClick(btn:)))
navigationItem.rightBarButtonItems = [historyItem, searchItem, qrcodeItem]
}
@objc fileprivate func historyClick(_ btn: UIButton) {
self.show(WatchHistoryViewController(), sender: nil)
}
// 搜索
@objc fileprivate func seachClick(_ btn: UIButton) {
self.show(SearchResultViewController(), sender: nil)
}
// 扫一扫
@objc fileprivate func scanClick(btn: UIButton) {
self.show(ScanViewController(), sender: nil)
}
}
| mit | 84d3e0a446367c6c133a39ea456c8d54 | 36.155689 | 182 | 0.653344 | 4.634055 | false | false | false | false |
RobinChao/Hacking-with-Swift | HackingWithSwift-07/HackingWithSwift-07/DetailViewController.swift | 1 | 1172 | //
// DetailViewController.swift
// HackingWithSwift-07
//
// Created by Robin on 2/25/16.
// Copyright © 2016 Robin. All rights reserved.
//
import UIKit
import WebKit
class DetailViewController: UIViewController {
var webView: WKWebView!
var detailItem: [String : String]!
override func loadView() {
webView = WKWebView()
view = webView
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
guard detailItem != nil else { return }
if let body = detailItem["body"] {
var html = "<html>"
html += "<head>"
html += "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">"
html += "<style>body {font-size: 150%;}</style>"
html += "</head>"
html += "<body>"
html += body
html += "</body>"
html += "</html>"
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 95cd10f10cde9dceb3b04d325a19b768 | 23.395833 | 94 | 0.551665 | 4.684 | false | false | false | false |
xmartlabs/Opera | Example/Release.swift | 1 | 1774 | // Release.swift
// Example-iOS ( https://github.com/xmartlabs/Example-iOS )
//
// Copyright (c) 2016 Xmartlabs SRL ( 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 OperaSwift
import protocol Decodable.Decodable
import Decodable
struct Release {
let id: Int
let name: String
let tagName: String
let body: String
let user: String
}
extension Release: OperaDecodable, Decodable {
static func decode(_ json: Any) throws -> Release {
return try Release(
id: json => "id",
name: json => "name",
tagName: json => "tag_name",
body: json => "body",
user: json => ["author", "login"]
)
}
}
| mit | e2fed7c9d0f163180ba4ff5bbe46c7ea | 33.115385 | 80 | 0.697858 | 4.358722 | false | false | false | false |
kdawgwilk/KarmaAPI | Sources/App/Controllers/AuthController.swift | 1 | 1366 | import Foundation
// Vapor
import HTTP
import Vapor
// Authentication
import Turnstile
import TurnstileWeb
import TurnstileCrypto
struct AuthController {
var realm: Realm?
init(realm: Realm? = nil) {
self.realm = realm
}
/// Currently only supports Digits auth
///
/// - Parameter request: Passed from Vapor
/// - Returns: Successful login message
/// - Throws: An unauthorized error
func login(request: Request) throws -> ResponseRepresentable {
guard let digits = realm else {
throw Abort.custom(status: .unauthorized, message: "AuthController has no realm")
}
var credentials: Credentials?
guard
let urlString = request.headers["X-Auth-Service-Provider"],
let url = URL(string: urlString),
let authHeader = request.headers["X-Verify-Credentials-Authorization"],
let oauthParams = OAuthParameters(header: authHeader)
else {
throw Abort.custom(status: .unauthorized, message: "Bad Digits headers")
}
credentials = OAuthEcho(authServiceProvider: url, oauthParameters: oauthParams)
let account = try digits.authenticate(credentials: credentials!) as! DigitsAccount
try request.auth.login(account)
return try request.auth.user() as! ResponseRepresentable
}
}
| mit | 67acabcff9ef30b38b06702354705a8c | 28.695652 | 93 | 0.65959 | 4.896057 | false | false | false | false |
kelvin13/maxpng | tests/common/result.swift | 1 | 5193 | import PNG
enum Test
{
struct Failure:Swift.Error
{
let message:String
}
enum Function
{
case void( () -> Result<Void, Failure>)
// case string_int2((String, (x:Int, y:Int)) -> Result<Void, Failure>, [(String, (x:Int, y:Int))])
case string( (String) -> Result<Void, Failure>, [String])
case int( (Int) -> Result<Void, Failure>, [Int])
}
// prints an image using terminal colors
static
func terminal<T>(image rgb:[PNG.RGBA<T>], size:(x:Int, y:Int)) -> String
where T:FixedWidthInteger & UnsignedInteger
{
let downsample:Int = min(max(1, size.x / 16), max(1, size.y / 16))
return stride(from: 0, to: size.y, by: downsample).map
{
(i:Int) -> String in
stride(from: 0, to: size.x, by: downsample).map
{
(j:Int) in
// downsampling
var r:Int = 0,
g:Int = 0,
b:Int = 0
for y:Int in i ..< min(i + downsample, size.y)
{
for x:Int in j ..< min(j + downsample, size.x)
{
let c:PNG.RGBA<T> = rgb[x + y * size.x]
r += .init(c.r)
g += .init(c.g)
b += .init(c.b)
}
}
let count:Int =
(min(i + downsample, size.y) - i) *
(min(j + downsample, size.x) - j)
let color:(r:Double, g:Double, b:Double) =
(
.init(r) / (.init(T.max) * .init(count)),
.init(g) / (.init(T.max) * .init(count)),
.init(b) / (.init(T.max) * .init(count))
)
return .highlight(" ", bg: color)
}.joined()
}.joined(separator: "\n")
}
}
func test(_ function:Test.Function, cases filter:Set<String>, name:String) -> Void?
{
var successes:Int = 0
var failures:[(name:String?, message:String)] = []
switch function
{
case .void(let function):
switch function()
{
case .success:
successes += 1
case .failure(let failure):
failures.append((nil, failure.message))
}
//case .string_int2(let function, let cases):
// for arguments:(String, (x:Int, y:Int)) in cases
// {
// switch function(arguments.0, arguments.1)
// {
// case .success:
// successes += 1
// case .failure(let failure):
// failures.append(("('\(arguments.0)', \(arguments.1))", failure.message))
// }
// }
case .string(let function, let cases):
for argument:String in cases where filter.contains(argument) || filter.isEmpty
{
switch function(argument)
{
case .success:
successes += 1
case .failure(let failure):
failures.append((argument, failure.message))
}
}
case .int(let function, let cases):
for argument:Int in cases where filter.contains("\(argument)") || filter.isEmpty
{
switch function(argument)
{
case .success:
successes += 1
case .failure(let failure):
failures.append(("n = \(argument)", failure.message))
}
}
}
var width:Int
{
80
}
var white:(Double, Double, Double)
{
(1, 1, 1)
}
var red:(Double, Double, Double)
{
(1, 0.4, 0.3)
}
switch (successes, failures.count)
{
case (1, 0):
print(String.highlight(.pad(" test \(String.pad("'\(name)'", right: 30)) passed ", right: width),
bg: white))
case (let succeeded, 0):
print(String.highlight(.pad(" test \(String.pad("'\(name)'", right: 30)) passed \(String.pad("(\(succeeded)", left: 3)) cases)", right: width),
bg: white))
case (0, 1):
print(String.highlight(.pad(" test \(String.pad("'\(name)'", right: 30)) failed ", right: width),
bg: red))
case (let succeeded, let failed):
print(String.highlight(.pad(" test \(String.pad("'\(name)'", right: 30)) failed \(String.pad("(\(succeeded + failed)", left: 3)) cases, \(String.pad("\(failed)", left: 2)) failed)", right: width),
bg: red))
}
for (i, failure):(Int, (name:String?, message:String)) in failures.enumerated()
{
if let name:String = failure.name
{
print(String.highlight(" [\(String.pad("\(i)", left: 2))] case '\(name)' failed: \(failure.message)",
bg: red))
}
else
{
print(String.highlight(" [\(String.pad("\(i)", left: 2))]: \(failure.message)",
bg: red))
}
}
return failures.count > 0 ? nil : ()
}
| gpl-3.0 | 1f8fe314fe617f6a9a168a7da7dfd81b | 33.164474 | 205 | 0.452147 | 4.060203 | false | false | false | false |
ryanbooker/Swiftz | Sources/StringExt.swift | 1 | 6095 | //
// StringExt.swift
// Swiftz
//
// Created by Maxwell Swadling on 8/06/2014.
// Copyright (c) 2014 Maxwell Swadling. All rights reserved.
//
#if !XCODE_BUILD
import Operadics
import Swiftx
#endif
/// An enum representing the possible values a string can match against.
public enum StringMatcher {
/// The empty string.
case Nil
/// A cons cell.
case Cons(Character, String)
}
extension String {
/// Returns an array of strings at newlines.
public func lines() -> [String] {
return componentsSeparatedByString("\n")
}
public func componentsSeparatedByString(_ token: Character) -> [String] {
return characters.split(maxSplits: Int.max, omittingEmptySubsequences: false) { $0 == token }.map { String($0) }
}
/// Concatenates an array of strings into a single string containing
/// newlines between each element.
public static func unlines(_ xs : [String]) -> String {
return xs.reduce("", { "\($0)\($1)\n" })
}
/// Appends a character onto the front of a string.
public static func cons(head : Character, tail : String) -> String {
return String(head) + tail
}
/// Creates a string of n repeating characters.
public static func replicate(_ n : UInt, value : Character) -> String {
var l = ""
for _ in 0..<n {
l = String.cons(head: value, tail: l)
}
return l
}
/// Destructures a string. If the string is empty the result is .Nil,
/// otherwise the result is .Cons(head, tail).
public var match : StringMatcher {
if self.characters.count == 0 {
return .Nil
} else if self.characters.count == 1 {
return .Cons(self[self.startIndex], "")
}
return .Cons(self[self.startIndex], self[self.index(after: self.startIndex)..<self.endIndex])
}
/// Returns a string containing the characters of the receiver in reverse
/// order.
public func reverse() -> String {
return self.reduce(flip(curry(String.cons)), initial: "")
}
/// Maps a function over the characters of a string and returns a new string
/// of those values.
public func map(_ f : (Character) -> Character) -> String {
switch self.match {
case .Nil:
return ""
case let .Cons(hd, tl):
return String(f(hd)) + tl.map(f)
}
}
/// Removes characters from the receiver that do not satisfy a given predicate.
public func filter(_ p : (Character) -> Bool) -> String {
switch self.match {
case .Nil:
return ""
case let .Cons(x, xs):
return p(x) ? (String(x) + xs.filter(p)) : xs.filter(p)
}
}
/// Applies a binary operator to reduce the characters of the receiver to a
/// single value.
public func reduce<B>(_ f : (B) -> (Character) -> B, initial : B) -> B {
switch self.match {
case .Nil:
return initial
case let .Cons(x, xs):
return xs.reduce(f, initial: f(initial)(x))
}
}
/// Applies a binary operator to reduce the characters of the receiver to a
/// single value.
public func reduce<B>(_ f : (B, Character) -> B, initial : B) -> B {
switch self.match {
case .Nil:
return initial
case let .Cons(x, xs):
return xs.reduce(f, initial: f(initial, x))
}
}
/// Takes two lists and returns true if the first string is a prefix of the
/// second string.
public func isPrefixOf(_ r : String) -> Bool {
switch (self.match, r.match) {
case (.Cons(let x, let xs), .Cons(let y, let ys)) where (x == y):
return xs.isPrefixOf(ys)
case (.Nil, _):
return true
default:
return false
}
}
/// Takes two lists and returns true if the first string is a suffix of the
/// second string.
public func isSuffixOf(_ r : String) -> Bool {
return self.reverse().isPrefixOf(r.reverse())
}
/// Takes two lists and returns true if the first string is contained
/// entirely anywhere in the second string.
public func isInfixOf(_ r : String) -> Bool {
func tails(_ l : String) -> [String] {
return l.reduce({ x, y in
return [String.cons(head: y, tail: x.first!)] + x
}, initial: [""])
}
if let _ = tails(r).first(where: self.isPrefixOf) {
return true
}
return false
}
/// Takes two strings and drops items in the first from the second. If the
/// first string is not a prefix of the second string this function returns
/// `.none`.
public func stripPrefix(_ r : String) -> Optional<String> {
switch (self.match, r.match) {
case (.Nil, _):
return .some(r)
case (.Cons(let x, let xs), .Cons(let y, _)) where x == y:
return xs.stripPrefix(xs)
default:
return .none
}
}
/// Takes two strings and drops items in the first from the end of the
/// second. If the first string is not a suffix of the second string this
/// function returns `.none`.
public func stripSuffix(_ r : String) -> Optional<String> {
return self.reverse().stripPrefix(r.reverse()).map({ $0.reverse() })
}
}
extension String : Monoid {
public typealias M = String
public static var mempty : String {
return ""
}
public func op(_ other : String) -> String {
return self + other
}
}
public func <>(l : String, r : String) -> String {
return l + r
}
extension String /*: Functor*/ {
public typealias A = Character
public typealias B = Character
public typealias FB = String
public func fmap(_ f : (Character) -> Character) -> String {
return self.map(f)
}
}
public func <^> (_ f : (Character) -> Character, l : String) -> String {
return l.fmap(f)
}
extension String /*: Pointed*/ {
public static func pure(_ x : Character) -> String {
return String(x)
}
}
extension String /*: Applicative*/ {
public typealias FAB = [(Character) -> Character]
public func ap(_ a : [(Character) -> Character]) -> String {
return a.map(self.map).reduce("", +)
}
}
public func <*> (_ f : [((Character) -> Character)], l : String) -> String {
return l.ap(f)
}
extension String /*: Monad*/ {
public func bind(_ f : (Character) -> String) -> String {
return Array(self.characters).map(f).reduce("", +)
}
}
public func >>- (l : String, f : (Character) -> String) -> String {
return l.bind(f)
}
public func sequence(_ ms: [String]) -> [String] {
return sequence(ms.map { m in Array(m.characters) }).map(String.init(describing:))
}
| bsd-3-clause | 08ef1d74accef88cd3bbc8d99b0171ec | 25.615721 | 114 | 0.645447 | 3.26985 | false | false | false | false |
Rendel27/RDExtensionsSwift | RDExtensionsSwift/RDExtensionsSwift/Source/UIView/UIView+Mask.swift | 1 | 4007 | //
// UIView+Mask.swift
//
// Created by Giorgi Iashvili on 19.09.16.
// Copyright (c) 2016 Giorgi Iashvili
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
public extension UIView {
/// RDExtensionsSwift: Mask the receiver outside of the frame with given corner radius
func outterMask(_ frame: CGRect, cornerRadius : CGFloat = 0)
{
let layerMask = CALayer()
UIGraphicsBeginImageContextWithOptions(CGSize(width: frame.size.width, height: frame.size.height), true, 0.0);
let viewMask = UIView(frame: CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height))
viewMask.backgroundColor = UIColor.black
if let ctx = UIGraphicsGetCurrentContext()
{
viewMask.layer.render(in: ctx)
if let blackImage = UIGraphicsGetImageFromCurrentImageContext()?.cgImage
{
layerMask.contents = blackImage
layerMask.frame = frame
layerMask.cornerRadius = cornerRadius
self.layer.mask = layerMask
}
}
UIGraphicsEndImageContext()
}
/// RDExtensionsSwift: Mask the receiver inside of the frame with given corner radius
func innerMask(_ frame: CGRect, cornerRadius : CGFloat = 0)
{
UIGraphicsBeginImageContextWithOptions(CGSize(width: frame.size.width, height: frame.size.height), true, 0.0)
let blackImage : UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
UIGraphicsBeginImageContext(self.frame.size)
let context : CGContext = UIGraphicsGetCurrentContext()!
context.saveGState()
UIColor(white: 1, alpha: 0).setFill()
context.setBlendMode(.destinationIn)
blackImage.draw(in: frame, blendMode: .normal, alpha: 1)
var mergedImage : UIImage?
mergedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
mergedImage = mergedImage?.invertTransparancy()
let layerMask : CALayer = CALayer()
layerMask.contents = mergedImage?.cgImage
layerMask.frame = self.frame
layerMask.cornerRadius = cornerRadius
self.layer.mask = layerMask
}
/// RDExtensionsSwift: Mask the receiver in/out side of give frame
func mask(with rect: CGRect, inverse: Bool = false)
{
let path = UIBezierPath(rect: rect)
let maskLayer = CAShapeLayer()
if(inverse)
{
path.append(UIBezierPath(rect: self.bounds))
maskLayer.fillRule = .evenOdd
}
maskLayer.path = path.cgPath
self.layer.mask = maskLayer
}
/// RDExtensionsSwift: Remove mask from the receiver
func removeMask()
{
self.layer.mask = nil
}
/// RDExtensionsSwift: Check if the receiver is masked
var isMasked : Bool { get { return self.layer.mask != nil } }
}
| mit | 7a92cc948f1b28eabbb7cbf0092be096 | 39.887755 | 118 | 0.66858 | 4.904529 | false | false | false | false |
mercadopago/px-ios | MercadoPagoSDK/MercadoPagoSDK/Models/PXPaymentData.swift | 1 | 8258 | import UIKit
/**
Data needed for payment.
*/
@objcMembers public class PXPaymentData: NSObject, NSCopying {
var paymentMethod: PXPaymentMethod?
var issuer: PXIssuer? {
didSet {
processIssuer()
}
}
var payerCost: PXPayerCost?
var token: PXToken?
var payer: PXPayer?
var transactionAmount: NSDecimalNumber?
var transactionDetails: PXTransactionDetails?
private(set) var discount: PXDiscount?
private(set) var campaign: PXCampaign?
private(set) var consumedDiscount: Bool?
private(set) var discountDescription: PXDiscountDescription?
private let paymentTypesWithoutInstallments = [PXPaymentTypes.PREPAID_CARD.rawValue]
var paymentOptionId: String?
var amount: Double?
var taxFreeAmount: Double?
var noDiscountAmount: Double?
var transactionInfo: PXTransactionInfo?
/// :nodoc:
public func copy(with zone: NSZone? = nil) -> Any {
let copyObj = PXPaymentData()
copyObj.paymentMethod = paymentMethod
copyObj.issuer = issuer
copyObj.payerCost = payerCost
copyObj.token = token
copyObj.payerCost = payerCost
copyObj.transactionDetails = transactionDetails
copyObj.discount = discount
copyObj.campaign = campaign
copyObj.consumedDiscount = consumedDiscount
copyObj.discountDescription = discountDescription
copyObj.payer = payer
copyObj.paymentOptionId = paymentOptionId
copyObj.amount = amount
copyObj.taxFreeAmount = taxFreeAmount
copyObj.noDiscountAmount = noDiscountAmount
copyObj.transactionInfo = transactionInfo
return copyObj
}
func isComplete(shouldCheckForToken: Bool = true) -> Bool {
guard let paymentMethod = self.paymentMethod else {
return false
}
if paymentMethod.isEntityTypeRequired && payer?.entityType == nil {
return false
}
if paymentMethod.isPayerInfoRequired {
guard let identification = payer?.identification else {
return false
}
if !identification.isComplete {
return false
}
}
if paymentMethod.id == PXPaymentTypes.ACCOUNT_MONEY.rawValue || !paymentMethod.isOnlinePaymentMethod {
return true
}
if paymentMethod.isIssuerRequired && self.issuer == nil {
return false
}
if paymentMethod.isCard && payerCost == nil &&
!paymentTypesWithoutInstallments.contains(paymentMethod.paymentTypeId) {
return false
}
if paymentMethod.isDigitalCurrency && payerCost == nil {
return false
}
if paymentMethod.isCard && !hasToken() && shouldCheckForToken {
return false
}
return true
}
func hasToken() -> Bool {
return token != nil
}
func hasIssuer() -> Bool {
return issuer != nil
}
func hasPayerCost() -> Bool {
return payerCost != nil
}
func hasPaymentMethod() -> Bool {
return paymentMethod != nil
}
func hasCustomerPaymentOption() -> Bool {
return hasPaymentMethod() && (self.paymentMethod!.isAccountMoney || (hasToken() && !String.isNullOrEmpty(self.token!.cardId)))
}
}
// MARK: Getters
extension PXPaymentData {
/**
getToken
*/
public func getToken() -> PXToken? {
return token
}
/**
getPayerCost
*/
public func getPayerCost() -> PXPayerCost? {
return payerCost
}
/**
getNumberOfInstallments
*/
public func getNumberOfInstallments() -> Int {
guard let installments = payerCost?.installments else {
return 0
}
return installments
}
/**
getIssuer
*/
public func getIssuer() -> PXIssuer? {
return issuer
}
/**
getPayer
*/
public func getPayer() -> PXPayer? {
return payer
}
/**
getPaymentMethod
*/
public func getPaymentMethod() -> PXPaymentMethod? {
return paymentMethod
}
/**
getDiscount
*/
public func getDiscount() -> PXDiscount? {
return discount
}
/**
getRawAmount
*/
public func getRawAmount() -> NSDecimalNumber? {
return transactionAmount
}
/**
backend payment_option amount
*/
public func getAmount() -> Double? {
return amount
}
/**
backend paymentt_option tax_free_amount
*/
public func getTaxFreeAmount() -> Double? {
return taxFreeAmount
}
/**
backend paymentt_option no_discount_amount
*/
public func getNoDiscountAmount() -> Double? {
return noDiscountAmount
}
func getTransactionAmountWithDiscount() -> Double? {
if let transactionAmount = transactionAmount {
let transactionAmountDouble = transactionAmount.doubleValue
if let discount = discount {
return transactionAmountDouble - discount.couponAmount
} else {
return transactionAmountDouble
}
}
return nil
}
public func getTransactionInfo() -> PXTransactionInfo? {
return transactionInfo
}
}
// MARK: Setters
extension PXPaymentData {
func setDiscount(_ discount: PXDiscount?, withCampaign campaign: PXCampaign, consumedDiscount: Bool, discountDescription: PXDiscountDescription? = nil) {
self.discount = discount
self.campaign = campaign
self.consumedDiscount = consumedDiscount
self.discountDescription = discountDescription
}
func updatePaymentDataWith(paymentMethod: PXPaymentMethod?) {
guard let paymentMethod = paymentMethod else {
return
}
cleanIssuer()
cleanToken()
cleanPayerCost()
cleanPaymentOptionId()
self.paymentMethod = paymentMethod
}
func updatePaymentDataWith(paymentMethod: PXPaymentMethod?, paymentOptionId: String?) {
guard let paymentMethod = paymentMethod else {
return
}
cleanIssuer()
cleanToken()
cleanPayerCost()
cleanPaymentOptionId()
self.paymentMethod = paymentMethod
self.paymentOptionId = paymentOptionId
}
func updatePaymentDataWith(token: PXToken?) {
guard let token = token else {
return
}
self.token = token
}
func updatePaymentDataWith(payerCost: PXPayerCost?) {
guard let payerCost = payerCost else {
return
}
self.payerCost = payerCost
}
func updatePaymentDataWith(issuer: PXIssuer?) {
guard let issuer = issuer else {
return
}
cleanPayerCost()
self.issuer = issuer
}
func updatePaymentDataWith(payer: PXPayer?) {
guard let payer = payer else {
return
}
self.payer = payer
}
}
// MARK: Clears
extension PXPaymentData {
func cleanToken() {
self.token = nil
}
func cleanPayerCost() {
self.payerCost = nil
}
func cleanIssuer() {
self.issuer = nil
}
func cleanPaymentMethod() {
self.paymentMethod = nil
}
func cleanPaymentOptionId() {
self.paymentOptionId = nil
}
func clearCollectedData() {
clearPaymentMethodData()
clearPayerData()
}
func clearPaymentMethodData() {
self.paymentMethod = nil
self.issuer = nil
self.payerCost = nil
self.token = nil
self.transactionDetails = nil
self.paymentOptionId = nil
// No borrar el descuento
}
func clearPayerData() {
self.payer = self.payer?.copy() as? PXPayer
self.payer?.clearCollectedData()
}
func clearDiscount() {
self.discount = nil
self.campaign = nil
self.consumedDiscount = nil
self.discountDescription = nil
}
}
// MARK: Private
extension PXPaymentData {
private func processIssuer() {
if let newIssuer = issuer, newIssuer.id.isEmpty {
cleanIssuer()
}
}
}
| mit | 89c98718cfba76d6ceabdb7dba43fe98 | 23.873494 | 157 | 0.603778 | 4.950839 | false | false | false | false |
GetZero/-Swift-LeetCode | LeetCode/SingleNumber.swift | 1 | 775 | //
// SingleNumber.swift
// LeetCode
//
// Created by 韦曲凌 on 2016/11/8.
// Copyright © 2016年 Wake GetZero. All rights reserved.
//
import Foundation
class SingleNumber: NSObject {
func singleNumber(_ nums: [Int]) -> Int {
var map: [String: Int] = [:]
for num in nums {
let numStr = "\(num)"
if let value = map[numStr] {
map.updateValue(value + 1, forKey: numStr)
} else {
map.updateValue(1, forKey: numStr)
}
}
for key in map.keys {
if let value = map[key] {
if value == 1 {
return Int(key)!
}
}
}
return 0
}
}
| apache-2.0 | f8037f900bc7dd672fd521d08941c2f1 | 20.277778 | 58 | 0.436031 | 4.096257 | false | false | false | false |
apple/swift-nio-ssl | Sources/NIOSSL/ByteBufferBIO.swift | 1 | 17496 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIOCore
@_implementationOnly import CNIOBoringSSL
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin.C
#elseif os(Linux) || os(FreeBSD) || os(Android)
import Glibc
#else
#error("unsupported os")
#endif
/// The BoringSSL entry point to write to the `ByteBufferBIO`. This thunk unwraps the user data
/// and then passes the call on to the specific BIO reference.
///
/// This specific type signature is annoying (I'd rather have UnsafeRawPointer, and rather than a separate
/// len I'd like a buffer pointer), but this interface is required because this is passed to an BoringSSL
/// function pointer and so needs to be @convention(c).
internal func boringSSLBIOWriteFunc(bio: UnsafeMutablePointer<BIO>?, buf: UnsafePointer<CChar>?, len: CInt) -> CInt {
guard let concreteBIO = bio, let concreteBuf = buf else {
preconditionFailure("Invalid pointers in boringSSLBIOWriteFunc: bio: \(String(describing: bio)) buf: \(String(describing: buf))")
}
// This unwrap may fail if the user has dropped the ref to the ByteBufferBIO but still has
// a ref to the other pointer. Sigh heavily and just fail.
guard let userPtr = CNIOBoringSSL_BIO_get_data(concreteBIO) else {
return -1
}
// Begin by clearing retry flags. We do this at all BoringSSL entry points.
CNIOBoringSSL_BIO_clear_retry_flags(concreteBIO)
// In the event a write of 0 bytes has been asked for, just return early, don't bother with the other work.
guard len > 0 else {
return 0
}
let swiftBIO: ByteBufferBIO = Unmanaged.fromOpaque(userPtr).takeUnretainedValue()
let bufferPtr = UnsafeRawBufferPointer(start: concreteBuf, count: Int(len))
return swiftBIO.sslWrite(buffer: bufferPtr)
}
/// The BoringSSL entry point to read from the `ByteBufferBIO`. This thunk unwraps the user data
/// and then passes the call on to the specific BIO reference.
///
/// This specific type signature is annoying (I'd rather have UnsafeRawPointer, and rather than a separate
/// len I'd like a buffer pointer), but this interface is required because this is passed to an BoringSSL
/// function pointer and so needs to be @convention(c).
internal func boringSSLBIOReadFunc(bio: UnsafeMutablePointer<BIO>?, buf: UnsafeMutablePointer<CChar>?, len: CInt) -> CInt {
guard let concreteBIO = bio, let concreteBuf = buf else {
preconditionFailure("Invalid pointers in boringSSLBIOReadFunc: bio: \(String(describing: bio)) buf: \(String(describing: buf))")
}
// This unwrap may fail if the user has dropped the ref to the ByteBufferBIO but still has
// a ref to the other pointer. Sigh heavily and just fail.
guard let userPtr = CNIOBoringSSL_BIO_get_data(concreteBIO) else {
return -1
}
// Begin by clearing retry flags. We do this at all BoringSSL entry points.
CNIOBoringSSL_BIO_clear_retry_flags(concreteBIO)
// In the event a read for 0 bytes has been asked for, just return early, don't bother with the other work.
guard len > 0 else {
return 0
}
let swiftBIO: ByteBufferBIO = Unmanaged.fromOpaque(userPtr).takeUnretainedValue()
let bufferPtr = UnsafeMutableRawBufferPointer(start: concreteBuf, count: Int(len))
return swiftBIO.sslRead(buffer: bufferPtr)
}
/// The BoringSSL entry point for `puts`. This is a silly function, so we're just going to implement it
/// in terms of write.
///
/// This specific type signature is annoying (I'd rather have UnsafeRawPointer, and rather than a separate
/// len I'd like a buffer pointer), but this interface is required because this is passed to an BoringSSL
/// function pointer and so needs to be @convention(c).
internal func boringSSLBIOPutsFunc(bio: UnsafeMutablePointer<BIO>?, buf: UnsafePointer<CChar>?) -> CInt {
guard let concreteBIO = bio, let concreteBuf = buf else {
preconditionFailure("Invalid pointers in boringSSLBIOPutsFunc: bio: \(String(describing: bio)) buf: \(String(describing: buf))")
}
return boringSSLBIOWriteFunc(bio: concreteBIO, buf: concreteBuf, len: CInt(strlen(concreteBuf)))
}
/// The BoringSSL entry point for `gets`. This is a *really* silly function and we can't implement it nicely
/// in terms of read, so we just refuse to support it.
///
/// This specific type signature is annoying (I'd rather have UnsafeRawPointer, and rather than a separate
/// len I'd like a buffer pointer), but this interface is required because this is passed to an BoringSSL
/// function pointer and so needs to be @convention(c).
internal func boringSSLBIOGetsFunc(bio: UnsafeMutablePointer<BIO>?, buf: UnsafeMutablePointer<CChar>?, len: CInt) -> CInt {
return -2
}
/// The BoringSSL entry point for `BIO_ctrl`. We don't support most of these.
internal func boringSSLBIOCtrlFunc(bio: UnsafeMutablePointer<BIO>?, cmd: CInt, larg: CLong, parg: UnsafeMutableRawPointer?) -> CLong {
switch cmd {
case BIO_CTRL_GET_CLOSE:
return CLong(CNIOBoringSSL_BIO_get_shutdown(bio))
case BIO_CTRL_SET_CLOSE:
CNIOBoringSSL_BIO_set_shutdown(bio, CInt(larg))
return 1
case BIO_CTRL_FLUSH:
return 1
default:
return 0
}
}
internal func boringSSLBIOCreateFunc(bio: UnsafeMutablePointer<BIO>?) -> CInt {
return 1
}
internal func boringSSLBIODestroyFunc(bio: UnsafeMutablePointer<BIO>?) -> CInt {
return 1
}
/// An BoringSSL BIO object that wraps `ByteBuffer` objects.
///
/// BoringSSL extensively uses an abstraction called `BIO` to manage its input and output
/// channels. For NIO we want a BIO that operates entirely in-memory, and it's tempting
/// to assume that BoringSSL's `BIO_s_mem` is the best choice for that. However, ultimately
/// `BIO_s_mem` is a flat memory buffer that we end up using as a staging between one
/// `ByteBuffer` of plaintext and one of ciphertext. We'd like to cut out that middleman.
///
/// For this reason, we want to create an object that implements the `BIO` abstraction
/// but which use `ByteBuffer`s to do so. This allows us to avoid unnecessary memory copies,
/// which can be a really large win.
final class ByteBufferBIO {
/// The unsafe pointer to the BoringSSL BIO_METHOD.
///
/// This is used to give BoringSSL pointers to the methods that need to be invoked when
/// using a ByteBufferBIO. There will only ever be one value of this in a NIO program,
/// and it will always be non-NULL. Failure to initialize this structure is fatal to
/// the program.
private static let boringSSLBIOMethod: UnsafeMutablePointer<BIO_METHOD> = {
guard boringSSLIsInitialized else {
preconditionFailure("Failed to initialize BoringSSL")
}
let bioType = CNIOBoringSSL_BIO_get_new_index() | BIO_TYPE_SOURCE_SINK
guard let method = CNIOBoringSSL_BIO_meth_new(bioType, "ByteBuffer BIO") else {
preconditionFailure("Unable to allocate new BIO_METHOD")
}
CNIOBoringSSL_BIO_meth_set_write(method, boringSSLBIOWriteFunc)
CNIOBoringSSL_BIO_meth_set_read(method, boringSSLBIOReadFunc)
CNIOBoringSSL_BIO_meth_set_puts(method, boringSSLBIOPutsFunc)
CNIOBoringSSL_BIO_meth_set_gets(method, boringSSLBIOGetsFunc)
CNIOBoringSSL_BIO_meth_set_ctrl(method, boringSSLBIOCtrlFunc)
CNIOBoringSSL_BIO_meth_set_create(method, boringSSLBIOCreateFunc)
CNIOBoringSSL_BIO_meth_set_destroy(method, boringSSLBIODestroyFunc)
return method
}()
/// Pointer to the backing BoringSSL BIO object.
///
/// Generally speaking BoringSSL wants to own the object initialization logic for a BIO.
/// This doesn't work for us, because we'd like to ensure that the `ByteBufferBIO` is
/// correctly initialized with all the state it needs. One of those bits of state is
/// a `ByteBuffer`, which BoringSSL cannot give us, so we need to build our `ByteBufferBIO`
/// *first* and then use that to drive `BIO` initialization.
///
/// Because of this split initialization dance, we elect to initialize this data structure,
/// and have it own building an BoringSSL `BIO` structure.
private let bioPtr: UnsafeMutablePointer<BIO>
/// The buffer of bytes received from the network.
///
/// By default, `ByteBufferBIO` expects to pass data directly to BoringSSL whenever it
/// is received. It is, in essence, a temporary container for a `ByteBuffer` on the
/// read side. This provides a powerful optimisation, which is that the read buffer
/// passed to the `NIOSSLHandler` can be re-used immediately upon receipt. Given that
/// the `NIOSSLHandler` is almost always the first handler in the pipeline, this greatly
/// improves the allocation profile of busy connections, which can more-easily re-use
/// the receive buffer.
private var inboundBuffer: ByteBuffer?
/// The buffer of bytes to send to the network.
///
/// While on the read side `ByteBufferBIO` expects to hold each bytebuffer only temporarily,
/// on the write side we attempt to coalesce as many writes as possible. This is because a
/// buffer can only be re-used if it is flushed to the network, and that can only happen
/// on flush calls, so we are incentivised to write as many SSL_write calls into one buffer
/// as possible.
private var outboundBuffer: ByteBuffer
/// Whether the outbound buffer should be cleared before writing.
///
/// This is true only if we've flushed the buffer to the network. Rather than track an annoying
/// boolean for this, we use a quick check on the properties of the buffer itself. This clear
/// wants to be delayed as long as possible to maximise the possibility that it does not
/// trigger an allocation.
private var mustClearOutboundBuffer: Bool {
return outboundBuffer.readerIndex == outboundBuffer.writerIndex && outboundBuffer.readerIndex > 0
}
init(allocator: ByteBufferAllocator) {
// We allocate enough space for a single TLS record. We may not actually write a record that size, but we want to
// give ourselves the option. We may also write more data than that: if we do, the ByteBuffer will just handle it.
self.outboundBuffer = allocator.buffer(capacity: SSL_MAX_RECORD_SIZE)
guard let bio = CNIOBoringSSL_BIO_new(ByteBufferBIO.boringSSLBIOMethod) else {
preconditionFailure("Unable to initialize custom BIO")
}
// We now need to complete the BIO initialization. The BIO takes an owned reference to self here,
// which is broken on close().
self.bioPtr = bio
CNIOBoringSSL_BIO_set_data(self.bioPtr, Unmanaged.passRetained(self).toOpaque())
CNIOBoringSSL_BIO_set_init(self.bioPtr, 1)
CNIOBoringSSL_BIO_set_shutdown(self.bioPtr, 1)
}
deinit {
// In debug mode we assert that we've been closed.
assert(CNIOBoringSSL_BIO_get_data(self.bioPtr) == nil, "must call close() on ByteBufferBIO before deinit")
// On deinit we need to drop our reference to the BIO.
CNIOBoringSSL_BIO_free(self.bioPtr)
}
/// Shuts down the BIO, rendering it unable to be used.
///
/// This method is idempotent: it is safe to call more than once.
internal func close() {
guard let selfRef = CNIOBoringSSL_BIO_get_data(self.bioPtr) else {
// Shutdown is safe to call more than once.
return
}
// We consume the original retain of self, and then nil out the ref in the BIO so that this can't happen again.
Unmanaged<ByteBufferBIO>.fromOpaque(selfRef).release()
CNIOBoringSSL_BIO_set_data(self.bioPtr, nil)
}
/// Obtain an owned pointer to the backing BoringSSL BIO object.
///
/// This pointer is safe to use elsewhere, as it has increased the reference to the backing
/// `BIO`. This makes it safe to use with BoringSSL functions that require an owned reference
/// (that is, that consume a reference count).
///
/// Note that the BIO may not remain useful for long periods of time: if the `ByteBufferBIO`
/// object that owns the BIO goes out of scope, the BIO will have its pointers invalidated
/// and will no longer be able to send/receive data.
internal func retainedBIO() -> UnsafeMutablePointer<BIO> {
CNIOBoringSSL_BIO_up_ref(self.bioPtr)
return self.bioPtr
}
/// Called to obtain the outbound ciphertext written by BoringSSL.
///
/// This function obtains a buffer of ciphertext that needs to be written to the network. In a
/// normal application, this should be obtained on a call to `flush`. If no bytes have been flushed
/// to the network, then this call will return `nil` rather than an empty byte buffer, to help signal
/// that the `write` call should be elided.
///
/// - returns: A buffer of ciphertext to send to the network, or `nil` if no buffer is available.
func outboundCiphertext() -> ByteBuffer? {
guard self.outboundBuffer.readableBytes > 0 else {
// No data to send.
return nil
}
/// Once we return from this function, we want to account for the bytes we've handed off.
defer {
self.outboundBuffer.moveReaderIndex(to: self.outboundBuffer.writerIndex)
}
return self.outboundBuffer
}
/// Stores a buffer received from the network for delivery to BoringSSL.
///
/// Whenever a buffer is received from the network, it is passed to the BIO via this function
/// call. In almost all cases this BIO should be immediately consumed by BoringSSL, but in some cases
/// it may not be. In those cases, additional calls will cause byte-by-byte copies. This should
/// be avoided, but usually only happens during asynchronous certificate verification in the
/// handshake.
///
/// - parameters:
/// - buffer: The buffer of ciphertext bytes received from the network.
func receiveFromNetwork(buffer: ByteBuffer) {
var buffer = buffer
if self.inboundBuffer == nil {
self.inboundBuffer = buffer
} else {
self.inboundBuffer!.writeBuffer(&buffer)
}
}
/// Retrieves any inbound data that has not been processed by BoringSSL.
///
/// When unwrapping TLS from a connection, there may be application bytes that follow the terminating
/// CLOSE_NOTIFY message. Those bytes may be in the buffer passed to this BIO, and so we need to
/// retrieve them.
///
/// This function extracts those bytes and returns them to the user, and drops the reference to them
/// in this BIO.
///
/// - returns: The unconsumed `ByteBuffer`, if any.
func evacuateInboundData() -> ByteBuffer? {
defer {
self.inboundBuffer = nil
}
return self.inboundBuffer
}
/// BoringSSL has requested to read ciphertext bytes from the network.
///
/// This function is invoked whenever BoringSSL is looking to read data.
///
/// - parameters:
/// - buffer: The buffer for NIO to copy bytes into.
/// - returns: The number of bytes we have copied.
fileprivate func sslRead(buffer: UnsafeMutableRawBufferPointer) -> CInt {
guard var inboundBuffer = self.inboundBuffer else {
// We have no bytes to read. Mark this as "needs read retry".
CNIOBoringSSL_BIO_set_retry_read(self.bioPtr)
return -1
}
let bytesToCopy = min(buffer.count, inboundBuffer.readableBytes)
_ = inboundBuffer.readWithUnsafeReadableBytes { bytePointer in
assert(bytePointer.count >= bytesToCopy, "Copying more bytes (\(bytesToCopy)) than fits in readable bytes \((bytePointer.count))")
assert(buffer.count >= bytesToCopy, "Copying more bytes (\(bytesToCopy) than contained in source buffer (\(buffer.count))")
buffer.baseAddress!.copyMemory(from: bytePointer.baseAddress!, byteCount: bytesToCopy)
return bytesToCopy
}
// If we have read all the bytes from the inbound buffer, nil it out.
if inboundBuffer.readableBytes > 0 {
self.inboundBuffer = inboundBuffer
} else {
self.inboundBuffer = nil
}
return CInt(bytesToCopy)
}
/// BoringSSL has requested to write ciphertext bytes from the network.
///
/// - parameters:
/// - buffer: The buffer for NIO to copy bytes from.
/// - returns: The number of bytes we have copied.
fileprivate func sslWrite(buffer: UnsafeRawBufferPointer) -> CInt {
if self.mustClearOutboundBuffer {
// We just flushed, and this is a new write. Let's clear the buffer now.
self.outboundBuffer.clear()
assert(!self.mustClearOutboundBuffer)
}
let writtenBytes = self.outboundBuffer.writeBytes(buffer)
return CInt(writtenBytes)
}
}
| apache-2.0 | b08d8815fc1bc7ff5d399e1889e8ee4a | 45.656 | 142 | 0.686557 | 4.449644 | false | false | false | false |
KeithPiTsui/Pavers | Pavers/Sources/CryptoSwift/Array+Extensions.swift | 2 | 2629 | //
// Array+Extensions.swift
// CryptoSwift
//
// Copyright (C) 2014-2017 Marcin Krzyżanowski <[email protected]>
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
//
// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
// - This notice may not be removed or altered from any source or binary distribution.
//
public extension Array where Element == UInt8 {
public func toHexString() -> String {
return `lazy`.reduce("") {
var s = String($1, radix: 16)
if s.count == 1 {
s = "0" + s
}
return $0 + s
}
}
}
public extension Array where Element == UInt8 {
public func md5() -> [Element] {
return Digest.md5(self)
}
public func sha1() -> [Element] {
return Digest.sha1(self)
}
public func sha224() -> [Element] {
return Digest.sha224(self)
}
public func sha256() -> [Element] {
return Digest.sha256(self)
}
public func sha384() -> [Element] {
return Digest.sha384(self)
}
public func sha512() -> [Element] {
return Digest.sha512(self)
}
public func sha2(_ variant: SHA2.Variant) -> [Element] {
return Digest.sha2(self, variant: variant)
}
public func sha3(_ variant: SHA3.Variant) -> [Element] {
return Digest.sha3(self, variant: variant)
}
public func crc32(seed: UInt32? = nil, reflect: Bool = true) -> UInt32 {
return Checksum.crc32(self, seed: seed, reflect: reflect)
}
public func crc16(seed: UInt16? = nil) -> UInt16 {
return Checksum.crc16(self, seed: seed)
}
public func encrypt(cipher: Cipher) throws -> [Element] {
return try cipher.encrypt(slice)
}
public func decrypt(cipher: Cipher) throws -> [Element] {
return try cipher.decrypt(slice)
}
public func authenticate<A: Authenticator>(with authenticator: A) throws -> [Element] {
return try authenticator.authenticate(self)
}
}
| mit | 9854bbc3562630e62743d300ed120693 | 30.662651 | 217 | 0.641172 | 4.068111 | false | false | false | false |
Codility-BMSTU/Codility | Codility/Codility/OBSegueRouter.swift | 1 | 471 | //
// OBSegueRouter.swift
// Codility
//
// Created by Кирилл Володин on 16.09.17.
// Copyright © 2017 Кирилл Володин. All rights reserved.
//
import Foundation
struct OBSegueRouter {
static let toTransfer = "toTransfer"
static let toQuests = "toQuests"
static let toATMOutlets = "toATMOutlets"
static let toCardPicker = "toCardPicker"
static let toQRSCan = "toQRSCan"
static let toCreateQR = "toCreateQR"
}
| apache-2.0 | 56f67f637bdbfff7571221f1cc9cb903 | 21.2 | 57 | 0.693694 | 3.083333 | false | false | false | false |
bigL055/Routable | Example/Pods/SPKit/Sources/UIViewController/SP+UIViewController.swift | 1 | 5333 | //
// SPKit
//
// Copyright (c) 2017 linhay - https:// github.com/linhay
//
// 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
import UIKit
public extension BLExtension where Base: UIViewController {
/// tabbarHeight高度
public var tabbarHeight: CGFloat {
return base.tabBarController?.tabBar.bounds.height ?? 0
}
/// 能否回退
public var canback: Bool {
return (base.navigationController?.viewControllers.count ?? 0) > 1
}
}
public extension BLExtension where Base: UIViewController {
public var isByPresented: Bool {
guard base.navigationController != nil else { return false }
guard base.navigationController!.viewControllers.count > 0 else { return false }
guard base.presentingViewController == nil else { return false }
return true
}
/// 是否是当前显示控制器
public var isVisible: Bool {
func find(rawVC: UIViewController) -> UIViewController {
switch rawVC {
case let nav as UINavigationController:
guard let vc = nav.viewControllers.last else { return rawVC }
return find(rawVC: vc)
case let tab as UITabBarController:
guard let vc = tab.selectedViewController else { return rawVC }
return find(rawVC: vc)
case let vc where vc.presentedViewController != nil:
return find(rawVC: vc.presentedViewController!)
default:
return rawVC
}
}
guard let rootViewController = UIApplication.shared.windows.filter({ (item) -> Bool in
/// =.=,如果没手动设置的话...
return item.windowLevel == 0.0 && item.isKeyWindow
}).first?.rootViewController else {
return false
}
let vc = find(rawVC: rootViewController)
return vc == base || vc.tabBarController == base || vc.navigationController == base
}
/// 前进至指定控制器
///
/// - Parameters:
/// - vc: 指定控制器
/// - isRemove: 前进后是否移除当前控制器
/// - animated: 是否显示动画
public func push(vc: UIViewController?,
isRemove: Bool = false,
animated: Bool = true) {
guard let vc = vc else { return }
switch base {
case let nav as UINavigationController:
nav.pushViewController(vc, animated: animated)
default:
base.navigationController?.pushViewController(vc, animated: animated)
if isRemove {
guard let vcs = base.navigationController?.viewControllers else{ return }
guard let flags = vcs.index(of: base.self) else { return }
base.navigationController?.viewControllers.remove(at: flags)
}
}
}
/// modal 指定控制器
///
/// - Parameters:
/// - vc: 指定控制器
/// - animated: 是否显示动画
/// - completion: 完成后事件
func present(vc: UIViewController?,
animated: Bool = true,
completion: (() -> Void)? = nil) {
guard let vc = vc else { return }
base.present(vc, animated: animated, completion: completion)
}
/// 后退一层控制器
///
/// - Parameter animated: 是否显示动画
/// - Returns: vc
@discardableResult public func pop(animated: Bool) -> UIViewController? {
switch base {
case let nav as UINavigationController:
return nav.popViewController(animated: animated)
default:
return base.navigationController?.popViewController(animated: animated)
}
}
/// 后退至指定控制器
///
/// - Parameters:
/// - vc: 指定控制器
/// - animated: 是否显示动画
/// - Returns: vcs
@discardableResult public func pop(vc: UIViewController, animated: Bool) -> [UIViewController]? {
switch base {
case let nav as UINavigationController:
return nav.popToViewController(vc, animated: animated)
default:
return base.navigationController?.popToViewController(vc, animated: animated)
}
}
/// 后退至根控制器
///
/// - Parameter animated: 是否显示动画
/// - Returns: vcs
@discardableResult public func pop(toRootVC animated: Bool) -> [UIViewController]? {
if let vc = base as? UINavigationController {
return vc.popToRootViewController(animated: animated)
}else{
return base.navigationController?.popToRootViewController(animated: animated)
}
}
}
| mit | 33f3b56aaf6193aeff938eeed366a35f | 32.701987 | 99 | 0.671448 | 4.448427 | false | false | false | false |
emilstahl/swift | validation-test/compiler_crashers_fixed/1297-swift-type-walk.swift | 13 | 637 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func ^(r: l, k) -> k {
? {
h (s : t?) q u {
g let d = s {
}
}
e}
let u : [Int?] = [n{
c v: j t.v == m>(n: o<t>) {
}
}
class a<f : g, g : g where f.f == g> {
}
protocol g {
typealias f
}
struct c<h : g> : g {
typealias e = a<c<h>, f>
func r<t>() {
f f {
}
}
struct i<o : u> {
}
func r<o>() -> [i<o>] {
}
class g<t : g> {
}
class g: g {
}
class n : h {
}
func i() -> l func o() -> m {
}
class d<c>: NSObject {
}
func c<b:c
| apache-2.0 | 618e1a37a2faf68f8925b3ce297eadee | 13.813953 | 87 | 0.535322 | 2.299639 | false | false | false | false |
marko628/Playground | Protocols.playground/Contents.swift | 1 | 980 | // Protocol practice stuff for UIKit Fundamentals
// Lesson 2
import UIKit
// Protocol Definitions
protocol FullyNamed {
var fullName: String {get set}
}
protocol RandomNumberGenerator {
func random() -> Int
}
// SomeProgrammer: adopts and conforms to both protocols
class SomeProgrammer: FullyNamed, RandomNumberGenerator {
var fullName: String
var favoriteNumber: Int!
init(name: String!) {
self.fullName = name
self.favoriteNumber = self.random()
}
func random() -> Int {
return 42
}
func setFavoriteNumber() {
self.favoriteNumber = self.favoriteNumber + 1
}
}
let Mark = SomeProgrammer(name: "Mark A. Nolte")
Mark.fullName
Mark.random()
Mark.fullName = "Mark Andrews Nolte"
Mark.fullName
Mark.favoriteNumber
let Beaux = SomeProgrammer(name: "Beaux Dog")
Beaux.favoriteNumber
Beaux.random()
Beaux.fullName
Beaux.setFavoriteNumber()
Beaux.setFavoriteNumber()
Beaux.favoriteNumber
| mit | 774a48d989f21b626801a56e85569c8c | 17.846154 | 57 | 0.7 | 3.904382 | false | false | false | false |
theappbusiness/TABResourceLoader | Sources/TABResourceLoader/Services/NetworkDataResourceService.swift | 1 | 4601 | //
// NetworkDataResourceService.swift
// TABResourceLoader
//
// Created by Luciano Marisi on 05/07/2016.
//
// The MIT License (MIT)
//
// Copyright (c) 2016 Kin + Carta
//
// 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
/// Enum representing an error from a network service
///
/// - couldNotCreateURLRequest: The URL request could not be formed
/// - noHTTPURLResponse: No HTTPURLResponse exists
/// - sessionError: The networking error returned by the URLSession
/// - statusCodeError: A status code error between 400 and 600 (not including 600) was returned
/// - noDataProvided: No data was returned
/// - statusCodeCustomError: Contains the custom error for failed status code
public enum NetworkServiceError: Error {
case couldNotCreateURLRequest
case noHTTPURLResponse
case sessionError(error: Error)
case statusCodeError(statusCode: Int)
case noDataProvided
case statusCodeCustomError(statusCode: Int, error: Error)
case parsingModel(error: Error)
}
/// Object used to retrive types that conform to both @NetworkResourceType and DataResourceType
open class NetworkDataResourceService {
/**
Method designed to be implemented on subclasses, these fields will be overriden by any HTTP header field
key that is defined in the resource (in case of conflicts)
- returns: Return any additional header fields that need to be added to the url request
*/
open func additionalHeaderFields() -> [String: String] {
return [:]
}
let session: URLSessionType
/**
Designated initializer for NetworkDataResourceService
- parameter session: The session that will be used to make network requests.
- returns: An new instance
*/
public init(session: URLSessionType = URLSession.shared) {
self.session = session
}
deinit {
session.invalidateAndCancel()
}
/**
Fetches a resource conforming to both NetworkResourceType & DataResourceType
- parameter resource: The resource to fetch
- parameter completion: A completion handler called with a Result type of the fetching computation
*/
@discardableResult
open func fetch<Resource: NetworkResourceType & DataResourceType>(resource: Resource, completion: @escaping (NetworkResponse<Resource.Model>) -> Void) -> Cancellable? {
let cancellable = fetch(resource: resource, networkServiceActivity: NetworkServiceActivity.shared, completion: completion)
return cancellable
}
// Method used for injecting the NetworkServiceActivity for testing
@discardableResult
func fetch<Resource: NetworkResourceType & DataResourceType>(resource: Resource, networkServiceActivity: NetworkServiceActivity, completion: @escaping (NetworkResponse<Resource.Model>) -> Void) -> Cancellable? {
guard var urlRequest = resource.urlRequest() else {
completion(.failure(.couldNotCreateURLRequest, nil))
return nil
}
urlRequest.allHTTPHeaderFields = merge(additionalHeaderFields(), urlRequest.allHTTPHeaderFields)
networkServiceActivity.increaseActiveRequest()
let cancellable = session.perform(request: urlRequest) { (data, URLResponse, error) in
networkServiceActivity.decreaseActiveRequest()
let result = NetworkResponseHandler.resultFrom(resource: resource, data: data, URLResponse: URLResponse, error: error)
completion(result)
}
return cancellable
}
/**
Cancels all requests associated with this service's session
*/
open func cancelAllRequests() {
session.cancelAllRequests()
}
}
| mit | 92a5725d984b7189dd2e26333f6f3d79 | 38.663793 | 213 | 0.745055 | 4.853376 | false | false | false | false |
ingopaulsen/MovingHelper | MovingHelper/Extensions/SafeDictionaryExtension.swift | 22 | 2005 | //
// SafeDictionaryExtension.swift
// MovingHelper
//
// Created by Ellen Shapiro on 6/7/15.
// Copyright (c) 2015 Razeware. All rights reserved.
//
import Foundation
/**
An extension to facilitate getting type-safe data out of an NSDictionary.
Inspired by Erica Sadun and Mike Ash (though for some reason I can't get
this to work with subscript):
http://ericasadun.com/2015/06/01/swift-safe-array-indexing-my-favorite-thing-of-the-new-week/
*/
public extension NSDictionary {
/**
Checks a dictionary for a value for a given key, and returns either its
String value or an empty string.
- parameter key:: The key to use to check the dictionary
- returns: The found string, or an empty string if it was not found.
*/
public func safeString(key: String) -> String {
//Is there a value for the key?
if let item: AnyObject = self[key] {
//Is that value a string?
if let string = item as? String {
return string
}
}
//Fall-through case
return ""
}
/**
Checks a dictionary for a value for a given key, and returns either its
integer value or zero.
- parameter key:: The key to use to check the dictionary
- returns: The found number, or zero if it was not found.
*/
public func safeInt(key: String) -> Int {
//Is there a value for the key?
if let item: AnyObject = self[key] {
if let number = item as? NSNumber {
return number.integerValue
}
}
return 0
}
/**
Checks a dictionary for a value for a given key, and returns either its
boolean value or false.
- parameter key:: The key to use to check the dictionary
- returns: The found boolean value, or false if it was not found.
*/
public func safeBoolean(key:String) -> Bool {
//Is there a value for the key?
if let item: AnyObject = self[key] {
if let number = item as? NSNumber {
return number.boolValue
}
}
//Fall-through case
return false
}
}
| mit | b593093de3b03cf6f671b633f84e2fb4 | 24.705128 | 93 | 0.653367 | 3.954635 | false | false | false | false |
ForrestAlfred/firefox-ios | Providers/Profile.swift | 1 | 25820 | /* 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 Account
import ReadingList
import Shared
import Storage
import Sync
import XCGLogger
// TODO: same comment as for SyncAuthState.swift!
private let log = XCGLogger.defaultInstance()
public protocol SyncManager {
func syncClients() -> SyncResult
func syncClientsThenTabs() -> SyncResult
func syncHistory() -> SyncResult
func syncLogins() -> SyncResult
// The simplest possible approach.
func beginTimedSyncs()
func endTimedSyncs()
func onRemovedAccount(account: FirefoxAccount?) -> Success
func onAddedAccount() -> Success
}
typealias EngineIdentifier = String
typealias SyncFunction = (SyncDelegate, Prefs, Ready) -> SyncResult
class ProfileFileAccessor: FileAccessor {
init(profile: Profile) {
let profileDirName = "profile.\(profile.localName())"
// Bug 1147262: First option is for device, second is for simulator.
var rootPath: String?
if let sharedContainerIdentifier = ExtensionUtils.sharedContainerIdentifier(), url = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier(sharedContainerIdentifier), path = url.path {
rootPath = path
} else {
log.error("Unable to find the shared container. Defaulting profile location to ~/Documents instead.")
rootPath = String(NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! NSString)
}
super.init(rootPath: rootPath!.stringByAppendingPathComponent(profileDirName))
}
}
class CommandStoringSyncDelegate: SyncDelegate {
let profile: Profile
init() {
profile = BrowserProfile(localName: "profile", app: nil)
}
func displaySentTabForURL(URL: NSURL, title: String) {
if let urlString = URL.absoluteString {
let item = ShareItem(url: urlString, title: title, favicon: nil)
self.profile.queue.addToQueue(item)
}
}
}
/**
* This exists because the Sync code is extension-safe, and thus doesn't get
* direct access to UIApplication.sharedApplication, which it would need to
* display a notification.
* This will also likely be the extension point for wipes, resets, and
* getting access to data sources during a sync.
*/
let TabSendURLKey = "TabSendURL"
let TabSendTitleKey = "TabSendTitle"
let TabSendCategory = "TabSendCategory"
enum SentTabAction: String {
case View = "TabSendViewAction"
case Bookmark = "TabSendBookmarkAction"
case ReadingList = "TabSendReadingListAction"
}
class BrowserProfileSyncDelegate: SyncDelegate {
let app: UIApplication
init(app: UIApplication) {
self.app = app
}
// SyncDelegate
func displaySentTabForURL(URL: NSURL, title: String) {
// check to see what the current notification settings are and only try and send a notification if
// the user has agreed to them
let currentSettings = app.currentUserNotificationSettings()
if currentSettings.types.rawValue & UIUserNotificationType.Alert.rawValue != 0 {
log.info("Displaying notification for URL \(URL.absoluteString)")
let notification = UILocalNotification()
notification.fireDate = NSDate()
notification.timeZone = NSTimeZone.defaultTimeZone()
notification.alertBody = String(format: NSLocalizedString("New tab: %@: %@", comment:"New tab [title] [url]"), title, URL.absoluteString!)
notification.userInfo = [TabSendURLKey: URL.absoluteString!, TabSendTitleKey: title]
notification.alertAction = nil
notification.category = TabSendCategory
app.presentLocalNotificationNow(notification)
}
}
}
/**
* A Profile manages access to the user's data.
*/
protocol Profile: class {
var bookmarks: protocol<BookmarksModelFactory, ShareToDestination> { get }
// var favicons: Favicons { get }
var prefs: Prefs { get }
var queue: TabQueue { get }
var searchEngines: SearchEngines { get }
var files: FileAccessor { get }
var history: protocol<BrowserHistory, SyncableHistory> { get }
var favicons: Favicons { get }
var readingList: ReadingListService? { get }
var logins: protocol<BrowserLogins, SyncableLogins> { get }
var thumbnails: Thumbnails { get }
func shutdown()
// I got really weird EXC_BAD_ACCESS errors on a non-null reference when I made this a getter.
// Similar to <http://stackoverflow.com/questions/26029317/exc-bad-access-when-indirectly-accessing-inherited-member-in-swift>.
func localName() -> String
// URLs and account configuration.
var accountConfiguration: FirefoxAccountConfiguration { get }
func getAccount() -> FirefoxAccount?
func removeAccount()
func setAccount(account: FirefoxAccount)
func getClients() -> Deferred<Result<[RemoteClient]>>
func getClientsAndTabs() -> Deferred<Result<[ClientAndTabs]>>
func getCachedClientsAndTabs() -> Deferred<Result<[ClientAndTabs]>>
func storeTabs(tabs: [RemoteTab]) -> Deferred<Result<Int>>
func sendItems(items: [ShareItem], toClients clients: [RemoteClient])
var syncManager: SyncManager { get }
}
public class BrowserProfile: Profile {
private let name: String
weak private var app: UIApplication?
init(localName: String, app: UIApplication?) {
self.name = localName
self.app = app
let notificationCenter = NSNotificationCenter.defaultCenter()
let mainQueue = NSOperationQueue.mainQueue()
notificationCenter.addObserver(self, selector: Selector("onLocationChange:"), name: "LocationChange", object: nil)
if let baseBundleIdentifier = ExtensionUtils.baseBundleIdentifier() {
KeychainWrapper.serviceName = baseBundleIdentifier
} else {
log.error("Unable to get the base bundle identifier. Keychain data will not be shared.")
}
// If the profile dir doesn't exist yet, this is first run (for this profile).
if !files.exists("") {
log.info("New profile. Removing old account data.")
removeAccount()
prefs.clearAll()
}
}
// Extensions don't have a UIApplication.
convenience init(localName: String) {
self.init(localName: localName, app: nil)
}
func shutdown() {
if dbCreated {
db.close()
}
if loginsDBCreated {
loginsDB.close()
}
}
@objc
func onLocationChange(notification: NSNotification) {
if let v = notification.userInfo!["visitType"] as? Int,
let visitType = VisitType(rawValue: v),
let url = notification.userInfo!["url"] as? NSURL where !isIgnoredURL(url),
let title = notification.userInfo!["title"] as? NSString {
// We don't record a visit if no type was specified -- that means "ignore me".
let site = Site(url: url.absoluteString!, title: title as String)
let visit = SiteVisit(site: site, date: NSDate.nowMicroseconds(), type: visitType)
log.debug("Recording visit for \(url) with type \(v).")
history.addLocalVisit(visit)
} else {
let url = notification.userInfo!["url"] as? NSURL
log.debug("Ignoring navigation for \(url).")
}
}
deinit {
self.syncManager.endTimedSyncs()
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func localName() -> String {
return name
}
var files: FileAccessor {
return ProfileFileAccessor(profile: self)
}
lazy var queue: TabQueue = {
return SQLiteQueue(db: self.db)
}()
private var dbCreated = false
lazy var db: BrowserDB = {
self.dbCreated = true
return BrowserDB(filename: "browser.db", files: self.files)
}()
/**
* Favicons, history, and bookmarks are all stored in one intermeshed
* collection of tables.
*/
private lazy var places: protocol<BrowserHistory, Favicons, SyncableHistory> = {
return SQLiteHistory(db: self.db)
}()
var favicons: Favicons {
return self.places
}
var history: protocol<BrowserHistory, SyncableHistory> {
return self.places
}
lazy var bookmarks: protocol<BookmarksModelFactory, ShareToDestination> = {
return SQLiteBookmarks(db: self.db)
}()
lazy var searchEngines: SearchEngines = {
return SearchEngines(prefs: self.prefs)
}()
func makePrefs() -> Prefs {
return NSUserDefaultsPrefs(prefix: self.localName())
}
lazy var prefs: Prefs = {
return self.makePrefs()
}()
lazy var readingList: ReadingListService? = {
return ReadingListService(profileStoragePath: self.files.rootPath)
}()
private lazy var remoteClientsAndTabs: RemoteClientsAndTabs = {
return SQLiteRemoteClientsAndTabs(db: self.db)
}()
lazy var syncManager: SyncManager = {
return BrowserSyncManager(profile: self)
}()
private func getSyncDelegate() -> SyncDelegate {
if let app = self.app {
return BrowserProfileSyncDelegate(app: app)
}
return CommandStoringSyncDelegate()
}
public func getClients() -> Deferred<Result<[RemoteClient]>> {
return self.syncManager.syncClients()
>>> { self.remoteClientsAndTabs.getClients() }
}
public func getClientsAndTabs() -> Deferred<Result<[ClientAndTabs]>> {
return self.syncManager.syncClientsThenTabs()
>>> { self.remoteClientsAndTabs.getClientsAndTabs() }
}
public func getCachedClientsAndTabs() -> Deferred<Result<[ClientAndTabs]>> {
return self.remoteClientsAndTabs.getClientsAndTabs()
}
func storeTabs(tabs: [RemoteTab]) -> Deferred<Result<Int>> {
return self.remoteClientsAndTabs.insertOrUpdateTabs(tabs)
}
public func sendItems(items: [ShareItem], toClients clients: [RemoteClient]) {
let commands = items.map { item in
SyncCommand.fromShareItem(item, withAction: "displayURI")
}
self.remoteClientsAndTabs.insertCommands(commands, forClients: clients) >>> { self.syncManager.syncClients() }
}
lazy var logins: protocol<BrowserLogins, SyncableLogins> = {
return SQLiteLogins(db: self.loginsDB)
}()
private lazy var loginsKey: String? = {
let key = "sqlcipher.key.logins.db"
if KeychainWrapper.hasValueForKey(key) {
return KeychainWrapper.stringForKey(key)
}
let Length: UInt = 256
let secret = Bytes.generateRandomBytes(Length).base64EncodedString
KeychainWrapper.setString(secret, forKey: key)
return secret
}()
private var loginsDBCreated = false
private lazy var loginsDB: BrowserDB = {
self.loginsDBCreated = true
return BrowserDB(filename: "logins.db", secretKey: self.loginsKey, files: self.files)
}()
lazy var thumbnails: Thumbnails = {
return SDWebThumbnails(files: self.files)
}()
let accountConfiguration: FirefoxAccountConfiguration = ProductionFirefoxAccountConfiguration()
private lazy var account: FirefoxAccount? = {
if let dictionary = KeychainWrapper.objectForKey(self.name + ".account") as? [String: AnyObject] {
return FirefoxAccount.fromDictionary(dictionary)
}
return nil
}()
func getAccount() -> FirefoxAccount? {
return account
}
func removeAccount() {
let old = self.account
prefs.removeObjectForKey(PrefsKeys.KeyLastRemoteTabSyncTime)
KeychainWrapper.removeObjectForKey(name + ".account")
self.account = nil
// tell any observers that our account has changed
NSNotificationCenter.defaultCenter().postNotificationName(NotificationFirefoxAccountChanged, object: nil)
// Trigger cleanup. Pass in the account in case we want to try to remove
// client-specific data from the server.
self.syncManager.onRemovedAccount(old)
// deregister for remote notifications
app?.unregisterForRemoteNotifications()
}
func setAccount(account: FirefoxAccount) {
KeychainWrapper.setObject(account.asDictionary(), forKey: name + ".account")
self.account = account
// register for notifications for the account
registerForNotifications()
// tell any observers that our account has changed
NSNotificationCenter.defaultCenter().postNotificationName(NotificationFirefoxAccountChanged, object: nil)
self.syncManager.onAddedAccount()
}
func registerForNotifications() {
let viewAction = UIMutableUserNotificationAction()
viewAction.identifier = SentTabAction.View.rawValue
viewAction.title = NSLocalizedString("View", comment: "View a URL - https://bugzilla.mozilla.org/attachment.cgi?id=8624438, https://bug1157303.bugzilla.mozilla.org/attachment.cgi?id=8624440")
viewAction.activationMode = UIUserNotificationActivationMode.Foreground
viewAction.destructive = false
viewAction.authenticationRequired = false
let bookmarkAction = UIMutableUserNotificationAction()
bookmarkAction.identifier = SentTabAction.Bookmark.rawValue
bookmarkAction.title = NSLocalizedString("Bookmark", comment: "Bookmark a URL - https://bugzilla.mozilla.org/attachment.cgi?id=8624438, https://bug1157303.bugzilla.mozilla.org/attachment.cgi?id=8624440")
bookmarkAction.activationMode = UIUserNotificationActivationMode.Foreground
bookmarkAction.destructive = false
bookmarkAction.authenticationRequired = false
let readingListAction = UIMutableUserNotificationAction()
readingListAction.identifier = SentTabAction.ReadingList.rawValue
readingListAction.title = NSLocalizedString("Add to Reading List", comment: "Add URL to the reading list - https://bugzilla.mozilla.org/attachment.cgi?id=8624438, https://bug1157303.bugzilla.mozilla.org/attachment.cgi?id=8624440")
readingListAction.activationMode = UIUserNotificationActivationMode.Foreground
readingListAction.destructive = false
readingListAction.authenticationRequired = false
let sentTabsCategory = UIMutableUserNotificationCategory()
sentTabsCategory.identifier = TabSendCategory
sentTabsCategory.setActions([readingListAction, bookmarkAction, viewAction], forContext: UIUserNotificationActionContext.Default)
sentTabsCategory.setActions([bookmarkAction, viewAction], forContext: UIUserNotificationActionContext.Minimal)
app?.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Alert, categories: [sentTabsCategory]))
app?.registerForRemoteNotifications()
}
// Extends NSObject so we can use timers.
class BrowserSyncManager: NSObject, SyncManager {
unowned private let profile: BrowserProfile
let FifteenMinutes = NSTimeInterval(60 * 15)
let OneMinute = NSTimeInterval(60)
private var syncTimer: NSTimer? = nil
/**
* Locking is managed by withSyncInputs. Make sure you take and release these
* whenever you do anything Sync-ey.
*/
var syncLock = OSSpinLock()
private func beginSyncing() -> Bool {
return OSSpinLockTry(&syncLock)
}
private func endSyncing() {
return OSSpinLockUnlock(&syncLock)
}
init(profile: BrowserProfile) {
self.profile = profile
super.init()
let center = NSNotificationCenter.defaultCenter()
center.addObserver(self, selector: "onLoginDidChange:", name: NotificationDataLoginDidChange, object: nil)
}
deinit {
// Remove 'em all.
NSNotificationCenter.defaultCenter().removeObserver(self)
}
// Simple in-memory rate limiting.
var lastTriggeredLoginSync: Timestamp = 0
@objc func onLoginDidChange(notification: NSNotification) {
log.debug("Login did change.")
if (NSDate.now() - lastTriggeredLoginSync) > OneMinuteInMilliseconds {
lastTriggeredLoginSync = NSDate.now()
// Give it a few seconds.
let when: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, SyncConstants.SyncDelayTriggered)
// Trigger on the main queue. The bulk of the sync work runs in the background.
dispatch_after(when, dispatch_get_main_queue()) {
self.syncLogins()
}
}
}
var prefsForSync: Prefs {
return self.profile.prefs.branch("sync")
}
func onAddedAccount() -> Success {
return self.syncEverything()
}
func onRemovedAccount(account: FirefoxAccount?) -> Success {
let h: SyncableHistory = self.profile.history
let flagHistory = h.onRemovedAccount()
let clearTabs = self.profile.remoteClientsAndTabs.onRemovedAccount()
let done = allSucceed(flagHistory, clearTabs)
// Clear prefs after we're done clearing everything else -- just in case
// one of them needs the prefs and we race. Clear regardless of success
// or failure.
done.upon { result in
// This will remove keys from the Keychain if they exist, as well
// as wiping the Sync prefs.
SyncStateMachine.clearStateFromPrefs(self.prefsForSync)
}
return done
}
private func repeatingTimerAtInterval(interval: NSTimeInterval, selector: Selector) -> NSTimer {
return NSTimer.scheduledTimerWithTimeInterval(interval, target: self, selector: selector, userInfo: nil, repeats: true)
}
func beginTimedSyncs() {
if self.syncTimer != nil {
log.debug("Already running sync timer.")
return
}
let interval = FifteenMinutes
let selector = Selector("syncOnTimer")
log.debug("Starting sync timer.")
self.syncTimer = repeatingTimerAtInterval(interval, selector: selector)
}
/**
* The caller is responsible for calling this on the same thread on which it called
* beginTimedSyncs.
*/
func endTimedSyncs() {
if let t = self.syncTimer {
log.debug("Stopping history sync timer.")
self.syncTimer = nil
t.invalidate()
}
}
private func syncClientsWithDelegate(delegate: SyncDelegate, prefs: Prefs, ready: Ready) -> SyncResult {
log.debug("Syncing clients to storage.")
let clientSynchronizer = ready.synchronizer(ClientsSynchronizer.self, delegate: delegate, prefs: prefs)
return clientSynchronizer.synchronizeLocalClients(self.profile.remoteClientsAndTabs, withServer: ready.client, info: ready.info)
}
private func syncTabsWithDelegate(delegate: SyncDelegate, prefs: Prefs, ready: Ready) -> SyncResult {
let storage = self.profile.remoteClientsAndTabs
let tabSynchronizer = ready.synchronizer(TabsSynchronizer.self, delegate: delegate, prefs: prefs)
return tabSynchronizer.synchronizeLocalTabs(storage, withServer: ready.client, info: ready.info)
}
private func syncHistoryWithDelegate(delegate: SyncDelegate, prefs: Prefs, ready: Ready) -> SyncResult {
log.debug("Syncing history to storage.")
let historySynchronizer = ready.synchronizer(HistorySynchronizer.self, delegate: delegate, prefs: prefs)
return historySynchronizer.synchronizeLocalHistory(self.profile.history, withServer: ready.client, info: ready.info)
}
private func syncLoginsWithDelegate(delegate: SyncDelegate, prefs: Prefs, ready: Ready) -> SyncResult {
log.debug("Syncing logins to storage.")
let loginsSynchronizer = ready.synchronizer(LoginsSynchronizer.self, delegate: delegate, prefs: prefs)
return loginsSynchronizer.synchronizeLocalLogins(self.profile.logins, withServer: ready.client, info: ready.info)
}
/**
* Returns nil if there's no account.
*/
private func withSyncInputs<T>(label: EngineIdentifier? = nil, function: (SyncDelegate, Prefs, Ready) -> Deferred<Result<T>>) -> Deferred<Result<T>>? {
if let account = profile.account {
if !beginSyncing() {
log.info("Not syncing \(label); already syncing something.")
return deferResult(AlreadySyncingError())
}
if let label = label {
log.info("Syncing \(label).")
}
let authState = account.syncAuthState
let syncPrefs = profile.prefs.branch("sync")
let readyDeferred = SyncStateMachine.toReady(authState, prefs: syncPrefs)
let delegate = profile.getSyncDelegate()
let go = readyDeferred >>== { ready in
function(delegate, syncPrefs, ready)
}
// Always unlock when we're done.
go.upon({ res in self.endSyncing() })
return go
}
log.warning("No account; can't sync.")
return nil
}
/**
* Runs the single provided synchronization function and returns its status.
*/
private func sync(label: EngineIdentifier, function: (SyncDelegate, Prefs, Ready) -> SyncResult) -> SyncResult {
return self.withSyncInputs(label: label, function: function) ??
deferResult(.NotStarted(.NoAccount))
}
/**
* Runs each of the provided synchronization functions with the same inputs.
* Returns an array of IDs and SyncStatuses the same length as the input.
*/
private func syncSeveral(synchronizers: (EngineIdentifier, SyncFunction)...) -> Deferred<Result<[(EngineIdentifier, SyncStatus)]>> {
typealias Pair = (EngineIdentifier, SyncStatus)
let combined: (SyncDelegate, Prefs, Ready) -> Deferred<Result<[Pair]>> = { delegate, syncPrefs, ready in
let thunks = synchronizers.map { (i, f) in
return { () -> Deferred<Result<Pair>> in
log.debug("Syncing \(i)…")
return f(delegate, syncPrefs, ready) >>== { deferResult((i, $0)) }
}
}
return accumulate(thunks)
}
return self.withSyncInputs(label: nil, function: combined) ??
deferResult(synchronizers.map { ($0.0, .NotStarted(.NoAccount)) })
}
func syncEverything() -> Success {
return self.syncSeveral(
("clients", self.syncClientsWithDelegate),
("tabs", self.syncTabsWithDelegate),
("history", self.syncHistoryWithDelegate)
) >>> succeed
}
@objc func syncOnTimer() {
log.debug("Running timed logins sync.")
// Note that we use .upon here rather than chaining with >>> precisely
// to allow us to sync subsequent engines regardless of earlier failures.
// We don't fork them in parallel because we want to limit perf impact
// due to background syncs, and because we're cautious about correctness.
self.syncLogins().upon { result in
if let success = result.successValue {
log.debug("Timed logins sync succeeded. Status: \(success.description).")
} else {
let reason = result.failureValue?.description ?? "none"
log.debug("Timed logins sync failed. Reason: \(reason).")
}
log.debug("Running timed history sync.")
self.syncHistory().upon { result in
if let success = result.successValue {
log.debug("Timed history sync succeeded. Status: \(success.description).")
} else {
let reason = result.failureValue?.description ?? "none"
log.debug("Timed history sync failed. Reason: \(reason).")
}
}
}
}
func syncClients() -> SyncResult {
// TODO: recognize .NotStarted.
return self.sync("clients", function: syncClientsWithDelegate)
}
func syncClientsThenTabs() -> SyncResult {
return self.syncSeveral(
("clients", self.syncClientsWithDelegate),
("tabs", self.syncTabsWithDelegate)
) >>== { statuses in
let tabsStatus = statuses[1].1
return deferResult(tabsStatus)
}
}
func syncLogins() -> SyncResult {
return self.sync("logins", function: syncLoginsWithDelegate)
}
func syncHistory() -> SyncResult {
// TODO: recognize .NotStarted.
return self.sync("history", function: syncHistoryWithDelegate)
}
}
}
class AlreadySyncingError: ErrorType {
var description: String {
return "Already syncing."
}
}
| mpl-2.0 | 63a6d226628b8b54313a735253157ed0 | 37.591928 | 238 | 0.642071 | 5.26898 | false | false | false | false |
julienbodet/wikipedia-ios | Wikipedia/Code/ArticleLocationController.swift | 1 | 2240 | import Foundation
@objc class ArticleLocationController: NSObject {
let migrationKey = "WMFDidCompleteQuadKeyMigration"
@objc func needsMigration(managedObjectContext: NSManagedObjectContext) -> Bool {
do {
let keyValueRequest = WMFKeyValue.fetchRequest()
keyValueRequest.predicate = NSPredicate(format: "key == %@", migrationKey)
let keyValueResult = try managedObjectContext.fetch(keyValueRequest)
return keyValueResult.count == 0 || (keyValueResult[0].value == nil)
} catch {
return true
}
}
@objc func migrate(managedObjectContext: NSManagedObjectContext, completion: @escaping (Error?) -> Void) {
do {
let request = WMFArticle.fetchRequest()
request.predicate = NSPredicate(format: "latitude != NULL && latitude != 0 && longitude != NULL && longitude != 0 && signedQuadKey == NULL")
request.fetchLimit = 500
let results = try managedObjectContext.fetch(request)
if results.count == 0, let entity = NSEntityDescription.entity(forEntityName: "WMFKeyValue", in: managedObjectContext) {
let kv = WMFKeyValue(entity: entity, insertInto: managedObjectContext)
kv.key = migrationKey
kv.value = NSNumber(value: true)
try managedObjectContext.save()
completion(nil)
return
}
for result in results {
let lat = QuadKeyDegrees(result.latitude)
let lon = QuadKeyDegrees(result.longitude)
if lat != 0 && lon != 0 {
let quadKey = QuadKey(latitude: lat, longitude: lon)
let signedQuadKey = Int64(quadKey: quadKey)
result.signedQuadKey = NSNumber(value: signedQuadKey)
}
}
try managedObjectContext.save()
} catch let error {
completion(error)
return
}
dispatchOnMainQueue {
self.migrate(managedObjectContext: managedObjectContext, completion: completion)
}
}
}
| mit | 907010e51228459e1d48865923881806 | 39 | 152 | 0.570982 | 5.6 | false | false | false | false |
artsy/eigen | ios/ArtsyTests/Networking_Tests/Live_Auctions/LiveAuctionStaticDataFetcherSpec.swift | 1 | 1650 | import Quick
import Nimble
import Interstellar
@testable
import Artsy
class LiveAuctionStaticDataFetcherSpec: QuickSpec {
override func spec() {
let saleID = "the-id"
let jwt = StubbedCredentials.notRegistered.jwt.string
let bidderID = "000000"
let paddleNumber = "1234"
let userID = "abcd"
let stateJSON: NSDictionary = ["data": ["sale": ["id": "the-id"], "system": ["causalityJWT": jwt], "me": ["id": userID, "paddle_number": paddleNumber, "bidders": [["id": bidderID]]]]]
var subject: LiveAuctionStaticDataFetcher!
beforeEach {
OHHTTPStubs.stubJSONResponse(forHost: "metaphysics*.artsy.net", withResponse: stateJSON)
subject = LiveAuctionStaticDataFetcher(saleSlugOrID: saleID)
}
it("configures its sale ID correctly") {
expect(subject.saleSlugOrID) == saleID
}
describe("after fetching") {
var receivedState: Observable<StaticSaleResult>!
beforeEach {
receivedState = subject.fetchStaticData()
}
it("fetches the static data") {
expect(receivedState.peek()?.sale.liveSaleID) == saleID
}
it("fetches a jwt") {
expect(receivedState.peek()?.jwt.string) == jwt
}
it("fetches a bidderId") {
expect(receivedState.peek()?.bidderCredentials.bidderID) == bidderID
}
it("fetches a paddleNumber") {
expect(receivedState.peek()?.bidderCredentials.paddleNumber) == paddleNumber
}
}
}
}
| mit | df0ab91dccad31bed4cafae3511cffb7 | 29 | 191 | 0.581212 | 4.661017 | false | false | false | false |
coderZsq/coderZsq.target.swift | StudyNotes/Swift Note/ObjC.io/Swift4/Functional/Immutable.swift | 1 | 1693 | //
// Immutable.swift
// Functional
//
// Created by 朱双泉 on 2018/5/11.
// Copyright © 2018 Castie!. All rights reserved.
//
import Foundation
//var x: Int = 1
//let y: Int = 2
struct PointStruct {
var x: Int
var y: Int
}
var structPoint = PointStruct(x: 1, y: 2)
var sameStructPoint = structPoint
//sameStructPoint.x = 3
class PointClass {
var x: Int
var y: Int
init(x: Int, y: Int) {
self.x = x
self.y = y
}
}
var classPoint = PointClass(x: 1, y: 2)
var sameClassPoint = classPoint
//sameClassPoint.x = 3
func setStructToOrigin(point: PointStruct) -> PointStruct {
var newPoint = point
newPoint.x = 0
newPoint.y = 0
return newPoint
}
var structOrigin = setStructToOrigin(point: structPoint)
func setClassToOrigin(point: PointClass) -> PointClass {
point.x = 0
point.y = 0
return point
}
var classOrigin = setClassToOrigin(point: classPoint)
extension PointStruct {
mutating func setStructToOrigin() {
x = 0
y = 0
}
}
class Immutable {
static func run() {
var myPoint = PointStruct(x: 100, y: 100)
let otherPoint = myPoint
myPoint.setStructToOrigin()
print(otherPoint)
print(myPoint)
}
}
let immutablePoint = PointStruct(x: 0, y: 0)
var mutablePoint = PointStruct(x: 1, y: 1)
//mutablePoint.x = 3
struct immutablePointStruct {
let x: Int
let y: Int
}
var immutablePoint2 = immutablePointStruct(x: 1, y: 1)
//immutablePoint2.x = 3
//immutablePoint2 = immutablePointStruct(x: 2, y: 2)
func sum(inetegers: [Int]) -> Int {
var result = 0
for x in inetegers {
result += x
}
return result
}
| mit | 5d88a1a2fcc9e4f4a4993866a402f85b | 16.93617 | 59 | 0.630486 | 3.187146 | false | false | false | false |
andyshep/Waypoints | Sources/Waypoints/Extensions/CLGeocoder+Combine.swift | 1 | 2147 | import CoreLocation
import Combine
enum GeocoderError: Error {
case notFound
case other(Error)
}
class ReverseGeocoderSubscription<SubscriberType: Subscriber>: Subscription where SubscriberType.Input == Result<[CLPlacemark], Error> {
private var subscriber: SubscriberType?
private let geocoder: CLGeocoder
init(subscriber: SubscriberType, location: CLLocation, geocoder: CLGeocoder) {
self.subscriber = subscriber
self.geocoder = geocoder
geocoder.reverseGeocodeLocation(location) { (placemarks, error) in
if let error = error {
_ = subscriber.receive(.failure(GeocoderError.other(error)))
} else if let placemarks = placemarks {
_ = subscriber.receive(.success(placemarks))
} else {
_ = subscriber.receive(.failure(GeocoderError.notFound))
}
}
}
func request(_ demand: Subscribers.Demand) {
// No need to handle `demand` because events are sent when they occur
}
func cancel() {
subscriber = nil
}
}
public struct ReverseGeocoderPublisher: Publisher {
public typealias Output = Result<[CLPlacemark], Error>
public typealias Failure = Never
private let location: CLLocation
private let geocoder: CLGeocoder
init(location: CLLocation, geocoder: CLGeocoder = CLGeocoder()) {
self.location = location
self.geocoder = geocoder
}
public func receive<S>(subscriber: S) where S : Subscriber, ReverseGeocoderPublisher.Failure == S.Failure, ReverseGeocoderPublisher.Output == S.Input {
let subscription = ReverseGeocoderSubscription(
subscriber: subscriber,
location: location,
geocoder: geocoder
)
subscriber.receive(subscription: subscription)
}
}
public extension CLGeocoder {
func reverseGeocodingPublisher(for location: CLLocation) -> AnyPublisher<Result<[CLPlacemark], Error>, Never> {
return ReverseGeocoderPublisher(location: location, geocoder: self)
.eraseToAnyPublisher()
}
}
| mit | 624ace4c2599141bbfe6ff2ef8cd36d0 | 32.030769 | 155 | 0.656265 | 5.249389 | false | false | false | false |
xiangpengzhu/QuickStart | QuickStart/UIKit+Extension/QSImagePickerController/QSImagePickerPhotoCell.swift | 1 | 1257 | //
// QSImagePickerPhotoCell.swift
// QuickStart
//
// Created by zhuxiangpeng on 2017/3/30.
// Copyright © 2017年 zxp. All rights reserved.
//
import UIKit
class QSImagePickerPhotoCell: UICollectionViewCell {
var representedAssetIdentifier: String?
var disable: Bool = false {
didSet {
maskV?.removeFromSuperview()
maskV = nil
if disable {
selectImageV.image = nil
let maskV = UIView(frame: contentView.bounds)
maskV.backgroundColor = UIColor(colorHexValue: 0xffffff, alpha: 0.7)
contentView.addSubview(maskV)
maskV.translatesAutoresizingMaskIntoConstraints = false
var constraints = [NSLayoutConstraint]()
constraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "H:|[view]|", options: .alignAllBottom, metrics: nil, views: ["view": maskV]))
constraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:|[view]|", options: .alignAllLeft, metrics: nil, views: ["view": maskV]))
contentView.addConstraints(constraints)
self.maskV = maskV
}
}
}
@IBOutlet var imageV: UIImageView!
@IBOutlet var selectImageV: UIImageView!
private var maskV: UIView?
override func awakeFromNib() {
super.awakeFromNib()
}
}
| gpl-3.0 | 3e7249e03176a5097c3b8913d74fed8d | 27.5 | 162 | 0.714514 | 4.032154 | false | false | false | false |
DrabWeb/Sudachi | Sudachi/Sudachi/SCViews.swift | 1 | 4821 | //
// SCPopUpButton.swift
// Sudachi
//
// Created by Seth on 2016-04-17.
//
import Cocoa
class SCPopUpButton: NSPopUpButton {
override func drawRect(dirtyRect: NSRect) {
super.drawRect(dirtyRect)
// Drawing code here.
// Set the title colors and fonts
setMenuItemsTitleColorsAndFonts();
}
required init?(coder: NSCoder) {
super.init(coder: coder);
// Set the title colors and fonts
setMenuItemsTitleColorsAndFonts();
}
/// Sets the color of the label of each menu item for this popup button to the control text color and sets the fonts
func setMenuItemsTitleColorsAndFonts() {
// Set the popup button's font
self.font = SCThemingEngine().defaultEngine().setFontFamily(self.font!, size: SCThemingEngine().defaultEngine().controlTextFontSize);
// For every menu item...
for(_, currentMenuItem) in self.menu!.itemArray.enumerate() {
/// The attributed title
let attributedTitle = NSMutableAttributedString(string: currentMenuItem.title, attributes: [NSFontAttributeName: NSFont.systemFontOfSize(self.font!.pointSize), NSForegroundColorAttributeName: SCThemingEngine().defaultEngine().controlTextColor, NSFontFamilyAttribute: self.font!.familyName!]);
// Set the title
currentMenuItem.attributedTitle = attributedTitle;
}
}
}
class SCPopUpButtonCell: NSPopUpButtonCell {
override func drawBorderAndBackgroundWithFrame(cellFrame: NSRect, inView controlView: NSView) {
/// The bounds of the NSPopUpButton for this cell
var controlBounds : NSRect = (self.controlView as! NSPopUpButton).bounds;
// Fix the bounds so we draw the control background the same size as it would regularly
controlBounds = NSRect(x: controlBounds.origin.x, y: controlBounds.origin.y + 3, width: controlBounds.width, height: controlBounds.height - 7);
// Set the fill color
SCThemingEngine().defaultEngine().controlBackgroundColor.setFill();
/// The bezier path to fill in the background of the cell
let backgroundPath : NSBezierPath = NSBezierPath(roundedRect: controlBounds, xRadius: 3, yRadius: 3);
// Fill the background
backgroundPath.fill();
}
override func drawInteriorWithFrame(cellFrame: NSRect, inView controlView: NSView) {
// Adjust the interior size so it fits with our custom drawing
super.drawInteriorWithFrame(NSRect(x: cellFrame.origin.x - 3, y: cellFrame.origin.y, width: cellFrame.width, height:cellFrame.height), inView: controlView);
}
}
class SCButton: NSButton {
override func drawRect(dirtyRect: NSRect) {
super.drawRect(dirtyRect)
// Drawing code here.
// Set the title color and font
setTitleColorAndFont();
}
required init?(coder: NSCoder) {
super.init(coder: coder);
// Set the title color and font
setTitleColorAndFont();
}
/// Sets the color of the button's title to the control text color and the font family
func setTitleColorAndFont() {
// Set the font
self.font = SCThemingEngine().defaultEngine().setFontFamily(self.font!, size: SCThemingEngine().defaultEngine().controlTextFontSize);
/// The title's paragraph style
let titleParagraphStyle = NSMutableParagraphStyle();
// Set the alignment to the button's title aligment
titleParagraphStyle.alignment = self.alignment;
/// The attributed title
let attributedTitle = NSMutableAttributedString(string: self.title, attributes: [NSFontAttributeName: NSFont.systemFontOfSize(self.font!.pointSize), NSParagraphStyleAttributeName: titleParagraphStyle, NSForegroundColorAttributeName: SCThemingEngine().defaultEngine().controlTextColor, NSFontFamilyAttribute: self.font!.familyName!]);
// Set the title
self.attributedTitle = attributedTitle;
}
}
class SCButtonCell: NSButtonCell {
override func drawBezelWithFrame(frame: NSRect, inView controlView: NSView) {
/// The frame that was passed, adjusted to be sized properly
let adjustedFrame : NSRect = NSRect(x: frame.origin.x + 7, y: frame.origin.y + 5, width: frame.width - 14, height: frame.height - 13);
// Set the fill color
SCThemingEngine().defaultEngine().controlBackgroundColor.setFill();
/// The bezier path to fill in the background of the cell
let backgroundPath : NSBezierPath = NSBezierPath(roundedRect: adjustedFrame, xRadius: 3, yRadius: 3);
// Fill the background
backgroundPath.fill();
}
}
| gpl-3.0 | 5c0f8936de012a1d043e7822d5e64a5c | 40.560345 | 341 | 0.668119 | 5.123273 | false | false | false | false |
siavashalipour/SAPinViewController | SAPinViewController/Classes/SAPinViewController.swift | 1 | 20818 | //
// SAPinViewController.swift
// PINManagement
//
// Created by Siavash Abbasalipour on 19/08/2016.
// Copyright © 2016 Siavash Abbasalipour. All rights reserved.
//
import UIKit
import SnapKit
/// SAPinViewControllerDelegate
/// Any ViewController that would like to present `SAPinViewController` should implement
/// all these protocol methods
public protocol SAPinViewControllerDelegate: class {
/// Gets called upon tapping on `Cancel` button
/// required and must be implemented
func pinEntryWasCancelled()
/// Gets called if the enterd PIN returned `true` passing it to `isPinValid(pin: String) -> Bool`
/// required and must be implemented
func pinEntryWasSuccessful()
/// Gets called if the enterd PIN returned `false` passing it to `isPinValid(pin: String) -> Bool`
/// required and must be implemented
func pinWasIncorrect()
/// Ask the implementer to see whether the PIN is valid or not
/// required and must be implemented
func isPinValid(_ pin: String) -> Bool
}
/// SAPinViewController
/// Use this class to instantiate a PIN screen
/// Set each one of its property for customisation
/// N.B: UNLY use the Designate initialaiser
open class SAPinViewController: UIViewController {
/// Set this to customise the border colour around the dots
/// This will set the dots fill colour as well
/// Default is white colour
open var circleBorderColor: UIColor! {
didSet {
if circleViews.count > 0 {
for i in 0...3 {
circleViews[i].circleBorderColor = circleBorderColor
}
}
}
}
/// Set this to change the font of PIN numbers and alphabet
/// Note that the maximum font size for numbers are 30.0 and for alphabets are 10.0
open var font: UIFont! {
didSet {
if buttons.count > 0 {
for i in 0...9 {
buttons[i].font = font
}
}
}
}
/// Set this if you want to hide the alphabets - default is to show alphabet
open var showAlphabet: Bool! {
didSet {
if buttons.count > 0 {
for i in 0...9 {
buttons[i].showAlphabet = showAlphabet
}
}
}
}
/// Set this to customise the border colour around the PIN numbers
/// Default is white
open var buttonBorderColor: UIColor! {
didSet {
if buttons.count > 0 {
for i in 0...9 {
buttons[i].buttonBorderColor = buttonBorderColor
}
}
}
}
/// Set this to customise the PIN numbers colour
/// Default is white
open var numberColor: UIColor! {
didSet {
if buttons.count > 0 {
for i in 0...9 {
buttons[i].numberColor = numberColor
}
}
}
}
/// Set this to customise the alphabet colour
/// Default is white
open var alphabetColor: UIColor! {
didSet {
if buttons.count > 0 {
for i in 0...9 {
buttons[i].alphabetColor = alphabetColor
}
}
}
}
/// Set this to add subtitle text for the `SAPinViewController`
/// Default is empty String
open var subtitleText: String! {
didSet {
if subtitleLabel != nil {
subtitleLabel.text = subtitleText
updateSubtitle()
}
}
}
/// Set this to add title text for the `SAPinViewController`
/// Default is "Enter Passcode"
open var titleText: String! {
didSet {
if titleLabel != nil {
titleLabel.text = titleText
updateTitle()
}
}
}
/// Set this to customise subtitle text colour for the `SAPinViewController`
/// Default is white
open var subtitleTextColor: UIColor! {
didSet {
if subtitleLabel != nil {
subtitleLabel.textColor = subtitleTextColor
}
}
}
/// Set this to customise title text colour for the `SAPinViewController`
/// Default is white
open var titleTextColor: UIColor! {
didSet {
if titleLabel != nil {
titleLabel.textColor = titleTextColor
}
}
}
/// Set this to customise `Cancel` button text colour
/// Default is white
open var cancelButtonColor: UIColor! {
didSet {
if cancelButton != nil {
let font = UIFont(name: SAPinConstant.DefaultFontName, size: 17)
setAttributedTitleForButtonWithTitle(SAPinConstant.CancelString, font: font!, color: cancelButtonColor)
}
}
}
/// Set this to customise `Cancel` button text font
/// Maximum font size is 17.0
open var cancelButtonFont: UIFont! {
didSet {
if cancelButton != nil {
let font = cancelButtonFont.withSize(17)
setAttributedTitleForButtonWithTitle(SAPinConstant.CancelString, font: font, color: cancelButtonColor ?? UIColor.white)
}
}
}
/// Set this to `true` to get rounded rect boarder style
open var isRoundedRect: Bool! {
didSet {
if let safeIsRoundedRect = isRoundedRect {
if buttons.count > 0 {
for i in 0...9 {
buttons[i].isRoundedRect = safeIsRoundedRect
}
}
if circleViews.count > 0 {
for i in 0...3 {
circleViews[i].isRoundedRect = safeIsRoundedRect
}
}
}
}
}
fileprivate var blurView: UIVisualEffectView!
fileprivate var numPadView: UIView!
fileprivate var buttons: [SAButtonView]! = []
fileprivate var circleViews: [SACircleView]! = []
fileprivate var dotContainerView: UIView!
fileprivate var titleLabel: UILabel!
fileprivate var subtitleLabel: UILabel!
fileprivate var cancelButton: UIButton!
fileprivate var dotContainerWidth: CGFloat = 0
fileprivate var tappedButtons: [Int] = []
fileprivate weak var delegate: SAPinViewControllerDelegate?
fileprivate var backgroundImage: UIImage!
fileprivate var logoImage: UIImage!
/// Designate initialaiser
///
/// - parameter withDelegate: user should pass itself as `SAPinViewControllerDelegate`
/// - parameter backgroundImage: optional Image, by passing one, you will get a nice blur effect above that
/// - parameter backgroundColor: optional Color, by passing one, you will get a solid backgournd color and the blur effect would be ignored
/// - parameter logoImage: optional Image, by passing one, you will get a circled logo on top, please pass a square size image. not available for 3.5inch screen
public init(withDelegate: SAPinViewControllerDelegate, backgroundImage: UIImage? = nil, backgroundColor: UIColor? = nil, logoImage: UIImage? = nil) {
super.init(nibName: nil, bundle: nil)
delegate = withDelegate
if let safeImage = backgroundImage {
if let safeBGColor = backgroundColor {
self.view.backgroundColor = safeBGColor
} else {
self.backgroundImage = safeImage
}
}
if let safeBGColor = backgroundColor {
self.view.backgroundColor = safeBGColor
}
if let safeLogoImage = logoImage {
if !self.isSmallScreen() {
self.logoImage = safeLogoImage
}
}
self.modalPresentationStyle = UIModalPresentationStyle.formSheet
self.setupUI()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
/// Initial UI setup
func setupUI() {
dotContainerWidth = 3 * SAPinConstant.ButtonWidth + 2 * SAPinConstant.ButtonPadding
numPadView = UIView()
blurView = UIVisualEffectView(effect: UIBlurEffect(style: .light))
if backgroundImage != nil {
let imageView = UIImageView(image: backgroundImage)
imageView.contentMode = .scaleAspectFit
view.addSubview(imageView)
imageView.snp.makeConstraints({ (make) in
make.edges.equalTo(view)
})
}
view.addSubview(blurView)
view.bringSubview(toFront: blurView)
blurView.snp.makeConstraints { (make) in
make.edges.equalTo(self.view)
}
blurView.contentView.addSubview(numPadView)
numPadView.snp.makeConstraints { (make) in
make.width.equalTo(dotContainerWidth)
make.height.equalTo(4 * SAPinConstant.ButtonWidth + 3 * SAPinConstant.ButtonPadding)
make.centerX.equalTo(blurView.snp.centerX)
if logoImage != nil {
make.centerY.equalTo(blurView.snp.centerY).offset(2*SAPinConstant.ButtonPadding + SAPinConstant.LogoImageWidth)
} else {
make.centerY.equalTo(blurView.snp.centerY).offset(2*SAPinConstant.ButtonPadding)
}
}
// Add buttons
addButtons()
layoutButtons()
// Add dots
addCircles()
layoutCircles()
// Add subtitle
addSubtitle()
// Add title label
addTitle()
// Add logo
if logoImage != nil {
addLogo()
}
// Add Cancel Button
addCancelButton()
}
// MARK: Private methods
fileprivate func addButtons() {
for i in 0...9 {
let btnView = SAButtonView(frame: CGRect(x: 0, y: 0, width: SAPinConstant.ButtonWidth, height: SAPinConstant.ButtonWidth))
btnView.numberTag = i
btnView.delegate = self
buttons.append(btnView)
numPadView.addSubview(btnView)
}
}
fileprivate func layoutButtons() {
for i in 0...9 {
buttons[i].snp.makeConstraints({ (make) in
make.width.equalTo(SAPinConstant.ButtonWidth)
make.height.equalTo(SAPinConstant.ButtonWidth)
})
}
buttons[2].snp.makeConstraints { (make) in
make.top.equalTo(numPadView.snp.top)
make.centerX.equalTo(numPadView.snp.centerX)
}
buttons[5].snp.makeConstraints { (make) in
make.top.equalTo(numPadView.snp.top).offset(SAPinConstant.ButtonWidth + SAPinConstant.ButtonPadding)
make.centerX.equalTo(numPadView.snp.centerX)
}
buttons[8].snp.makeConstraints { (make) in
make.top.equalTo(numPadView.snp.top).offset(2*(SAPinConstant.ButtonWidth + SAPinConstant.ButtonPadding))
make.centerX.equalTo(numPadView.snp.centerX)
}
buttons[0].snp.makeConstraints { (make) in
make.top.equalTo(numPadView.snp.top).offset(3*(SAPinConstant.ButtonWidth + SAPinConstant.ButtonPadding))
make.centerX.equalTo(numPadView.snp.centerX)
}
buttons[1].snp.makeConstraints { (make) in
make.top.equalTo(numPadView.snp.top)
make.left.equalTo(numPadView)
}
buttons[3].snp.makeConstraints { (make) in
make.top.equalTo(numPadView.snp.top)
make.right.equalTo(numPadView)
}
buttons[4].snp.makeConstraints { (make) in
make.top.equalTo(numPadView.snp.top).offset(SAPinConstant.ButtonWidth + SAPinConstant.ButtonPadding)
make.left.equalTo(numPadView)
}
buttons[6].snp.makeConstraints { (make) in
make.top.equalTo(numPadView.snp.top).offset(SAPinConstant.ButtonWidth + SAPinConstant.ButtonPadding)
make.right.equalTo(numPadView)
}
buttons[7].snp.makeConstraints { (make) in
make.top.equalTo(numPadView.snp.top).offset(2*(SAPinConstant.ButtonWidth + SAPinConstant.ButtonPadding))
make.left.equalTo(numPadView)
}
buttons[9].snp.makeConstraints { (make) in
make.top.equalTo(numPadView.snp.top).offset(2*(SAPinConstant.ButtonWidth + SAPinConstant.ButtonPadding))
make.right.equalTo(numPadView)
}
}
fileprivate func addCircles() {
dotContainerView = UIView()
blurView.contentView.addSubview(dotContainerView)
dotContainerView.snp.makeConstraints { (make) in
make.top.equalTo(numPadView.snp.top).offset(-2*SAPinConstant.ButtonPadding)
make.height.equalTo(20)
make.width.equalTo(3*SAPinConstant.ButtonWidth + 2*SAPinConstant.ButtonPadding)
make.centerX.equalTo(numPadView.snp.centerX)
}
for _ in 0...3 {
let aBall = SACircleView(frame: CGRect(x: 0, y: 0, width: SAPinConstant.CircleWidth, height: SAPinConstant.CircleWidth))
dotContainerView.addSubview(aBall)
circleViews.append(aBall)
}
}
fileprivate func layoutCircles() {
for i in 0...3 {
circleViews[i].snp.makeConstraints({ (make) in
make.width.equalTo(SAPinConstant.CircleWidth)
make.height.equalTo(SAPinConstant.CircleWidth)
})
}
let dotLeading = (dotContainerWidth - 3*SAPinConstant.ButtonPadding - 4*SAPinConstant.CircleWidth)/2.0
circleViews[0].snp.makeConstraints { (make) in
make.leading.equalTo(dotContainerView).offset(dotLeading)
make.top.equalTo(dotContainerView)
}
circleViews[3].snp.makeConstraints { (make) in
make.trailing.equalTo(dotContainerView).offset(-dotLeading)
make.top.equalTo(dotContainerView)
}
circleViews[2].snp.makeConstraints { (make) in
make.trailing.equalTo(circleViews[3]).offset(-1.45*SAPinConstant.ButtonPadding)
make.top.equalTo(dotContainerView)
}
circleViews[1].snp.makeConstraints { (make) in
make.leading.equalTo(circleViews[0]).offset(1.45*SAPinConstant.ButtonPadding)
make.top.equalTo(dotContainerView)
}
}
fileprivate func addSubtitle() {
subtitleLabel = UILabel()
subtitleLabel.numberOfLines = 0
subtitleLabel.font = UIFont(name: SAPinConstant.DefaultFontName, size: 13.0)
subtitleLabel.textAlignment = .center
subtitleLabel.textColor = UIColor.white
blurView.contentView.addSubview(subtitleLabel)
updateSubtitle()
}
fileprivate func updateSubtitle() {
subtitleLabel.text = subtitleText
subtitleLabel.snp.remakeConstraints { (make) in
make.width.equalTo(dotContainerWidth)
make.bottom.equalTo(dotContainerView.snp.top).offset(-5)
make.centerX.equalTo(blurView.snp.centerX)
}
}
fileprivate func addTitle() {
titleLabel = UILabel()
titleLabel.numberOfLines = 1
titleLabel.font = UIFont(name: SAPinConstant.DefaultFontName, size: 17.0)
titleLabel.textAlignment = .center
titleLabel.textColor = UIColor.white
blurView.contentView.addSubview(titleLabel)
updateTitle()
}
fileprivate func updateTitle() {
titleLabel.text = titleText ?? "Enter Passcode"
titleLabel.snp.remakeConstraints { (make) in
make.width.equalTo(dotContainerWidth)
if subtitleLabel.text == "" {
make.bottom.equalTo(dotContainerView.snp.top).offset(-17)
} else {
make.bottom.equalTo(subtitleLabel.snp.top).offset(-5)
}
make.centerX.equalTo(blurView.snp.centerX)
}
}
fileprivate func addLogo() {
let logoImageView = UIImageView(image: logoImage)
blurView.contentView.addSubview(logoImageView)
logoImageView.contentMode = .scaleAspectFit
logoImageView.layer.cornerRadius = SAPinConstant.LogoImageWidth/2.0
logoImageView.clipsToBounds = true
logoImageView.snp.makeConstraints { (make) in
make.width.equalTo(SAPinConstant.LogoImageWidth)
make.height.equalTo(SAPinConstant.LogoImageWidth)
make.centerX.equalTo(blurView.snp.centerX)
make.bottom.equalTo(titleLabel.snp.top).offset(-8)
}
}
fileprivate func addCancelButton() {
cancelButton = UIButton(type: .custom)
cancelButtonColor = titleLabel.textColor
cancelButtonFont = titleLabel.font
setAttributedTitleForButtonWithTitle(SAPinConstant.CancelString, font: cancelButtonFont, color: cancelButtonColor)
cancelButton.addTarget(self, action: #selector(self.cancelDeleteTap), for: .touchUpInside)
blurView.contentView.addSubview(cancelButton)
cancelButton.snp.makeConstraints { (make) in
make.trailing.equalTo(numPadView.snp.trailing)
if UIDevice.current.userInterfaceIdiom == .phone {
// 3.5" special case
if isSmallScreen() {
make.bottom.equalTo(numPadView)
} else {
if logoImage != nil {
make.bottom.equalTo(numPadView).offset(SAPinConstant.ButtonWidth - SAPinConstant.LogoImageWidth)
} else {
make.bottom.equalTo(numPadView).offset(SAPinConstant.ButtonWidth)
}
}
} else {
make.bottom.equalTo(numPadView)
}
make.height.equalTo(44)
}
}
func cancelDeleteTap() {
if cancelButton.titleLabel?.text == SAPinConstant.DeleteString {
if tappedButtons.count > 0 {
circleViews[tappedButtons.count-1].animateTapEmpty()
let _ = tappedButtons.removeLast()
}
if tappedButtons.count == 0 {
setAttributedTitleForButtonWithTitle(SAPinConstant.CancelString, font: cancelButtonFont, color: cancelButtonColor)
}
} else {
delegate?.pinEntryWasCancelled()
}
}
fileprivate func isSmallScreen() -> Bool {
return UIScreen.main.bounds.height == 480
}
fileprivate func setAttributedTitleForButtonWithTitle(_ title: String, font: UIFont, color: UIColor) {
cancelButton.setAttributedTitle(NSAttributedString(string: title, attributes: [NSFontAttributeName:font,NSForegroundColorAttributeName:color]), for: UIControlState())
}
fileprivate func pinErrorAnimate() {
for item in circleViews {
UIView.animate(withDuration: 0.1, animations: {
item.backgroundColor = item.circleBorderColor.withAlphaComponent(0.7)
}, completion: { finished in
UIView.animate(withDuration: 0.5, animations: {
item.backgroundColor = UIColor.clear
})
})
}
animateView()
}
fileprivate func animateView() {
setOptions()
animate()
}
fileprivate func setOptions() {
for item in circleViews {
item.force = 2.2
item.duration = 1
item.delay = 0
item.damping = 0.7
item.velocity = 0.7
item.animation = "spring"
}
}
fileprivate func animate() {
for item in circleViews {
item.animateFrom = true
item.animatePreset()
item.setView{}
}
}
}
extension SAPinViewController: SAButtonViewDelegate {
func buttonTappedWithTag(_ tag: Int) {
if tappedButtons.count < 4 {
circleViews[tappedButtons.count].animateTapFull()
tappedButtons.append(tag)
setAttributedTitleForButtonWithTitle(SAPinConstant.DeleteString, font: cancelButtonFont, color: cancelButtonColor)
if tappedButtons.count == 4 {
if delegate!.isPinValid("\(tappedButtons[0])\(tappedButtons[1])\(tappedButtons[2])\(tappedButtons[3])") {
delegate?.pinEntryWasSuccessful()
} else {
delegate?.pinWasIncorrect()
pinErrorAnimate()
tappedButtons = []
setAttributedTitleForButtonWithTitle(SAPinConstant.CancelString, font: cancelButtonFont, color: cancelButtonColor)
}
}
}
}
}
| mit | d9059b4b3e0a5c425dc6837e7bfa80c2 | 36.918033 | 176 | 0.595139 | 4.869474 | false | false | false | false |
ilyapuchka/StencilJS | Pods/Stencil/Sources/Loader.swift | 3 | 2562 | import Foundation
import PathKit
public protocol Loader {
func loadTemplate(name: String, environment: Environment) throws -> Template
func loadTemplate(names: [String], environment: Environment) throws -> Template
}
extension Loader {
public func loadTemplate(names: [String], environment: Environment) throws -> Template {
for name in names {
do {
return try loadTemplate(name: name, environment: environment)
} catch is TemplateDoesNotExist {
continue
} catch {
throw error
}
}
throw TemplateDoesNotExist(templateNames: names, loader: self)
}
}
// A class for loading a template from disk
public class FileSystemLoader: Loader, CustomStringConvertible {
public let paths: [Path]
public init(paths: [Path]) {
self.paths = paths
}
public init(bundle: [Bundle]) {
self.paths = bundle.map {
return Path($0.bundlePath)
}
}
public var description: String {
return "FileSystemLoader(\(paths))"
}
public func loadTemplate(name: String, environment: Environment) throws -> Template {
for path in paths {
let templatePath = try path.safeJoin(path: Path(name))
if !templatePath.exists {
continue
}
let content: String = try templatePath.read()
return try environment.templateClass.init(templateString: content, environment: environment, name: name)
}
throw TemplateDoesNotExist(templateNames: [name], loader: self)
}
public func loadTemplate(names: [String], environment: Environment) throws -> Template {
for path in paths {
for templateName in names {
let templatePath = try path.safeJoin(path: Path(templateName))
if templatePath.exists {
let content: String = try templatePath.read()
return try environment.templateClass.init(templateString: content, environment: environment, name: templateName)
}
}
}
throw TemplateDoesNotExist(templateNames: names, loader: self)
}
}
extension Path {
func safeJoin(path: Path) throws -> Path {
let newPath = self + path
if !newPath.absolute().description.hasPrefix(absolute().description) {
throw SuspiciousFileOperation(basePath: self, path: newPath)
}
return newPath
}
}
class SuspiciousFileOperation: Error {
let basePath: Path
let path: Path
init(basePath: Path, path: Path) {
self.basePath = basePath
self.path = path
}
var description: String {
return "Path `\(path)` is located outside of base path `\(basePath)`"
}
}
| mit | 45279e46d6f73687db496ff7d9211a2e | 23.873786 | 122 | 0.676034 | 4.409639 | false | false | false | false |
JeromeTan1997/LocationPicker | LocationPickerDemo/LocationPickerDemo/ViewController.swift | 1 | 4943 | //
// ViewController.swift
// LocationPickerExample
//
// Created by Jerome Tan on 3/29/16.
// Copyright © 2016 Jerome Tan. All rights reserved.
//
import UIKit
import LocationPicker
class ViewController: UIViewController, LocationPickerDelegate, LocationPickerDataSource {
@IBOutlet weak var locationNameTextField: UITextField!
@IBOutlet weak var locationAddressTextField: UITextField!
@IBOutlet weak var arbitraryLocationSwitch: UISwitch!
var historyLocationList: [LocationItem] {
get {
if let locationDataList = UserDefaults.standard.array(forKey: "HistoryLocationList") as? [Data] {
// Decode NSData into LocationItem object.
return locationDataList.map({ NSKeyedUnarchiver.unarchiveObject(with: $0) as! LocationItem })
} else {
return []
}
}
set {
// Encode LocationItem object.
let locationDataList = newValue.map({ NSKeyedArchiver.archivedData(withRootObject: $0) })
UserDefaults.standard.set(locationDataList, forKey: "HistoryLocationList")
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
locationNameTextField.text = nil
locationAddressTextField.text = nil
}
// MARK: Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Show Location Picker via push segue.
// LocationPicker in Storyboard.
if segue.identifier == "LocationPicker" {
let locationPicker = segue.destination as! LocationPicker
// User delegate and dataSource.
locationPicker.delegate = self
locationPicker.dataSource = self
locationPicker.isAlternativeLocationEditable = true
locationPicker.isAllowArbitraryLocation = arbitraryLocationSwitch.isOn
}
}
@IBAction func presentLocationPickerButtonDidTap(button: UIButton) {
// Present Location Picker subclass via codes.
// Create LocationPicker subclass.
let customLocationPicker = CustomLocationPicker()
customLocationPicker.isAllowArbitraryLocation = arbitraryLocationSwitch.isOn
customLocationPicker.viewController = self
let navigationController = UINavigationController(rootViewController: customLocationPicker)
present(navigationController, animated: true, completion: nil)
}
// Push LocationPicker to navigation controller.
@IBAction func pushLocationPickerButtonDidTap(button: UIButton) {
// Push Location Picker via codes.
let locationPicker = LocationPicker()
locationPicker.alternativeLocations = historyLocationList.reversed()
locationPicker.isAlternativeLocationEditable = true
locationPicker.preselectedIndex = 0
locationPicker.isAllowArbitraryLocation = arbitraryLocationSwitch.isOn
// Completion closures
locationPicker.selectCompletion = { selectedLocationItem in
print("Select completion closure: " + selectedLocationItem.name)
}
locationPicker.pickCompletion = { pickedLocationItem in
self.showLocation(locationItem: pickedLocationItem)
self.storeLocation(locationItem: pickedLocationItem)
}
locationPicker.deleteCompletion = { locationItem in
self.historyLocationList.remove(at: self.historyLocationList.index(of: locationItem)!)
}
navigationController!.pushViewController(locationPicker, animated: true)
}
// Location Picker Delegate
func locationDidSelect(locationItem: LocationItem) {
print("Select delegate method: " + locationItem.name)
}
func locationDidPick(locationItem: LocationItem) {
showLocation(locationItem: locationItem)
storeLocation(locationItem: locationItem)
}
// Location Picker Data Source
func numberOfAlternativeLocations() -> Int {
return historyLocationList.count
}
func alternativeLocation(at index: Int) -> LocationItem {
return historyLocationList.reversed()[index]
}
func commitAlternativeLocationDeletion(locationItem: LocationItem) {
historyLocationList.remove(at: historyLocationList.index(of: locationItem)!)
}
func showLocation(locationItem: LocationItem) {
locationNameTextField.text = locationItem.name
locationAddressTextField.text = locationItem.formattedAddressString
}
func storeLocation(locationItem: LocationItem) {
if let index = historyLocationList.index(of: locationItem) {
historyLocationList.remove(at: index)
}
historyLocationList.append(locationItem)
}
}
| mit | 54fa92ac1001897baa58a232b8c26b9a | 35.072993 | 109 | 0.678268 | 5.596829 | false | false | false | false |
LeeShiYoung/RxSwiftXinWen | XW/XW/Classes/News/ViewModel/ContentViewModel.swift | 1 | 2179 | //
// ContentViewModel.swift
// XW
//
// Created by 李世洋 on 2017/9/10.
// Copyright © 2017年 浙江聚有财金融服务外包有限公司. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
import Kanna
import Kingfisher
import RxDataSources
struct ContentViewModel {
let parameter = Variable("")
var datas: Driver<[SectionModel<String, ContentModel>]>
init() {
self.datas = self.parameter.asDriver().flatMap { parm in
return API.request(.content(parm))
.filterSuccessfulStatusCodes()
.mapString()
.mapContentModels()
.asDriver(onErrorJustReturn: [SectionModel(model: "", items: [])])
}
}
}
fileprivate extension PrimitiveSequence where TraitType == SingleTrait, ElementType == String {
fileprivate func mapContentModels() -> Single<[SectionModel<String, ContentModel>]> {
return flatMap { html -> Single<[SectionModel<String, ContentModel>]> in
var datas = [ContentModel]()
if let doc = HTML(html: html, encoding: .utf8) {
for element in doc.xpath("//p | //a/img") {//| //a/img/@data-width
var contentModel = ContentModel()
if let text = element.text, !text.isEmpty {
contentModel.text = text.addLineSpace(15)
contentModel.identifier = ContentTextTableViewCell.toString()
datas.append(contentModel)
}
if let href = element["src"], let height = element["data-height"], let width = element["data-width"] {
contentModel.img = href
contentModel.identifier = ContentImgTableViewCell.toString()
contentModel.size = CGSize(width: Double(width) ?? 0.0, height: Double(height) ?? 0.0).scaleSize()
datas.append(contentModel)
}
}
}
return Single.just([SectionModel(model: "", items: datas)])
}
}
}
| apache-2.0 | 967b11cf5c0c05fc5c24b076c22e549a | 35.271186 | 122 | 0.548131 | 4.874715 | false | false | false | false |
MxABC/oclearning | swiftLearning/Pods/Alamofire/Source/ServerTrustPolicy.swift | 32 | 13049 | // ServerTrustPolicy.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/// Responsible for managing the mapping of `ServerTrustPolicy` objects to a given host.
public class ServerTrustPolicyManager {
/// The dictionary of policies mapped to a particular host.
public let policies: [String: ServerTrustPolicy]
/**
Initializes the `ServerTrustPolicyManager` instance with the given policies.
Since different servers and web services can have different leaf certificates, intermediate and even root
certficates, it is important to have the flexibility to specify evaluation policies on a per host basis. This
allows for scenarios such as using default evaluation for host1, certificate pinning for host2, public key
pinning for host3 and disabling evaluation for host4.
- parameter policies: A dictionary of all policies mapped to a particular host.
- returns: The new `ServerTrustPolicyManager` instance.
*/
public init(policies: [String: ServerTrustPolicy]) {
self.policies = policies
}
/**
Returns the `ServerTrustPolicy` for the given host if applicable.
By default, this method will return the policy that perfectly matches the given host. Subclasses could override
this method and implement more complex mapping implementations such as wildcards.
- parameter host: The host to use when searching for a matching policy.
- returns: The server trust policy for the given host if found.
*/
public func serverTrustPolicyForHost(host: String) -> ServerTrustPolicy? {
return policies[host]
}
}
// MARK: -
extension NSURLSession {
private struct AssociatedKeys {
static var ManagerKey = "NSURLSession.ServerTrustPolicyManager"
}
var serverTrustPolicyManager: ServerTrustPolicyManager? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.ManagerKey) as? ServerTrustPolicyManager
}
set (manager) {
objc_setAssociatedObject(self, &AssociatedKeys.ManagerKey, manager, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
// MARK: - ServerTrustPolicy
/**
The `ServerTrustPolicy` evaluates the server trust generally provided by an `NSURLAuthenticationChallenge` when
connecting to a server over a secure HTTPS connection. The policy configuration then evaluates the server trust
with a given set of criteria to determine whether the server trust is valid and the connection should be made.
Using pinned certificates or public keys for evaluation helps prevent man-in-the-middle (MITM) attacks and other
vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged
to route all communication over an HTTPS connection with pinning enabled.
- PerformDefaultEvaluation: Uses the default server trust evaluation while allowing you to control whether to
validate the host provided by the challenge. Applications are encouraged to always
validate the host in production environments to guarantee the validity of the server's
certificate chain.
- PinCertificates: Uses the pinned certificates to validate the server trust. The server trust is
considered valid if one of the pinned certificates match one of the server certificates.
By validating both the certificate chain and host, certificate pinning provides a very
secure form of server trust validation mitigating most, if not all, MITM attacks.
Applications are encouraged to always validate the host and require a valid certificate
chain in production environments.
- PinPublicKeys: Uses the pinned public keys to validate the server trust. The server trust is considered
valid if one of the pinned public keys match one of the server certificate public keys.
By validating both the certificate chain and host, public key pinning provides a very
secure form of server trust validation mitigating most, if not all, MITM attacks.
Applications are encouraged to always validate the host and require a valid certificate
chain in production environments.
- DisableEvaluation: Disables all evaluation which in turn will always consider any server trust as valid.
- CustomEvaluation: Uses the associated closure to evaluate the validity of the server trust.
*/
public enum ServerTrustPolicy {
case PerformDefaultEvaluation(validateHost: Bool)
case PinCertificates(certificates: [SecCertificate], validateCertificateChain: Bool, validateHost: Bool)
case PinPublicKeys(publicKeys: [SecKey], validateCertificateChain: Bool, validateHost: Bool)
case DisableEvaluation
case CustomEvaluation((serverTrust: SecTrust, host: String) -> Bool)
// MARK: - Bundle Location
/**
Returns all certificates within the given bundle with a `.cer` file extension.
- parameter bundle: The bundle to search for all `.cer` files.
- returns: All certificates within the given bundle.
*/
public static func certificatesInBundle(bundle: NSBundle = NSBundle.mainBundle()) -> [SecCertificate] {
var certificates: [SecCertificate] = []
let paths = Set([".cer", ".CER", ".crt", ".CRT", ".der", ".DER"].map { fileExtension in
bundle.pathsForResourcesOfType(fileExtension, inDirectory: nil)
}.flatten())
for path in paths {
if let
certificateData = NSData(contentsOfFile: path),
certificate = SecCertificateCreateWithData(nil, certificateData)
{
certificates.append(certificate)
}
}
return certificates
}
/**
Returns all public keys within the given bundle with a `.cer` file extension.
- parameter bundle: The bundle to search for all `*.cer` files.
- returns: All public keys within the given bundle.
*/
public static func publicKeysInBundle(bundle: NSBundle = NSBundle.mainBundle()) -> [SecKey] {
var publicKeys: [SecKey] = []
for certificate in certificatesInBundle(bundle) {
if let publicKey = publicKeyForCertificate(certificate) {
publicKeys.append(publicKey)
}
}
return publicKeys
}
// MARK: - Evaluation
/**
Evaluates whether the server trust is valid for the given host.
- parameter serverTrust: The server trust to evaluate.
- parameter host: The host of the challenge protection space.
- returns: Whether the server trust is valid.
*/
public func evaluateServerTrust(serverTrust: SecTrust, isValidForHost host: String) -> Bool {
var serverTrustIsValid = false
switch self {
case let .PerformDefaultEvaluation(validateHost):
let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil)
SecTrustSetPolicies(serverTrust, [policy])
serverTrustIsValid = trustIsValid(serverTrust)
case let .PinCertificates(pinnedCertificates, validateCertificateChain, validateHost):
if validateCertificateChain {
let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil)
SecTrustSetPolicies(serverTrust, [policy])
SecTrustSetAnchorCertificates(serverTrust, pinnedCertificates)
SecTrustSetAnchorCertificatesOnly(serverTrust, true)
serverTrustIsValid = trustIsValid(serverTrust)
} else {
let serverCertificatesDataArray = certificateDataForTrust(serverTrust)
let pinnedCertificatesDataArray = certificateDataForCertificates(pinnedCertificates)
outerLoop: for serverCertificateData in serverCertificatesDataArray {
for pinnedCertificateData in pinnedCertificatesDataArray {
if serverCertificateData.isEqualToData(pinnedCertificateData) {
serverTrustIsValid = true
break outerLoop
}
}
}
}
case let .PinPublicKeys(pinnedPublicKeys, validateCertificateChain, validateHost):
var certificateChainEvaluationPassed = true
if validateCertificateChain {
let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil)
SecTrustSetPolicies(serverTrust, [policy])
certificateChainEvaluationPassed = trustIsValid(serverTrust)
}
if certificateChainEvaluationPassed {
outerLoop: for serverPublicKey in ServerTrustPolicy.publicKeysForTrust(serverTrust) as [AnyObject] {
for pinnedPublicKey in pinnedPublicKeys as [AnyObject] {
if serverPublicKey.isEqual(pinnedPublicKey) {
serverTrustIsValid = true
break outerLoop
}
}
}
}
case .DisableEvaluation:
serverTrustIsValid = true
case let .CustomEvaluation(closure):
serverTrustIsValid = closure(serverTrust: serverTrust, host: host)
}
return serverTrustIsValid
}
// MARK: - Private - Trust Validation
private func trustIsValid(trust: SecTrust) -> Bool {
var isValid = false
var result = SecTrustResultType(kSecTrustResultInvalid)
let status = SecTrustEvaluate(trust, &result)
if status == errSecSuccess {
let unspecified = SecTrustResultType(kSecTrustResultUnspecified)
let proceed = SecTrustResultType(kSecTrustResultProceed)
isValid = result == unspecified || result == proceed
}
return isValid
}
// MARK: - Private - Certificate Data
private func certificateDataForTrust(trust: SecTrust) -> [NSData] {
var certificates: [SecCertificate] = []
for index in 0..<SecTrustGetCertificateCount(trust) {
if let certificate = SecTrustGetCertificateAtIndex(trust, index) {
certificates.append(certificate)
}
}
return certificateDataForCertificates(certificates)
}
private func certificateDataForCertificates(certificates: [SecCertificate]) -> [NSData] {
return certificates.map { SecCertificateCopyData($0) as NSData }
}
// MARK: - Private - Public Key Extraction
private static func publicKeysForTrust(trust: SecTrust) -> [SecKey] {
var publicKeys: [SecKey] = []
for index in 0..<SecTrustGetCertificateCount(trust) {
if let
certificate = SecTrustGetCertificateAtIndex(trust, index),
publicKey = publicKeyForCertificate(certificate)
{
publicKeys.append(publicKey)
}
}
return publicKeys
}
private static func publicKeyForCertificate(certificate: SecCertificate) -> SecKey? {
var publicKey: SecKey?
let policy = SecPolicyCreateBasicX509()
var trust: SecTrust?
let trustCreationStatus = SecTrustCreateWithCertificates(certificate, policy, &trust)
if let trust = trust where trustCreationStatus == errSecSuccess {
publicKey = SecTrustCopyPublicKey(trust)
}
return publicKey
}
}
| mit | 7f67a56905e7cca86d8f3276949bbab3 | 42.201987 | 121 | 0.661455 | 6.088194 | false | false | false | false |
ResearchSuite/ResearchSuiteExtensions-iOS | Example/Pods/ResearchSuiteTaskBuilder/ResearchSuiteTaskBuilder/Classes/Consent/RSTBStandardConsentDocumentGenerator.swift | 1 | 2036 | //
// RSTBStandardConsentDocumentGenerator.swift
// Pods
//
// Created by James Kizer on 7/26/17.
//
//
import UIKit
import Gloss
import ResearchKit
open class RSTBStandardConsentDocument: ORKConsentDocument, RSTBConsentDocumentGenerator {
open static func supportsType(type: String) -> Bool {
return type == "standardConsentDocument"
}
open static func generate(type: String, jsonObject: JSON, helper: RSTBTaskBuilderHelper) -> ORKConsentDocument? {
guard let descriptor = RSTBStandardConsentDocumentDescriptor(json: jsonObject),
let taskBuilder = helper.builder else {
return nil
}
let sections:[ORKConsentSection] = descriptor.sections.flatMap { sectionJSON in
guard let type: String = "type" <~~ sectionJSON else {
return nil
}
return taskBuilder.generateConsentSection(type: type, jsonObject: sectionJSON, helper: helper)
}
let signatures: [ORKConsentSignature] = descriptor.signatures.flatMap { signatureJSON in
guard let type: String = "type" <~~ signatureJSON else {
return nil
}
return taskBuilder.generateConsentSignature(type: type, jsonObject: signatureJSON, helper: helper)
}
return RSTBStandardConsentDocument(
title: descriptor.title,
sections: sections,
signatures: signatures
)
}
public init(
title: String,
sections: [ORKConsentSection],
signatures: [ORKConsentSignature]
) {
super.init()
self.title = title
self.sections = sections
signatures.forEach { self.addSignature($0) }
}
override public init() {
super.init()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| apache-2.0 | acfb0d970419a56c7b59fa66347206bc | 27.277778 | 117 | 0.593811 | 5.207161 | false | false | false | false |
EZ-NET/CodePiece | CodePiece/SNS/PostError.swift | 1 | 2835 | //
// PostError.swift
// CodePieceCore
//
// Created by kumagai on 2020/05/26.
// Copyright © 2020 Tomohiro Kumagai. All rights reserved.
//
import ESTwitter
extension SNSController {
/// This means a error which may occur when post.
public enum PostError : Error {
public enum State {
case occurred(on: PostDataContainer.PostStage)
case postGistDirectly
case postMediaDirectly
case postTweetDirectly
case unidentifiable
}
case unexpected(Error, state: State)
case systemError(String, state: State)
case description(String, state: State)
case authentication(AuthenticationError, state: State)
// case PostTextTooLong(limit: Int)
case failedToUploadMedia(reason: String, state: State)
case twitterError(ESTwitter.PostError, state: State)
case postError(String, state: State)
}
}
extension SNSController.PostError : CustomStringConvertible {
var description: String {
func prefix(for state: State) -> String {
guard
!state.isUnidentifiable,
case let .occurred(stage) = state else {
return ""
}
let allStages = PostDataContainer.PostStage.allCases
guard allStages.first != stage else {
return ""
}
let indexOfCurrentStage = allStages.firstIndex(of: stage)!
let passedStage = allStages[indexOfCurrentStage - 1]
switch passedStage {
case .initialized:
return ""
case .postToGists, .captureGists:
return "Posted gist, but following error occurred: "
case .postProcessToTwitter, .postToTwitterMedia:
return "Posted gist, but following error occurred: "
case .postToTwitterStatus, .posted:
return "All items posted completely, but following error occurred: "
}
}
switch self {
case .unexpected(_, let state),
.systemError(_, let state),
.description(_, let state),
.authentication(_, let state),
.failedToUploadMedia(_, let state),
.twitterError(_, let state),
.postError(_, let state):
return prefix(for: state) + descriptionWithoutState
}
}
var descriptionWithoutState: String {
switch self {
case .unexpected(let error, _):
return "Unexpected error: \(error)"
case .systemError(let message, _):
return "System Error: \(message)"
case .description(let message, _):
return message
case .authentication(let error, _):
return "Authentication Error: \(error)"
case .failedToUploadMedia(let reason, _):
return "Failed to upload the media. \(reason)"
case .twitterError(let error, _):
return "\(error)"
case .postError(let message, _):
return "System Error: \(message)"
}
}
}
extension PostError.State {
var isUnidentifiable: Bool {
if case .unidentifiable = self {
return true
}
else {
return false
}
}
}
| gpl-3.0 | 6ab277dc69dee26e481e923b0083dd17 | 20.8 | 72 | 0.669019 | 3.798928 | false | false | false | false |
Q42/Q42.ImagePreview.swift | example/ImagePreviewDemo/CollectionViewController.swift | 1 | 5776 | //
// ViewController.swift
// ImagePreview
//
// Created by Tim van Steenis on 10/26/2015.
// Copyright (c) 2015 Tim van Steenis. All rights reserved.
//
import UIKit
import ImagePreview
class CollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
fileprivate var items: [ImagePreviewCell.ViewModel] = []
override func viewDidLoad() {
super.viewDidLoad()
if let flowLayout = collectionView?.collectionViewLayout as? UICollectionViewFlowLayout {
flowLayout.minimumInteritemSpacing = 0.0
flowLayout.minimumLineSpacing = 0.0
}
collectionView?.register(UINib.init(nibName: "ImagePreviewCell", bundle: nil), forCellWithReuseIdentifier: "ImagePreviewCell")
items = [
// 1
ImagePreviewCell.ViewModel(
url: URL(string: "https://raw.githubusercontent.com/Q42/Q42.ImagePreview.swift/master/demo-resources/img1.jpg")!,
size: CGSize(width: 4157, height: 2811),
preview: "AQAUAB7/2gAMAwEAAhEDEQA/AILTR7wIu+KOOFgP9YMZ/wAR9K00tRY2/mCWBmRflQA456n7vP0rlrbQbxLEKNdhZmxiJHYgd8cAD8qtzRXNrY7JLgu4TOxlbHX35rGrjK0Ivlj/AF3Kp4enKSuzQuNOmuo2a3bzROdzskeAx9M9cVWPhaUY81VjJGfnIXNSafqKxRFZtUOnsQf3Uasx+p5wKzbjTLyeXdb3Fpf5HMhlcH8dxreGYYlUlJ07ee6/QylhaXtGuf5HNxKPvHJYAck1ZRyVVTyGz19u9FFK7CxFcSuYi7MSQ+0ZOeKYLuaIYVsdaKK6KTZnJI//2Q=="
),
ImagePreviewCell.ViewModel(
url: URL(string: "https://raw.githubusercontent.com/Q42/Q42.ImagePreview.swift/master/demo-resources/img1.jpg")!,
size: CGSize(width: 4157, height: 2811),
preview: "AgAUAB7/2gAMAwEAAhEDEQA/AK1rplzsDPtWNvXn8eK1TClnD5gdSwGMYOAOvp/OuOg0y2EARdQy5x8uMDPpyRV2X9xAEWbeygcHGOvbk1jVxNaMXyxKp0acmrs1ZdLmuU/0fLo53FgMAn9aoTaGIztmdEPozAVJFfWqRNDc3EkTkEFYx8oz+PNZcti0j7rae3kX1kBU/wAzzXTHF4nkTdP9fy2MXQpczXN+h//Q80jc5HA5qeKd2G04x6fSqsfb/PenwdR+P86m7FZCvNIYi2futioJ7yePhW6U5v8AUP8A7wqnddfxreDZDSP/2Q=="
),
// 2
ImagePreviewCell.ViewModel(
url: URL(string: "https://raw.githubusercontent.com/Q42/Q42.ImagePreview.swift/master/demo-resources/img2.jpg")!,
size: CGSize(width: 8000, height: 3876),
preview: "AQAOAB7/2gAMAwEAAhEDEQA/AOt1HWtK0u5jtb/UI4pGj3cAttGO5GcZ5xVefSNAubdrmO9t1jU7TIjKVB64Pb8K5y20jTIm3rBJtZccsM9PXFTSaVps67Y4GTrk8Zz29vzFc0c4pxelzollkpLVIsvKlvKILbVLPG7KLvXJI5zx06ViPqkVzJhdWtwBk524B5+lXX8P6f8AL5QmXaMAkrkfjjNQroNmCRI0uTzlAgz/AOO1ss+orW34HP8A2NUf2vxP/9k="
),
ImagePreviewCell.ViewModel(
url: URL(string: "https://raw.githubusercontent.com/Q42/Q42.ImagePreview.swift/master/demo-resources/img2.jpg")!,
size: CGSize(width: 8000, height: 3876),
preview: "AgAOAB7/2gAMAwEAAhEDEQA/AOnuta0W2lFrcXG47ckxguAD2JGetQzW3heSL7StwigHbuBHUdsGueijsI2JEAweMZNWGjsp/wDliFA9Dz19ev61yrNop6JnVLLJNaivd2kZKQ3seEBIA7AdfasGS8tbn/l6CgcjKkf0rWa2sH+ZImUY4wx4x6VRmt9PCjzI2bn+8Rz+BrZZ3D+Uw/seT+0f/9k="
),
// 3
ImagePreviewCell.ViewModel(
url: URL(string: "https://raw.githubusercontent.com/Q42/Q42.ImagePreview.swift/master/demo-resources/img3.jpg")!,
size: CGSize(width: 4256, height: 2832),
preview: "AQATAB7/2gAMAwEAAhEDEQA/AG2GhCRQ1vZs4I2iOeYK/T0I/ka2NCuZrVXY6YhsnG1wuGJPPrz0zXN23ifVLu63/Z4EnYL86xBm7Y53D2p2oatrahPsmo2G903hrePD4AHU/iKpVrqzM+VLY7oXOn3NuskE+xEOXSeQKmOehxk9ulZd9f6VLessEts6qoyVuDtz3wDXl+pXOq3LkXlw8jng+Y+eT6DGB07VWVL0Sf6iNvlACluMetXGaTIk01a5NYoBaAjOflPU1dktYXCEpz04JFFFeTV0N2Uru0iEqAK2CxGN56fnWZcFoJ8Ru6gKONxooq6Mm92JH//Z"
),
ImagePreviewCell.ViewModel(
url: URL(string: "https://raw.githubusercontent.com/Q42/Q42.ImagePreview.swift/master/demo-resources/img3.jpg")!,
size: CGSize(width: 4256, height: 2832),
preview: "AgAUAB7/2gAMAwEAAhEDEQA/AI7TSFdN8UG8c/LI4DcexH8jW5pcjQIXmtVMDDtzyOevXpXL2+vanPLuEaJIcfMFBPtzkUt9qOtrgWtxCCV3ZiXBxjHJ5qlVvozO1tjv9+mOizRyBUX7wlbA/DHJ/CsG9udOmnf7M0bKDxmQsPwzivLr2bUp5MXDlmz/ABHPv3HH0FRRi8DnMat7bsYq4zsyG01uf//Q4KGMJCCpPOD1+tWHijYjI7VEn+pX6D+tWW6j6VwT7gzLlhjYgnPOe5qlcFracrGxIwOpz2rRft9TWdqH/HyfoP5VVNtvUSP/2Q=="
),
// 4
ImagePreviewCell.ViewModel(
url: URL(string: "https://raw.githubusercontent.com/Q42/Q42.ImagePreview.swift/master/demo-resources/img4.jpg")!,
size: CGSize(width: 4288, height: 2848),
preview: "AQATAB7/2gAMAwEAAhEDEQA/ALI1/wAMOoKa1Z9OhDA9PcVVudb0wofsjCc9iuMVyQ0rw5D0iupD/tT4/kKZIbGEf6JmMjpnn9a9j2mKS6HlqjSv1NybWxuBS3Xrzk//AFqmt9dszkzJJE3psDD8CK5OS6YdJgfbmnQ3MRz5s0hP+zgCppV8W3b8zSdGlb/IrRqHhVmySfeqbMdxGT1oorGTZ0WDJOM0vQ0UUoPUTP/Z"
),
ImagePreviewCell.ViewModel(
url: URL(string: "https://raw.githubusercontent.com/Q42/Q42.ImagePreview.swift/master/demo-resources/img4.jpg")!,
size: CGSize(width: 4288, height: 2848),
preview: "AgAUAB7/2gAMAwEAAhEDEQA/ALC6v4YYZW+i+nI/mKqXGqadj/RT5vuOlceun+Hoh92Vj7v/AIAVG5s4v+PU7frzXsOriEjzFRp36m9Jqg3ZWMe/NSpqlkVy4ZT6Yz+orkXuGHR/505JoSPmds+2BSpV8T/w5c6VM//Q8o+0OB2P51EZXxnNNPSmnp+Fd0mzCxOGLdaCSOlNT/GlaiDYmf/Z"
)
]
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return items.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
return collectionView.dequeueReusableCell(withReuseIdentifier: "ImagePreviewCell", for: indexPath) as! ImagePreviewCell
}
override func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
(cell as! ImagePreviewCell).viewModel = items[indexPath.row]
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return collectionView.frame.size
}
}
| mit | 4cff5f02d8cbc555354992265d53436a | 57.343434 | 359 | 0.789301 | 2.436103 | false | false | false | false |
chinlam91/edx-app-ios | Source/OEXRouter+Swift.swift | 3 | 11090 | //
// OEXRouter+Swift.swift
// edX
//
// Created by Akiva Leffert on 5/7/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import Foundation
// The router is an indirection point for navigation throw our app.
// New router logic should live here so it can be written in Swift.
// We should gradually migrate the existing router class here and then
// get rid of the objc version
enum CourseHTMLBlockSubkind {
case Base
case Problem
}
enum CourseBlockDisplayType {
case Unknown
case Outline
case Unit
case Video
case HTML(CourseHTMLBlockSubkind)
var isUnknown : Bool {
switch self {
case Unknown: return true
default: return false
}
}
}
extension CourseBlock {
var displayType : CourseBlockDisplayType {
switch self.type {
case .Unknown(_), .HTML: return multiDevice ? .HTML(.Base) : .Unknown
case .Problem: return multiDevice ? .HTML(.Problem) : .Unknown
case .Course: return .Outline
case .Chapter: return .Outline
case .Section: return .Outline
case .Unit: return .Unit
case .Video(_): return .Video
}
}
}
extension OEXRouter {
func showCoursewareForCourseWithID(courseID : String, fromController controller : UIViewController) {
showContainerForBlockWithID(nil, type: CourseBlockDisplayType.Outline, parentID: nil, courseID : courseID, fromController: controller)
}
func unitControllerForCourseID(courseID : String, blockID : CourseBlockID?, initialChildID : CourseBlockID?) -> CourseContentPageViewController {
let environment = CourseContentPageViewController.Environment(
analytics: self.environment.analytics,
dataManager: self.environment.dataManager,
router: self,
styles : self.environment.styles)
let contentPageController = CourseContentPageViewController(environment: environment, courseID: courseID, rootID: blockID, initialChildID: initialChildID)
return contentPageController
}
func showContainerForBlockWithID(blockID : CourseBlockID?, type : CourseBlockDisplayType, parentID : CourseBlockID?, courseID : CourseBlockID, fromController controller: UIViewController) {
switch type {
case .Outline:
fallthrough
case .Unit:
let outlineController = controllerForBlockWithID(blockID, type: type, courseID: courseID)
controller.navigationController?.pushViewController(outlineController, animated: true)
case .HTML:
fallthrough
case .Video:
fallthrough
case .Unknown:
let pageController = unitControllerForCourseID(courseID, blockID: parentID, initialChildID: blockID)
if let delegate = controller as? CourseContentPageViewControllerDelegate {
pageController.navigationDelegate = delegate
}
controller.navigationController?.pushViewController(pageController, animated: true)
}
}
private func controllerForBlockWithID(blockID : CourseBlockID?, type : CourseBlockDisplayType, courseID : String) -> UIViewController {
switch type {
case .Outline:
let environment = CourseOutlineViewController.Environment(
analytics : self.environment.analytics,
dataManager: self.environment.dataManager,
networkManager : self.environment.networkManager,
reachability : InternetReachability(), router: self,
styles : self.environment.styles)
let outlineController = CourseOutlineViewController(environment: environment, courseID: courseID, rootID: blockID)
return outlineController
case .Unit:
return unitControllerForCourseID(courseID, blockID: blockID, initialChildID: nil)
case .HTML:
let environment = HTMLBlockViewController.Environment(config : self.environment.config, courseDataManager : self.environment.dataManager.courseDataManager, session : self.environment.session, styles : self.environment.styles)
let controller = HTMLBlockViewController(blockID: blockID, courseID : courseID, environment : environment)
return controller
case .Video:
let environment = VideoBlockViewController.Environment(courseDataManager: self.environment.dataManager.courseDataManager, interface : self.environment.interface, styles : self.environment.styles)
let controller = VideoBlockViewController(environment: environment, blockID: blockID, courseID: courseID)
return controller
case .Unknown:
let environment = CourseUnknownBlockViewController.Environment(dataManager : self.environment.dataManager, styles : self.environment.styles)
let controller = CourseUnknownBlockViewController(blockID: blockID, courseID : courseID, environment : environment)
return controller
}
}
func controllerForBlock(block : CourseBlock, courseID : String) -> UIViewController {
return controllerForBlockWithID(block.blockID, type: block.displayType, courseID: courseID)
}
func showFullScreenMessageViewControllerFromViewController(controller : UIViewController, message : String, bottomButtonTitle: String?) {
let fullScreenViewController = FullScreenMessageViewController(message: message, bottomButtonTitle: bottomButtonTitle)
controller.presentViewController(fullScreenViewController, animated: true, completion: nil)
}
func showDiscussionResponsesFromViewController(controller: UIViewController, courseID : String, item : DiscussionPostItem) {
let environment = DiscussionResponsesViewController.Environment(networkManager: self.environment.networkManager, router: self, styles : self.environment.styles)
let storyboard = UIStoryboard(name: "DiscussionResponses", bundle: nil)
let responsesViewController = storyboard.instantiateInitialViewController() as! DiscussionResponsesViewController
responsesViewController.environment = environment
responsesViewController.courseID = courseID
responsesViewController.postItem = item
controller.navigationController?.pushViewController(responsesViewController, animated: true)
}
func showDiscussionCommentsFromViewController(controller: UIViewController, courseID : String, item : DiscussionResponseItem, closed : Bool) {
let environment = DiscussionCommentsViewController.Environment(
courseDataManager: self.environment.dataManager.courseDataManager,
router: self, networkManager : self.environment.networkManager)
let commentsVC = DiscussionCommentsViewController(environment: environment, courseID : courseID, responseItem: item, closed: closed)
controller.navigationController?.pushViewController(commentsVC, animated: true)
}
func showDiscussionNewCommentFromController(controller: UIViewController, courseID : String, item: DiscussionItem) {
let environment = DiscussionNewCommentViewController.Environment(
courseDataManager: self.environment.dataManager.courseDataManager,
networkManager: self.environment.networkManager,
router: self)
let newCommentViewController = DiscussionNewCommentViewController(environment: environment, courseID : courseID, item: item)
let navigationController = UINavigationController(rootViewController: newCommentViewController)
controller.presentViewController(navigationController, animated: true, completion: nil)
}
func showPostsFromController(controller : UIViewController, courseID : String, topic : DiscussionTopic) {
let environment = PostsViewControllerEnvironment(networkManager: self.environment.networkManager, router: self, styles: self.environment.styles)
let postsController = PostsViewController(environment: environment, courseID: courseID, topic: topic)
controller.navigationController?.pushViewController(postsController, animated: true)
}
func showAllPostsFromController(controller : UIViewController, courseID : String, followedOnly following : Bool) {
let environment = PostsViewControllerEnvironment(networkManager: self.environment.networkManager, router: self, styles: self.environment.styles)
let postsController = PostsViewController(environment: environment, courseID: courseID, following : following)
controller.navigationController?.pushViewController(postsController, animated: true)
}
func showPostsFromController(controller : UIViewController, courseID : String, queryString : String) {
let environment = PostsViewControllerEnvironment(networkManager: self.environment.networkManager, router: self, styles: self.environment.styles)
let postsController = PostsViewController(environment: environment, courseID: courseID, queryString : queryString)
controller.navigationController?.pushViewController(postsController, animated: true)
}
func showDiscussionTopicsFromController(controller: UIViewController, courseID : String) {
let environment = DiscussionTopicsViewController.Environment(
config: self.environment.config,
courseDataManager: self.environment.dataManager.courseDataManager,
networkManager: self.environment.networkManager,
router: self,
styles : self.environment.styles
)
let topicsController = DiscussionTopicsViewController(environment: environment, courseID: courseID)
controller.navigationController?.pushViewController(topicsController, animated: true)
}
func showDiscussionNewPostFromController(controller: UIViewController, courseID : String, initialTopic : DiscussionTopic?) {
let environment = DiscussionNewPostViewController.Environment(
courseDataManager : self.environment.dataManager.courseDataManager,
networkManager: self.environment.networkManager,
router: self)
let newPostController = DiscussionNewPostViewController(environment: environment, courseID: courseID, selectedTopic: initialTopic)
let navigationController = UINavigationController(rootViewController: newPostController)
controller.presentViewController(navigationController, animated: true, completion: nil)
}
func showHandoutsFromController(controller : UIViewController, courseID : String) {
let environment = CourseHandoutsViewController.Environment(
dataManager : self.environment.dataManager,
networkManager: self.environment.networkManager,
styles: self.environment.styles)
let handoutsViewController = CourseHandoutsViewController(environment: environment, courseID: courseID)
controller.navigationController?.pushViewController(handoutsViewController, animated: true)
}
}
| apache-2.0 | 0373ccc5c717dc659afbbe9c75036f10 | 53.90099 | 237 | 0.730748 | 6.0141 | false | false | false | false |
antonio081014/LeeCode-CodeBase | Swift/largest-divisible-subset.swift | 2 | 1169 | /**
* https://leetcode.com/problems/largest-divisible-subset/
*
*
*/
// Date: Sat Jun 13 10:10:37 PDT 2020
class Solution {
func largestDivisibleSubset(_ nums: [Int]) -> [Int] {
guard nums.count > 0 else { return [] }
var count = Array(repeating: 1, count: nums.count)
var pre = Array(repeating: -1, count: nums.count)
let nums = nums.sorted()
var maxLengthSolutionIndex = 0
for index in 0 ..< nums.count {
var subIndex = index - 1
while subIndex >= 0 {
if nums[index] % nums[subIndex] == 0, count[index] < count[subIndex] + 1 {
count[index] = count[subIndex] + 1
pre[index] = subIndex
}
subIndex -= 1
}
if count[index] > count[maxLengthSolutionIndex] {
maxLengthSolutionIndex = index
}
}
var solution: [Int] = []
while maxLengthSolutionIndex >= 0 {
solution.insert(nums[maxLengthSolutionIndex], at: 0)
maxLengthSolutionIndex = pre[maxLengthSolutionIndex]
}
return solution
}
}
| mit | 9346edb7b1f3061d905ad5af9b5c116d | 33.382353 | 90 | 0.530368 | 4.175 | false | false | false | false |
cotkjaer/SilverbackFramework | SilverbackFramework/UIBezierPath.swift | 1 | 15217 | //
// UIBezierPath.swift
// SilverbackFramework
//
// Created by Christian Otkjær on 17/08/15.
// Copyright (c) 2015 Christian Otkjær. All rights reserved.
//
import UIKit
public extension UIBezierPath
{
public convenience init(lineSegmentFrom a: CGPoint, to b: CGPoint)
{
self.init()
moveToPoint(a)
addLineToPoint(b)
}
}
/// A Swiftified representation of a `CGPathElement`
///
/// Simpler and safer than `CGPathElement` because it doesn’t use a C array for the associated points.
public enum PathElement
{
case MoveToPoint(CGPoint)
case AddLineToPoint(CGPoint)
case AddQuadCurveToPoint(CGPoint, CGPoint)
case AddCurveToPoint(CGPoint, CGPoint, CGPoint)
case CloseSubpath
init(element: CGPathElement)
{
switch element.type
{
case .MoveToPoint:
self = .MoveToPoint(element.points[0])
case .AddLineToPoint:
self = .AddLineToPoint(element.points[0])
case .AddQuadCurveToPoint:
self = .AddQuadCurveToPoint(element.points[0], element.points[1])
case .AddCurveToPoint:
self = .AddCurveToPoint(element.points[0], element.points[1], element.points[2])
case .CloseSubpath:
self = .CloseSubpath
}
}
}
extension PathElement : CustomDebugStringConvertible
{
public var debugDescription: String
{
switch self
{
case let .MoveToPoint(point):
return "\(point.x) \(point.y) moveto"
case let .AddLineToPoint(point):
return "\(point.x) \(point.y) lineto"
case let .AddQuadCurveToPoint(point1, point2):
return "\(point1.x) \(point1.y) \(point2.x) \(point2.y) quadcurveto"
case let .AddCurveToPoint(point1, point2, point3):
return "\(point1.x) \(point1.y) \(point2.x) \(point2.y) \(point3.x) \(point3.y) curveto"
case .CloseSubpath:
return "closepath"
}
}
}
extension PathElement : Equatable
{ }
public func ==(lhs: PathElement, rhs: PathElement) -> Bool
{
switch(lhs, rhs)
{
case let (.MoveToPoint(l), .MoveToPoint(r)):
return l == r
case let (.AddLineToPoint(l), .AddLineToPoint(r)):
return l == r
case let (.AddQuadCurveToPoint(l1, l2), .AddQuadCurveToPoint(r1, r2)):
return l1 == r1 && l2 == r2
case let (.AddCurveToPoint(l1, l2, l3), .AddCurveToPoint(r1, r2, r3)):
return l1 == r1 && l2 == r2 && l3 == r3
case (.CloseSubpath, .CloseSubpath):
return true
case (_, _):
return false
}
}
//internal enum UIBezierPathSegment
//{
// case Point(CGPoint)
// case Line(CGPoint, CGPoint)
// case QuadraticCurve(CGPoint, CGPoint, CGPoint)
// case CubicCurve(CGPoint, CGPoint, CGPoint, CGPoint)
//
// init(element: PathElement, beginPoint:CGPoint, inout subPathBeginPoint: CGPoint)
// {
// switch element
// {
// case let .MoveToPoint(toPoint):
// self = .Point(toPoint)
// subPathBeginPoint = toPoint
//
// case let .AddLineToPoint(endPoint):
// self = .Line(beginPoint, endPoint)
//
// case let .AddQuadCurveToPoint(ctrlPoint, endPoint):
// self = .QuadraticCurve(beginPoint, ctrlPoint, endPoint)
//
// case let .AddCurveToPoint(ctrlPoint1, ctrlPoint2, endPoint):
// self = .CubicCurve(beginPoint, ctrlPoint1, ctrlPoint2, endPoint)
//
// case .CloseSubpath:
// self = .Line(beginPoint, subPathBeginPoint)
// }
// }
//
// var endPoint : CGPoint
// {
// switch self
// {
// case let .Point(point): return point
//
// case let .Line(_, endPoint): return endPoint
//
// case let .QuadraticCurve(_, _, endPoint): return endPoint
//
// case let .CubicCurve(_, _, _, endPoint): return endPoint
// }
// }
//
// var beginPoint : CGPoint
// {
// switch self
// {
// case let .Point(p): return p
//
// case let .Line(p, _): return p
//
// case let .QuadraticCurve(p, _, _): return p
//
// case let .CubicCurve(p, _, _, _): return p
// }
// }
//
// internal func pointForT(t: CGFloat) -> CGPoint
// {
// switch self
// {
// case let .Point(point): return point
//
// case let .Line(beginPoint, endPoint): return lerp(beginPoint, endPoint, t)
//
// case let .QuadraticCurve(beginPoint, controlPoint, endPoint): return quadraticBezierPoint(beginPoint, b: controlPoint, c: endPoint, t: t)
//
// case let .CubicCurve(beginPoint, ctrlPoint1, ctrlPoint2, endPoint): return cubicBezierPoint(beginPoint, b: ctrlPoint1, c: ctrlPoint2, d: endPoint, t: t)
// }
// }
//
// var length : CGFloat
// {
// switch self
// {
// case .Point(_): return 0
//
// case let .Line(beginPoint, endPoint): return endPoint.distanceTo(beginPoint)
//
// default:
// repeat
// {
// var approximation = endPoint.distanceTo(beginPoint)
// var segments = 2
//
// let points = Array(0...segments).map({ (segmentIndex) -> CGPoint in
// let t = CGFloat(segmentIndex) / CGFloat(segments)
// return self.pointForT(t)
// })
//
// let (length, _) = points.reduce((0, points[0]), combine: { (lengthAndPoint, point) -> (CGFloat, CGPoint) in
// let l = lengthAndPoint.1.distanceTo(point)
// return (l, point)
// })
//
// if abs(approximation - length) < 1 { return length }
//
// approximation = length
// segments *= 2
//
// } while true
// }
// }
//}
extension UIBezierPath
{
var curves: [BezierCurve]
{
var curves = [BezierCurve]()
withUnsafeMutablePointer(&curves)
{ curvesPointer in
CGPathApply(CGPath, curvesPointer)
{ (userInfo, nextElementPointer) in
let curvesPointer = UnsafeMutablePointer<[BezierCurve]>(userInfo)
let curves = curvesPointer.memory
let beginPoint = curves.last?.endPoint ?? CGPointZero
var nextCurve : BezierCurve!
let element = nextElementPointer.memory
switch element.type
{
case .MoveToPoint:
nextCurve = BezierCurve(element.points[0])
case .AddLineToPoint:
nextCurve = BezierCurve(beginPoint, element.points[0])
case .AddQuadCurveToPoint:
nextCurve = BezierCurve(beginPoint, element.points[0], element.points[1])
case .AddCurveToPoint:
nextCurve = BezierCurve(beginPoint, element.points[0], element.points[1], element.points[2])
case .CloseSubpath:
let subpathBeginPoint = curves.filter({ $0.order == 1 }).last?.beginPoint ?? CGPointZero
nextCurve = BezierCurve(beginPoint, subpathBeginPoint)
}
curvesPointer.memory.append(nextCurve)
}
}
return curves
}
// var curves: [BezierCurve]
// {
// var curves = [BezierCurve]()
//
// withUnsafeMutablePointer(&curves)
// { curvesPointer in
// CGPathApply(CGPath, curvesPointer)
// { (userInfo, nextElementPointer) in
//
// let curvesPointer = UnsafeMutablePointer<[BezierCurve]>(userInfo)
// let curves = curvesPointer.memory
//
// let beginPoint = curves.last?.endPoint ?? CGPointZero
//
// var nextCurve : BezierCurve!
// let element = nextElementPointer.memory
// switch element.type
// {
// case .MoveToPoint:
// nextCurve = .Point(element.points[0])
//
// case .AddLineToPoint:
// nextCurve = .Liniar(beginPoint, element.points[0])
//
// case .AddQuadCurveToPoint:
// nextCurve = .Quadratic(beginPoint, element.points[0], element.points[1])
//
// case .AddCurveToPoint:
// nextCurve = .Cubic(beginPoint, element.points[0], element.points[1], element.points[2])
//
// case .CloseSubpath:
// var subpathBeginPoint = CGPointZero
//
// for curve in curves.reverse()
// {
// switch curve
// {
// case let .Point(p): subpathBeginPoint = p; break
// default: continue
// }
// }
//
// nextCurve = .Liniar(beginPoint, subpathBeginPoint)
// }
//
// curvesPointer.memory.append(nextCurve)
// }
// }
// return curves
// }
// var segments: [UIBezierPathSegment]
// {
// var s = Array<UIBezierPathSegment>()
//
// var subPathBeginPoint = CGPointZero
// var beginPoint = CGPointZero
//
// for element in elements
// {
// let segment = UIBezierPathSegment(element: element, beginPoint: beginPoint, subPathBeginPoint: &subPathBeginPoint)
//
// beginPoint = segment.endPoint
//
// s.append(segment)
// }
//
// return s
// }
//
var length : CGFloat { return curves.reduce(0, combine: { $0 + $1.length } ) }
var elements: [PathElement]
{
var pathElements = [PathElement]()
withUnsafeMutablePointer(&pathElements)
{ elementsPointer in
CGPathApply(CGPath, elementsPointer)
{ (userInfo, nextElementPointer) in
let nextElement = PathElement(element: nextElementPointer.memory)
let elementsPointer = UnsafeMutablePointer<[PathElement]>(userInfo)
elementsPointer.memory.append(nextElement)
}
}
return pathElements
}
}
public extension UIBezierPath
{
// Convert one element to BezierElement and save to array
func GetBezierElements(info: Any, element: CGPathElement)
{
// NSMutableArray *bezierElements = (__bridge NSMutableArray *)info;
// if (element)
// [bezierElements addObject:[BezierElement elementWithPathElement:*element]];
}
// Retrieve array of component elements
func getElements()
{
// let
// NSMutableArray *elements = [NSMutableArray array];
// CGPathApply(self.CGPath, (__bridge void *)elements, GetBezierElements);
// return elements;
//
}
public func drawText(text: String, withFont font: UIFont)
{
// var originalString: String = "Some text is just here..."
// let myString: NSString = originalString as NSString
// let size: CGSize = myString.sizeWithAttributes([NSFontAttributeName: UIFont.systemFontOfSize(14.0)])
//
// if text.isEmpty
// { return }
//
// var context = UIGraphicsGetCurrentContext()
//
// precondition(context != nil, "No context to draw into")
//
//
// if self.elements.count < 2
// {
// return
// }
//
// var glyphDistance: Float = 0.0
// var lineLength: Float = self.pathLength
//
// for var loc = 0; loc < string.length; loc++
// {
// var range: NSRange = NSMakeRange(loc, 1)
// var item: NSAttributedString = string.attributedSubstringFromRange(range)
// var bounding: CGRect = item.boundingRectWithSize(CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX), options: 0, context: nil)
// glyphDistance += bounding.size.width / 2
// var slope: CGPoint
// var percentConsumed: CGFloat = glyphDistance / lineLength
// var targetPoint: CGPoint = self.pointAtPercent(percentConsumed, withSlope: &slope)
// glyphDistance += bounding.size.width / 2
// if percentConsumed >= 1.0
// {
//
// }
// var angle: Float = atan(slope.y / slope.x)
// if slope.x < 0
// {
// angle += M_PI
// }
// PushDraw({ CGContextTranslateCTM(context, targetPoint.x, targetPoint.y)
// CGContextRotateCTM(context, angle)
// CGContextTranslateCTM(context, -bounding.size.width / 2, -item.size.height / 2)
// item.drawAtPoint(CGPointZero)
//
// })
// }
}
} | mit | 5d486068d80092916e00ad7ece5fbb4d | 36.565432 | 162 | 0.46388 | 4.987869 | false | false | false | false |
kingloveyy/SwiftBlog | SwiftBlog/SwiftBlog/Classes/UI/Discover/DiscoverViewController.swift | 1 | 3311 | //
// DiscoverViewController.swift
// SwiftBlog
//
// Created by King on 15/3/19.
// Copyright (c) 2015年 king. All rights reserved.
//
import UIKit
class DiscoverViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return 0
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as! UITableViewCell
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
}
| mit | b6453a67d516d512aca922994fe00045 | 33.113402 | 157 | 0.68359 | 5.570707 | false | false | false | false |
ifLab/iCampus-iOS | iCampus/Controller/Gate/ICGateViewController.swift | 1 | 6234 | //
// ICGateViewController.swift
// iCampus
//
// Created by Bill Hu on 16/12/14.
// Copyright © 2016年 BISTU. All rights reserved.
//
import UIKit
//import PJYellowPageViewController
class ICGateViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
// MARK: - Properties
var identifier = "ICGateViewCell"
let itemTitles = [""];
// "新闻",
// "黄页",
// "校车",
// "地图",
// "兼职",
// "成绩",
// "课程",
// "教室",
// "失物招领",
// "关于",
// ]
let limitedTitles = ["黄页",
"失物招领",
]//需要登录并认证的栏目
let itemImageNames = ["ICGateNewsIcon",
"ICGateYellowPageIcon",
"ICGateBusIcon",
"ICGateMapIcon",
"二手货",
// "About",
]
let itemIdentifiers = [ICNewsMainViewController.self,
PJYellowPageViewController.self,
PJBusViewController.self,
PJMapViewController.self,
PJLostViewController.self,
// PJAboutViewController.self,
] as [Any]
// MARK: - Object Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
title = "iBistu"
let rightItemImg = UIImage(named: "user")?.withRenderingMode(UIImageRenderingMode.alwaysOriginal);
let rightItem = UIBarButtonItem.init(image: rightItemImg, style: UIBarButtonItemStyle.done, target: self, action: #selector(ICGateViewController.pushUserVC))
self.navigationItem.rightBarButtonItem = rightItem;
collectionView?.register(
UINib(nibName: identifier, bundle: Bundle.main), forCellWithReuseIdentifier: identifier)
collectionView?.backgroundColor = .white
}
func pushUserVC() {
if PJUser.current() == nil {
let controller = Bundle.main.loadNibNamed("ICLoginViewController", owner: nil, options: nil)?.first as! ICLoginViewController
present(controller, animated: true, completion: nil)
} else {
let mainStoryboard = UIStoryboard(name:"PJUserSB", bundle:nil)
var vc = PJUserViewController.init();
vc = mainStoryboard.instantiateViewController(withIdentifier: "PJUserViewController") as! PJUserViewController
navigationController?.pushViewController(vc, animated: true)
}
}
func isLimited(title: String) -> Bool {
for li in limitedTitles {
if li == title {
return true
}
}
return false
}
// MARK: - UICollectionViewDataSource
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as! ICGateViewCell
cell.update(image: itemImageNames[indexPath.item], label: itemTitles[indexPath.item])
return cell
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return itemTitles.count
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if isLimited(title: itemTitles[indexPath.item]) {//需要登录并且认证
if ICNetworkManager.default().token != nil && ICNetworkManager.default().token != "" {//logined
if !CASBistu.checkCASCertified() && CASBistu.showCASController() {//CAS not certified
let controller = Bundle.main.loadNibNamed("ICCASViewController", owner: nil, options: nil)?.first as! ICCASViewController
present(controller, animated: true, completion: nil)
return
}
//logined and CAS certified, present after exit if.
} else {//didn't login, present LoginVC
let controller = Bundle.main.loadNibNamed("ICLoginViewController", owner: nil, options: nil)?.first as! ICLoginViewController
present(controller, animated: true, completion: nil)
return
}
}
let controller = (itemIdentifiers[indexPath.item] as! UIViewController.Type).init()
navigationController?.pushViewController(controller, animated: true)
}
// MARK: - UICollectionViewDelegateFlowLayout
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 20.0, left: 20.0, bottom: 20.0, right: 20.0)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let numberOfItemsInLine: CGFloat = 3
let inset = self.collectionView(collectionView, layout: collectionViewLayout, insetForSectionAt: indexPath.section)
let itemWidth = (collectionView.frame.width) / numberOfItemsInLine - inset.left - inset.right
let itemHeight = itemWidth + 20
return CGSize(width: itemWidth, height: itemHeight)
}
internal func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 30.0
}
@nonobjc internal func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0.0
}
}
| gpl-2.0 | bcf028d0886f663ea87c524f04500c56 | 42.807143 | 193 | 0.610305 | 5.403524 | false | false | false | false |
material-motion/material-motion-swift | src/transitions/TransitionController.swift | 2 | 10685 | /*
Copyright 2016-present The Material Motion Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
import UIKit
extension UIViewController {
private struct AssociatedKeys {
static var transitionController = "MDMTransitionController"
}
/**
A transition controller may be used to implement custom Material Motion transitions.
The transition controller is lazily created upon access. If the view controller's
transitioningDelegate is nil when the controller is created, then the controller will also be set
to the transitioningDelegate property.
*/
public var transitionController: TransitionController {
get {
if let controller = objc_getAssociatedObject(self, &AssociatedKeys.transitionController) as? TransitionController {
return controller
}
let controller = TransitionController(viewController: self)
objc_setAssociatedObject(self, &AssociatedKeys.transitionController, controller, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
if transitioningDelegate == nil {
transitioningDelegate = controller.transitioningDelegate
}
return controller
}
}
}
/**
A TransitionController is the bridging object between UIKit's view controller transitioning
APIs and Material Motion transitions.
This class is not meant to be instantiated directly.
*/
public final class TransitionController {
/**
An instance of the directorClass will be created to describe the motion for this transition
controller's transitions.
If no directorClass is provided then a default UIKit transition will be used.
Must be a subclass of MDMTransition.
*/
public var transition: Transition? {
set {
_transitioningDelegate.transition = newValue
if let presentationTransition = newValue as? TransitionWithPresentation,
let modalPresentationStyle = presentationTransition.defaultModalPresentationStyle() {
_transitioningDelegate.associatedViewController?.modalPresentationStyle = modalPresentationStyle
}
}
get { return _transitioningDelegate.transition }
}
/**
The presentation controller to be used during this transition.
Will be read from and cached when the view controller is first presented. Changes made to this
property after presentation will be ignored.
*/
public var presentationController: UIPresentationController? {
set { _transitioningDelegate.presentationController = newValue }
get { return _transitioningDelegate.presentationController }
}
/**
Start a dismiss transition when the given gesture recognizer enters its began or recognized
state.
The provided gesture recognizer will be made available to the transition instance via the
TransitionContext's `gestureRecognizers` property.
*/
public func dismissWhenGestureRecognizerBegins(_ gestureRecognizer: UIGestureRecognizer) {
_transitioningDelegate.dismisser.dismissWhenGestureRecognizerBegins(gestureRecognizer)
}
/**
Will not allow the provided gesture recognizer to recognize simultaneously with other gesture
recognizers.
This method assumes that the provided gesture recognizer's delegate has been assigned to the
transition controller's gesture delegate.
*/
public func disableSimultaneousRecognition(of gestureRecognizer: UIGestureRecognizer) {
_transitioningDelegate.dismisser.disableSimultaneousRecognition(of: gestureRecognizer)
}
/**
Returns a gesture recognizer delegate that will allow the gesture recognizer to begin only if the
provided scroll view is scrolled to the top of its content.
The returned delegate implements gestureRecognizerShouldBegin.
*/
public func topEdgeDismisserDelegate(for scrollView: UIScrollView) -> UIGestureRecognizerDelegate {
return _transitioningDelegate.dismisser.topEdgeDismisserDelegate(for: scrollView)
}
/**
The set of gesture recognizers that will be provided to the transition via the TransitionContext
instance.
*/
public var gestureRecognizers: Set<UIGestureRecognizer> {
set { _transitioningDelegate.gestureDelegate.gestureRecognizers = newValue }
get { return _transitioningDelegate.gestureDelegate.gestureRecognizers }
}
/**
The transitioning delegate managed by this controller.
This object can be assigned to the view controller's transitioningDelegate. This is done
automatically when a view controller's `transitionController` is first accessed.
*/
public var transitioningDelegate: UIViewControllerTransitioningDelegate {
return _transitioningDelegate
}
/**
The gesture recognizer delegate managed by this controller.
*/
public var gestureDelegate: UIGestureRecognizerDelegate {
return _transitioningDelegate.gestureDelegate
}
init(viewController: UIViewController) {
_transitioningDelegate = TransitioningDelegate(viewController: viewController)
}
fileprivate let _transitioningDelegate: TransitioningDelegate
}
private final class TransitioningDelegate: NSObject, UIViewControllerTransitioningDelegate {
init(viewController: UIViewController) {
self.associatedViewController = viewController
self.dismisser = ViewControllerDismisser(gestureDelegate: self.gestureDelegate)
super.init()
self.dismisser.delegate = self
}
var ctx: TransitionContext?
var transition: Transition?
let dismisser: ViewControllerDismisser
let gestureDelegate = GestureDelegate()
var presentationController: UIPresentationController?
weak var associatedViewController: UIViewController?
func prepareForTransition(withSource: UIViewController,
back: UIViewController,
fore: UIViewController,
direction: TransitionDirection) {
// It's possible for a backward transition to be initiated while a forward transition is active.
// We prefer the most recent transition in this case by blowing away the existing transition.
if direction == .backward {
ctx = nil
}
assert(ctx == nil, "A transition is already active.")
if let transition = transition {
if direction == .forward, let selfDismissingDirector = transition as? SelfDismissingTransition {
selfDismissingDirector.willPresent(fore: fore, dismisser: dismisser)
}
ctx = TransitionContext(transition: transition,
direction: direction,
back: back,
fore: fore,
gestureRecognizers: gestureDelegate.gestureRecognizers,
presentationController: presentationController)
ctx?.delegate = self
}
}
public func animationController(forPresented presented: UIViewController,
presenting: UIViewController,
source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
prepareForTransition(withSource: source, back: presenting, fore: presented, direction: .forward)
return ctx
}
public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
// The source is sadly lost by the time we get to dismissing the view controller, so we do our
// best to infer what the source might have been.
//
// If the presenting view controller is a nav controller it's pretty likely that the view
// controller was presented from its last view controller. Making this assumption is generally
// harmless and only affects the view retriever search (by starting one view controller lower than
// we otherwise would by using the navigation controller as the source).
let source: UIViewController
if let navController = dismissed.presentingViewController as? UINavigationController {
source = navController.viewControllers.last!
} else {
source = dismissed.presentingViewController!
}
prepareForTransition(withSource: source,
back: dismissed.presentingViewController!,
fore: dismissed,
direction: .backward)
return ctx
}
public func interactionControllerForPresentation(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
if animator === ctx && isInteractive() {
return ctx
}
return nil
}
public func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
if animator === ctx && isInteractive() {
return ctx
}
return nil
}
func isInteractive() -> Bool {
return gestureDelegate.gestureRecognizers.filter { $0.state == .began || $0.state == .changed }.count > 0
}
func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
guard let transitionWithPresentation = transition as? TransitionWithPresentation else {
return nil
}
if let presentationController = presentationController {
return presentationController
}
presentationController = transitionWithPresentation.presentationController(forPresented: presented,
presenting: presenting,
source: source)
return presentationController
}
}
extension TransitioningDelegate: ViewControllerDismisserDelegate {
func dismiss() {
guard let associatedViewController = associatedViewController else {
return
}
if associatedViewController.presentingViewController == nil {
return
}
if associatedViewController.isBeingDismissed || associatedViewController.isBeingPresented {
return
}
associatedViewController.dismiss(animated: true)
}
}
extension TransitioningDelegate: TransitionDelegate {
func transitionDidComplete(withContext ctx: TransitionContext) {
if ctx === self.ctx {
self.ctx = nil
}
}
}
| apache-2.0 | ad2ddc69d65a6aa2d87f364a92414504 | 36.623239 | 159 | 0.72934 | 6.026509 | false | false | false | false |
yeziahehe/Gank | Gank/Extensions/String+Gank.swift | 1 | 1891 | //
// String+Gank.swift
// Gank
//
// Created by 叶帆 on 2017/6/26.
// Copyright © 2017年 Suzhou Coryphaei Information&Technology Co., Ltd. All rights reserved.
//
import UIKit
extension String {
public func toDate() -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
if let date = dateFormatter.date(from: self) {
return date
} else {
return nil
}
}
public func toDateOfSecond() -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
if let date = dateFormatter.date(from: self) {
return date
} else {
return nil
}
}
public func toGankUrl() -> String {
let stringArray = self.components(separatedBy: "/")
return String(format:"此网页由 %@ 提供", stringArray[2])
}
public var toTimeFormat: String {
var string = self.replacingOccurrences(of: "T", with: " ")
string = String(string[startIndex...string.index(startIndex, offsetBy: 18)])
return string
}
public var toChineseMonth: String {
switch self {
case "01":
return "一月"
case "02":
return "二月"
case "03":
return "三月"
case "04":
return "四月"
case "05":
return "五月"
case "06":
return "六月"
case "07":
return "七月"
case "08":
return "八月"
case "09":
return "九月"
case "10":
return "十月"
case "11":
return "十一月"
case "12":
return "十二月"
default:
return ""
}
}
}
| gpl-3.0 | e4328fe25e8db04f869398058d90bd8c | 22.037975 | 92 | 0.486264 | 4.282353 | false | false | false | false |
ilk33r/IORunner | Extensions/SSHHandler/SSHHandler.swift | 1 | 5261 | //
// SSHHandler.swift
// IORunner/Extensions/SSHHandler
//
// Created by ilker özcan on 10/08/16.
//
//
import Foundation
import IOIni
import IORunnerExtension
public class SSHHandler: AppHandlers {
#if swift(>=3)
private var processStatus: [Int] = [Int]()
private var checkingFrequency: Int = 60
private var taskTimeout: Int = 60
// 0 waiting, 1 stopping, 2 starting
private var taskStatus = 0
#if os(Linux)
private var lastTask: Task?
#else
private var lastTask: Process?
#endif
private var lastCheckDate: Date?
private var lastTaskStartDate = 0
private var asyncTaskPid: pid_t?
private var asyncTaskStartTime: UInt = 0
public required init(logger: Logger, configFilePath: String, moduleConfig: Section?) {
super.init(logger: logger, configFilePath: configFilePath, moduleConfig: moduleConfig)
if let currentProcessFrequency = moduleConfig?["ProcessFrequency"] {
if let frequencyInt = Int(currentProcessFrequency) {
self.checkingFrequency = frequencyInt
}
}
if let currentProcessTimeout = moduleConfig?["ProcessTimeout"] {
if let timeoutInt = Int(currentProcessTimeout) {
self.taskTimeout = timeoutInt
}
}
}
public override func getClassName() -> String {
return String(describing: self)
}
public override func forStart() {
self.logger.writeLog(level: Logger.LogLevels.WARNINGS, message: "SSH extension registered!")
self.lastCheckDate = Date()
}
public override func inLoop() {
if(lastCheckDate != nil) {
let currentDate = Int(Date().timeIntervalSince1970)
let lastCheckDif = currentDate - Int(lastCheckDate!.timeIntervalSince1970)
if(lastCheckDif >= self.checkingFrequency) {
if(!self.checkSSHProcess()) {
self.restartSSH()
}
if(self.asyncTaskPid != nil) {
self.waitAsyncTask()
}
}
}else{
self.lastCheckDate = Date()
}
}
public override func forAsyncTask() {
if(self.taskStatus == 0) {
self.taskStatus = 1
self.lastTaskStartDate = Int(Date().timeIntervalSince1970)
if let processStopCommand = moduleConfig?["ProcessStopCommand"] {
self.lastTask = self.executeTask(command: processStopCommand)
}
}else if(self.taskStatus == 1) {
guard self.lastTask != nil else {
self.taskStatus = 0
return
}
let taskIsRunning: Bool
#if os(Linux)
taskIsRunning = self.lastTask!.running
#else
taskIsRunning = self.lastTask!.isRunning
#endif
if(!taskIsRunning) {
self.taskStatus = 2
self.lastTaskStartDate = Int(Date().timeIntervalSince1970)
if let processStartCommand = moduleConfig?["ProcessStartCommand"] {
self.lastTask = self.executeTask(command: processStartCommand)
}
}
}else if(self.taskStatus == 2) {
guard self.lastTask != nil else {
self.taskStatus = 0
return
}
let lastTaskIsRunning: Bool
#if os(Linux)
lastTaskIsRunning = self.lastTask!.running
#else
lastTaskIsRunning = self.lastTask!.isRunning
#endif
if(!lastTaskIsRunning) {
self.taskStatus = 0
}
}
if(self.taskStatus != 0) {
let curDate = Int(Date().timeIntervalSince1970)
let startDif = curDate - self.lastTaskStartDate
if(startDif > taskTimeout) {
self.taskStatus = 0
}else{
usleep(300000)
self.forAsyncTask()
}
}
}
private func checkSSHProcess() -> Bool {
if let currentProcessName = moduleConfig?["ProcessName"] {
self.processStatus = self.checkProcess(processName: currentProcessName)
self.lastCheckDate = Date()
if(self.processStatus.count > 0) {
return true
}else{
self.logger.writeLog(level: Logger.LogLevels.ERROR, message: "Warning Process SSH does not working!")
return false
}
}
return true
}
private func restartSSH() {
self.logger.writeLog(level: Logger.LogLevels.WARNINGS, message: "Restarting SSH")
if(self.asyncTaskPid == nil) {
self.asyncTaskStartTime = UInt(Date().timeIntervalSince1970)
self.asyncTaskPid = self.startAsyncTask(command: "self", extraEnv: nil, extensionName: self.getClassName())
}else{
self.logger.writeLog(level: Logger.LogLevels.WARNINGS, message: "SSH Async task already started")
if(kill(self.asyncTaskPid!, 0) != 0) {
self.logger.writeLog(level: Logger.LogLevels.WARNINGS, message: "SSH Async task already started but does not work!")
self.asyncTaskPid = nil
self.restartSSH()
}
}
}
private func waitAsyncTask() {
let curDate = UInt(Date().timeIntervalSince1970)
let startDif = curDate - self.asyncTaskStartTime
if(startDif > UInt(taskTimeout + 30)) {
if(kill(self.asyncTaskPid!, 0) == 0) {
var pidStatus: Int32 = 0
waitpid(self.asyncTaskPid!, &pidStatus, 0)
self.asyncTaskPid = nil
}else{
self.asyncTaskPid = nil
}
}
}
#elseif swift(>=2.2) && os(OSX)
public required init(logger: Logger, configFilePath: String, moduleConfig: Section?) {
super.init(logger: logger, configFilePath: configFilePath, moduleConfig: moduleConfig)
self.logger.writeLog(Logger.LogLevels.ERROR, message: "SSH extension only works swift >= 3 build.")
}
#endif
}
| mit | 864a5221b14264f0aa80db2fa8a755ed | 21.969432 | 120 | 0.673764 | 3.556457 | false | true | false | false |
panadaW/MyNews | MyWb完善首页数据/MyWb/Class/Model/Status.swift | 1 | 5007 | //
// Status.swift
// MyWb
//
// Created by 王明申 on 15/10/13.
// Copyright © 2015年 晨曦的Mac. All rights reserved.
//
import SDWebImage
import UIKit
//微博数据模型
class Status: NSObject {
// 微博创建时间
var created_at: String?
// 微博ID
var id: Int = 0
// 微博信息内容
var text: String?
// 微博来源
var source: String? {
didSet {
source = source?.hrefLink().text
}
}
// 配图数组
var pic_urls: [[String: AnyObject]]? {
didSet {
if pic_urls?.count == 0 {
return
}
// 实例化数组
storepictureURLs = [NSURL]()
storedLargePictureURLs = [NSURL]()
// 遍历配图数组
for dict in pic_urls! {
if let urlstring = dict["thumbnail_pic"] as? String {
storepictureURLs?.append(NSURL(string: urlstring)!)
let largeurlstring = urlstring.stringByReplacingOccurrencesOfString("thumbnail", withString: "large")
storedLargePictureURLs?.append(NSURL(string: largeurlstring)!)
}
}
}
}
// 存储转发微博图片数组,或原创微博url数组
var storepictureURLs: [NSURL]?
// 微博配图URL数组
var pictureURLs: [NSURL]? {
return retweeted_status == nil ? storepictureURLs : retweeted_status?.storepictureURLs
}
// 定义大图URL数组
var storedLargePictureURLs: [NSURL]?
// 返回大图URL数组
var largePictureURLs: [NSURL]? {
return retweeted_status == nil ? storedLargePictureURLs : retweeted_status?.storedLargePictureURLs
}
// 用户模型
var user: UserModel?
// 转发微博
var retweeted_status: Status?
// 行高属性
var rowHight: CGFloat?
// 把微博数据转换为数组
class func loadstatus(since_id: Int,max_id: Int,finish:(dataList: [Status]?,error: NSError?)->() ){
NetWorkShare.shareTools.loadStatus(since_id,max_id: max_id) { (resault, error) -> () in
if error != nil{
return
}
if let array = resault?["statuses"] as? [[String: AnyObject]]{
// 实例化数组
var list = [Status]()
// 遍历数组
for dict in array {
// 字典转模型
list.append(Status(dict: dict))
}
// 缓存图片
self.cacheImage(list, finish: finish)
}else{
finish(dataList: nil, error: nil)
}
}
}
// 缓存网络图片,等缓存完毕,才能刷新数据
private class func cacheImage(list: [Status],finish:(dataList: [Status]?,error: NSError?)->()) {
// 创建调度组
let group = dispatch_group_create()
// 缓存图片大小
var dadtaLengh = 0
// 遍历数组
for status in list {
guard let url = status.pictureURLs else {
continue
}
// 遍历url数组,缓存图片
for imgurl in url {
dispatch_group_enter(group)
SDWebImageManager.sharedManager().downloadImageWithURL(imgurl, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (image, _, _, _, _) -> Void in
// 将图片转换为二进制
if image != nil {
let data = UIImagePNGRepresentation(image)!
dadtaLengh += data.length
}
// 出组
dispatch_group_leave(group)
})
}
}
// 监听缓存操作通知
dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
print("缓存图片大小 \(dadtaLengh / 1024) K")
// 回调
finish(dataList: list, error: nil)
}
}
//字典转模型
init(dict: [String: AnyObject]) {
super.init()
setValuesForKeysWithDictionary(dict)
}
override func setValue(value: AnyObject?, forKey key: String) {
if key == "user" {
// 判断 value 是否是一个字典,应为微博用户信息是用字典封装的
if let dict = value as? [String: AnyObject] {
user = UserModel(dict: dict)
}
return
}
if key == "retweeted_status" {
if let dict = value as? [String: AnyObject] {
retweeted_status = Status(dict: dict)
}
return
}
super.setValue(value, forKey: key)
}
override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
override var description: String {
let keys = ["created_at","id","text","source","pic_urls"]
return "\(dictionaryWithValuesForKeys(keys))"
}
} | mit | 6e594a61220742986f22f9f73e32e0c1 | 28.823529 | 178 | 0.512495 | 4.328273 | false | false | false | false |
KieranHarper/KJHUIKit | Sources/ImageOrLabelButton.swift | 1 | 5791 | //
// ImageOrLabelButton.swift
// KJHUIKit
//
// Created by Kieran Harper on 15/7/17.
// Copyright © 2017 Kieran Harper. All rights reserved.
//
import UIKit
/** Button that can either be an image or a label.
You can swap the mode on the fly but no animation is provided by default. Subclassing and overriding imageMode property should allow you to customize to your needs.
*/
@objc open class ImageOrLabelButton: Button {
// MARK: - Properties
/// Whether or not the button is operating in image mode, where the label will be hidden (via alpha = 0).
@objc public var imageMode = false {
didSet {
if imageMode {
label.alpha = 0.0
imageView.alpha = 1.0
} else {
label.alpha = 1.0
imageView.alpha = 0.0
}
self.invalidateIntrinsicContentSize()
self.setNeedsLayout()
}
}
/**
The image view that is centered inside the button. Alignment is centered by default.
*/
@objc public let imageView = CrossfadingImageView()
/**
The label that is centered inside the button. Alignment is centered by default.
*/
@objc public let label = CrossfadingLabel()
/**
The horizontal offset of the image from a X-centered position.
Positive numbers move it to the right, negative to the left.
*/
@objc public var imageOffsetFromCenterX: CGFloat = 0.0 {
didSet {
self.invalidateIntrinsicContentSize()
self.setNeedsLayout()
}
}
/**
The vertical offset of the image from a Y-centered position.
Positive numbers move it down, negative moves up.
*/
@objc public var imageOffsetFromCenterY: CGFloat = 0.0 {
didSet {
self.invalidateIntrinsicContentSize()
self.setNeedsLayout()
}
}
/**
The horizontal offset of the label from a X-centered position.
Positive numbers move it to the right, negative to the left.
*/
@objc public var labelOffsetFromCenterX: CGFloat = 0.0 {
didSet {
self.invalidateIntrinsicContentSize()
self.setNeedsLayout()
}
}
/**
The vertical offset of the label from a Y-centered position.
Positive numbers move it down, negative moves up.
*/
@objc public var labelOffsetFromCenterY: CGFloat = 0.0 {
didSet {
self.invalidateIntrinsicContentSize()
self.setNeedsLayout()
}
}
/**
A size to constrain the image view to, independent of the button size.
This is useful if your image is bigger than you expect, but you don't want it to be flush with the size of the button (or the button has constraints which shouldn't relate to the image).
*/
public var imageViewConstrainedSize: CGSize? = nil {
didSet {
self.invalidateIntrinsicContentSize()
self.setNeedsLayout()
}
}
// MARK: - Private variables
private var imageViewConstrainedWidth: CGFloat? {
if let width = imageViewConstrainedSize?.width, width != UIView.noIntrinsicMetric {
return width
} else {
return nil
}
}
private var imageViewConstrainedHeight: CGFloat? {
if let height = imageViewConstrainedSize?.height, height != UIView.noIntrinsicMetric {
return height
} else {
return nil
}
}
// MARK: - Lifecycle
@objc public override init(frame: CGRect) {
super.init(frame: frame)
self.setupImageOrLabelButton()
}
@objc public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setupImageOrLabelButton()
}
@objc public convenience init() {
self.init(frame: CGRect.zero)
}
private func setupImageOrLabelButton() {
imageMode = false
// Setup the image view
imageView.contentMode = .center
imageView.clipsToBounds = true
self.addSubview(imageView)
// Setup the label
label.textAlignment = .center
self.addSubview(label)
helperSetFrames()
}
@objc open override func layoutSubviews() {
super.layoutSubviews()
helperSetFrames()
}
private func helperSetFrames() {
label.frame = self.bounds.offsetBy(dx: labelOffsetFromCenterX, dy: labelOffsetFromCenterY)
imageView.frame = self.bounds.offsetBy(dx: imageOffsetFromCenterX, dy: imageOffsetFromCenterY).resizedTo(width: imageViewConstrainedWidth, height: imageViewConstrainedHeight)
}
@objc open override var intrinsicContentSize: CGSize {
if imageMode {
let intrinsicWidth = imageViewConstrainedWidth ?? imageView.intrinsicContentSize.width
let intrinsicHeight = imageViewConstrainedHeight ?? imageView.intrinsicContentSize.height
let widthAccountingForOffset = intrinsicWidth + 2.0 * abs(imageOffsetFromCenterX)
let heightAccountingForOffset = intrinsicHeight + 2.0 * abs(imageOffsetFromCenterY)
return CGSize(width: widthAccountingForOffset, height: heightAccountingForOffset)
} else {
let intrinsicSize = label.intrinsicContentSize
let widthAccountingForOffset = intrinsicSize.width + 2.0 * abs(labelOffsetFromCenterX)
let heightAccountingForOffset = intrinsicSize.height + 2.0 * abs(labelOffsetFromCenterY)
return CGSize(width: widthAccountingForOffset, height: heightAccountingForOffset)
}
}
}
| mit | 687f45ab9ca7520971af599994bca4ba | 30.297297 | 191 | 0.621762 | 5.061189 | false | false | false | false |
andrea-prearo/SwiftExamples | RegionMonitor/RegionMonitor/GenericStore.swift | 1 | 2078 | //
// GenericStore.swift
// RegionMonitor
//
// Created by Andrea Prearo on 5/25/15.
// Copyright (c) 2015 Andrea Prearo. All rights reserved.
//
import Foundation
class GenericStore<T: NSObject> {
fileprivate(set) internal var storedItems = [T]()
let storeItemsKey: String
let storeItemsDidChangeNotification: String
// MARK: Singleton
init(storeItemsKey: String, storeItemsDidChangeNotification: String) {
self.storeItemsKey = storeItemsKey
self.storeItemsDidChangeNotification = storeItemsDidChangeNotification
loadStoredItems()
}
// MARK: Private Methods
fileprivate func loadStoredItems() {
storedItems = []
if let items = UserDefaults.standard.array(forKey: storeItemsKey) {
for item in items {
if let storedItem = NSKeyedUnarchiver.unarchiveObject(with: item as! Data) as? T {
storedItems.append(storedItem)
}
}
}
NotificationCenter.default.post(name: Notification.Name(rawValue: storeItemsDidChangeNotification), object: nil)
}
private func saveStoredItems() {
let items = NSMutableArray()
for storedItem in storedItems {
let item = NSKeyedArchiver.archivedData(withRootObject: storedItem)
items.add(item)
}
NotificationCenter.default.post(name: Notification.Name(rawValue: storeItemsDidChangeNotification), object: nil)
UserDefaults.standard.set(items, forKey: storeItemsKey)
UserDefaults.standard.synchronize()
}
// MARK: Public Methods
func addStoredItem(_ item: T) {
storedItems.append(item)
saveStoredItems()
}
func removeStoredItem(_ item: T) {
storedItems.remove(at: indexForItem(item))
saveStoredItems()
}
func indexForItem(_ item: T) -> Int {
var index = -1
for storedItem in storedItems {
if storedItem == item {
break
}
index += 1
}
return index
}
}
| mit | f12281f6d0d3943e0d368f8e59ea14a4 | 27.465753 | 120 | 0.62897 | 4.659193 | false | false | false | false |
inderdhir/SwiftWeather | DatWeatherDoe/Model/WeatherAPIResponse.swift | 1 | 1283 | //
// WeatherResponse.swift
// DatWeatherDoe
//
// Created by Inder Dhir on 2/3/18.
// Copyright © 2018 Inder Dhir. All rights reserved.
//
struct WeatherAPIResponse: Decodable {
let temperature: Double
let humidity: Int
let location: String
let weatherId: Int
private enum RootKeys: String, CodingKey {
case main, weather, name
}
private enum APIKeys: String, CodingKey {
case temperature = "temp"
case humidity
}
private enum WeatherKeys: String, CodingKey {
case id
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: RootKeys.self)
temperature = try container.nestedContainer(keyedBy: APIKeys.self, forKey: .main)
.decode(Double.self, forKey: .temperature)
humidity = try container.nestedContainer(keyedBy: APIKeys.self, forKey: .main)
.decode(Int.self, forKey: .humidity)
location = try container.decode(String.self, forKey: .name)
var weatherContainer = try container.nestedUnkeyedContainer(forKey: .weather)
let weatherChildContainer = try weatherContainer.nestedContainer(keyedBy: WeatherKeys.self)
weatherId = try weatherChildContainer.decode(Int.self, forKey: .id)
}
}
| apache-2.0 | 77adfe8b1c4d51435fab362debe9491d | 31.871795 | 99 | 0.677067 | 4.405498 | false | false | false | false |
ifLab/WeCenterMobile-iOS | WeCenterMobile/Controller/LoginViewController.swift | 3 | 12040 | //
// LoginViewController.swift
// WeCenterMobile
//
// Created by Darren Liu on 14/7/14.
// Copyright (c) 2014年 ifLab. All rights reserved.
//
import AFViewShaker
import UIKit
enum LoginViewControllerState: Int {
case Login
case Registration
}
class LoginViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var emailField: UITextField!
@IBOutlet weak var userNameField: UITextField!
@IBOutlet weak var passwordField: UITextField!
@IBOutlet weak var emailImageView: UIImageView!
@IBOutlet weak var userNameImageView: UIImageView!
@IBOutlet weak var passwordImageView: UIImageView!
@IBOutlet weak var emailImageViewContainerView: UIVisualEffectView!
@IBOutlet weak var userNameImageViewContainerView: UIVisualEffectView!
@IBOutlet weak var passwordImageViewContainerView: UIVisualEffectView!
@IBOutlet weak var emailFieldUnderline: UIVisualEffectView!
@IBOutlet weak var userNameFieldUnderline: UIVisualEffectView!
@IBOutlet weak var passwordFieldUnderline: UIVisualEffectView!
@IBOutlet weak var loginButton: UIButton!
@IBOutlet weak var loginButtonLabel: UILabel!
@IBOutlet weak var loginActivityIndicatorView: UIActivityIndicatorView!
@IBOutlet weak var titleLabelContainerView: UIVisualEffectView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var errorMessageLabel: UILabel!
@IBOutlet weak var changeStateButton: UIButton!
var state: LoginViewControllerState = .Login {
didSet {
UIView.animateWithDuration(0.5,
delay: 0,
usingSpringWithDamping: 1,
initialSpringVelocity: 0.7,
options: .BeginFromCurrentState,
animations: {
[weak self] in
if let self_ = self {
self_.errorMessageLabel.text = ""
if self_.state == .Login {
self_.emailImageView.alpha = 0
self_.emailFieldUnderline.contentView.backgroundColor = UIColor.clearColor()
self_.emailField.alpha = 0
self_.loginButton.removeTarget(self, action: "register", forControlEvents: .TouchUpInside)
self_.loginButton.addTarget(self, action: "login", forControlEvents: .TouchUpInside)
self_.loginButtonLabel.text = "登录"
self_.changeStateButton.setTitle("没有账号?现在注册!", forState: .Normal)
} else {
self_.emailField.text = ""
self_.emailImageView.alpha = 1
self_.emailFieldUnderline.contentView.backgroundColor = UIColor.lightTextColor()
self_.emailField.alpha = 1
self_.loginButton.removeTarget(self, action: "login", forControlEvents: .TouchUpInside)
self_.loginButton.addTarget(self, action: "register", forControlEvents: .TouchUpInside)
self_.loginButtonLabel.text = "注册"
self_.changeStateButton.setTitle("已有账号?马上登录!", forState: .Normal)
}
}
},
completion: nil)
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Manually inform image view to update it's appearences.
emailImageView.tintColorDidChange()
userNameImageView.tintColorDidChange()
passwordImageView.tintColorDidChange()
scrollView.delaysContentTouches = false
scrollView.msr_setTouchesShouldCancel(true, inContentViewWhichIsKindOfClass: UIControl.self)
emailField.attributedPlaceholder = NSAttributedString(string: emailField.placeholder!, attributes: [NSForegroundColorAttributeName: UIColor.lightTextColor().colorWithAlphaComponent(0.3)])
userNameField.attributedPlaceholder = NSAttributedString(string: userNameField.placeholder!, attributes: [NSForegroundColorAttributeName: UIColor.lightTextColor().colorWithAlphaComponent(0.3)])
passwordField.attributedPlaceholder = NSAttributedString(string: passwordField.placeholder!, attributes: [NSForegroundColorAttributeName: UIColor.lightTextColor().colorWithAlphaComponent(0.3)])
emailField.tintColor = UIColor.lightTextColor()
userNameField.tintColor = UIColor.lightTextColor()
passwordField.tintColor = UIColor.lightTextColor()
loginButton.msr_setBackgroundImageWithColor(UIColor.whiteColor())
loginButton.layer.cornerRadius = 5
loginButton.layer.masksToBounds = true
loginButton.addTarget(self, action: "login", forControlEvents: .TouchUpInside)
let tap = UITapGestureRecognizer(target: self, action: "didTouchBlankArea")
let pan = UIPanGestureRecognizer(target: self, action: "didTouchBlankArea")
scrollView.addGestureRecognizer(tap)
scrollView.addGestureRecognizer(pan)
pan.requireGestureRecognizerToFail(tap)
emailField.delegate = self
userNameField.delegate = self
passwordField.delegate = self
}
var firstAppear = true
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
emailField.text = ""
userNameField.text = ""
passwordField.text = ""
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if firstAppear {
firstAppear = false
User.loginWithCookiesAndCacheInStorage(
success: {
[weak self] user in
User.currentUser = user
self?.presentMainViewController()
},
failure: nil)
}
}
@IBAction func login() {
view.endEditing(true)
loginButton.hidden = true
loginButtonLabel.hidden = true
changeStateButton.hidden = true
loginActivityIndicatorView.startAnimating()
User.loginWithName(userNameField.text ?? "",
password: passwordField.text ?? "",
success: {
[weak self] user in
User.currentUser = user
if let self_ = self {
UIView.animateWithDuration(0.5) {
self_.loginButton.hidden = false
self_.loginButtonLabel.hidden = false
self_.changeStateButton.hidden = false
self_.loginActivityIndicatorView.stopAnimating()
}
self_.presentMainViewController()
}
},
failure: {
[weak self] error in
if let self_ = self {
UIView.animateWithDuration(0.5) {
self_.loginButton.hidden = false
self_.loginButtonLabel.hidden = false
self_.changeStateButton.hidden = false
self_.loginActivityIndicatorView.stopAnimating()
}
self_.errorMessageLabel.text = (error.userInfo[NSLocalizedDescriptionKey] as? String) ?? "未知错误"
let s = AFViewShaker(viewsArray: [self_.userNameImageViewContainerView, self_.userNameField, self_.passwordImageViewContainerView, self_.passwordField, self_.userNameFieldUnderline, self_.passwordFieldUnderline])
s.shake()
}
})
}
@IBAction func register() {
view.endEditing(true)
loginButton.hidden = true
loginButtonLabel.hidden = true
changeStateButton.hidden = true
errorMessageLabel.text = ""
loginActivityIndicatorView.startAnimating()
User.registerWithEmail(emailField.text ?? "",
name: userNameField.text ?? "",
password: passwordField.text ?? "",
success: {
[weak self] user in
User.currentUser = user
if let self_ = self {
UIView.animateWithDuration(0.5) {
self_.loginButton.hidden = false
self_.loginButtonLabel.hidden = false
self_.changeStateButton.hidden = false
self_.loginActivityIndicatorView.stopAnimating()
}
self_.presentMainViewController()
}
},
failure: {
[weak self] error in
if let self_ = self {
UIView.animateWithDuration(0.5) {
self_.loginButton.hidden = false
self_.loginButtonLabel.hidden = false
self_.changeStateButton.hidden = false
self_.loginActivityIndicatorView.stopAnimating()
}
self_.errorMessageLabel.text = (error.userInfo[NSLocalizedDescriptionKey] as? String) ?? "未知错误"
let s = AFViewShaker(viewsArray: [self_.userNameImageViewContainerView, self_.userNameField, self_.passwordImageViewContainerView, self_.passwordField, self_.userNameFieldUnderline, self_.passwordFieldUnderline, self_.emailImageViewContainerView, self_.emailField, self_.emailFieldUnderline])
s.shake()
}
})
}
func presentMainViewController() {
appDelegate.mainViewController = MainViewController()
appDelegate.mainViewController.modalTransitionStyle = .CrossDissolve
presentViewController(appDelegate.mainViewController, animated: true, completion: nil)
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
errorMessageLabel.text = ""
return true
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
if textField === emailField {
userNameField.becomeFirstResponder()
} else if textField === userNameField {
passwordField.becomeFirstResponder()
} else if textField === passwordField {
passwordField.endEditing(true)
login()
}
return true
}
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
return !loginActivityIndicatorView.isAnimating()
}
func keyboardWillChangeFrame(notification: NSNotification) {
let info = MSRAnimationInfo(keyboardNotification: notification)
info.animate() {
[weak self] in
if let self_ = self {
let sv = self_.scrollView
if info.frameEnd.minY == UIScreen.mainScreen().bounds.height {
sv.contentInset.bottom = 0
self_.titleLabel.alpha = 1
} else {
sv.contentInset.bottom = self_.titleLabelContainerView.frame.maxY + 20
self_.titleLabel.alpha = 0
}
sv.contentOffset.y = sv.contentSize.height - sv.bounds.height + sv.contentInset.bottom
}
}
}
func didTouchBlankArea() {
view.endEditing(true)
}
@IBAction func changeState() {
state = state == .Login ? .Registration : .Login
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .LightContent
}
}
| gpl-2.0 | c764b45392af91a970772aac83107658 | 44.184906 | 312 | 0.606314 | 5.957214 | false | false | false | false |
coderQuanjun/RxSwift-Table-Collection | RxSwift-Table-Collection1/RxSwift-Table-Collection/Tools/ObservableObjectMapper.swift | 1 | 1974 | //
// ObservableObjectMapper.swift
// RxSwiftMoyaDemo
//
// Created by iOS_Tian on 2017/9/29.
// Copyright © 2017年 iOS_Tian. All rights reserved.
//
import Foundation
import RxSwift
import Moya
import ObjectMapper
/*
extension Observable {
//1. 单个对象的处理
public func mapObject<T: Mappable>(type: T.Type) -> Observable<T> {
return self.map({ response in
//1-1. 如果response是一个字典,就用ObjectMapper映射这个字典
guard let dict = response as? [String: Any] else {
//1-2. 如果不是字典就抛出一个错误
throw NetworkRequestState.jsonError
}
//2. 返回模型数组
return Mapper<T>().map(JSON: dict)!
})
}
//2. 对象数组的处理
public func mapObjectArray<T: Mappable>(type: T.Type) -> Observable<[T]> {
return self.map({ response in
//2-0. 先判断返回类型是不是一个对象
guard let array = response as? [String: Any] else {
throw NetworkRequestState.jsonError
}
//2-1. 判断返回类型是不是一个对象
guard let anchors = array["message"] as? [String: Any] else {
throw NetworkRequestState.jsonError
}
//2-1. 如果response是一个字典数组,就用ObjectMapper映射这个数组
guard let dictArr = anchors["anchors"] as? [[String: Any]] else {
//2-2. 如果不是字典就抛出一个错误
throw NetworkRequestState.jsonError
}
//3. 返回模型数组
return Mapper<T>().mapArray(JSONArray: dictArr)
})
}
}
//请求错误显示信息
enum NetworkRequestState: String {
case jsonError = "解析错误"
case OtherError
}
extension NetworkRequestState : Error {}
*/
| mit | fde5082f6798e5c06f7f47d48e88ee6a | 24.746269 | 78 | 0.548406 | 4.207317 | false | false | false | false |
zmian/xcore.swift | Sources/Xcore/SwiftUI/Components/DynamicTextField/Formatter/Mask.swift | 1 | 1382 | //
// Xcore
// Copyright © 2021 Xcore
// MIT license, see LICENSE file for details
//
import Foundation
public protocol Mask {
var maskFormat: String { get set }
func string(from value: String) -> String
func value(from string: String) -> String
}
extension Mask {
public func string(from value: String) -> String {
let sanitizedValue = value.components(separatedBy: .decimalDigits.inverted).joined()
let mask = maskFormat
var result = ""
var index = sanitizedValue.startIndex
for ch in mask where index < sanitizedValue.endIndex {
if ch == "#" {
result.append(sanitizedValue[index])
index = sanitizedValue.index(after: index)
} else {
result.append(ch)
}
}
return result
}
public func value(from string: String) -> String {
string.replacing("-", with: "")
}
}
public struct PhoneNumberMask: Mask {
public var maskFormat: String = "###-###-####"
public init () {}
}
public struct SSNMask: Mask {
public var maskFormat: String = "###-##-####"
public init () {}
}
// MARK: - Dot Syntax Support
extension Mask where Self == PhoneNumberMask {
public static var phoneNumber: Self { .init() }
}
extension Mask where Self == SSNMask {
public static var ssn: Self { .init() }
}
| mit | 71d034de4c3d32ec85ce899904cf8247 | 23.22807 | 92 | 0.596669 | 4.223242 | false | false | false | false |
boolkybear/iOS-Challenge | CatViewer/CatViewer/CoreData/Category+Extras.swift | 1 | 1362 | //
// Category+Extras.swift
// CatViewer
//
// Created by Boolky Bear on 7/2/15.
// Copyright (c) 2015 ByBDesigns. All rights reserved.
//
import Foundation
extension Category
{
class func emptyCategoryInContext(context: NSManagedObjectContext) -> Category?
{
return context.emptyObjectOfKind("Category") as? Category
}
class func categoryWithIdentifier(identifier: String?, context: NSManagedObjectContext) -> Category?
{
if let identifier = identifier
{
return context.objectFromRequestNamed("CategoryWithIdentifier", substitution: ["IDENTIFIER" : identifier], sortDescriptors: nil, error: nil) as? Category
}
return nil
}
class func categoryFromModel(model: CategoryModel, context: NSManagedObjectContext) -> Category?
{
var category = categoryWithIdentifier(model.identifier, context: context)
if category == nil
{
category = emptyCategoryInContext(context)
category?.identifier = model.identifier
}
category?.name = model.name
return category
}
class func categoriesInContext(context: NSManagedObjectContext) -> [Category]
{
if let categories = context.objectsFromRequestNamed("Categories", substitution: [ NSObject : AnyObject ](), sortDescriptors: [ NSSortDescriptor(key: "name", ascending: true) ], error: nil)
{
return categories.map {
$0 as Category
}
}
return []
}
} | mit | d40bb7997b1b10a9a5c2dc09ee4608f3 | 24.716981 | 190 | 0.727606 | 4.005882 | false | false | false | false |
pikachu987/PKCAlertView | PKCAlertView/Classes/PKCButtonGroupView.swift | 1 | 7789 | //Copyright (c) 2017 pikachu987 <[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
protocol PKCButtonDelegate: class {
func pkcButtonAction()
}
class PKCButtonGrouopView: UIView {
var lineView: PKCLineView?
var delegate: PKCButtonDelegate?
var handler: ((PKCAlertButtonType, String) -> Void)? = nil
private override init(frame: CGRect) {
super.init(frame: frame)
self.translatesAutoresizingMaskIntoConstraints = false
self.clipsToBounds = true
}
private func addLineView(){
let lineView = PKCLineView(.height)
self.addSubview(lineView)
self.addConstraints(lineView.horizontalLayout())
self.addConstraint(NSLayoutConstraint(item: self, attribute: .top, relatedBy: .equal, toItem: lineView, attribute: .top, multiplier: 1, constant: 0))
self.lineView = lineView
}
public init(_ defaultButton: PKCAlertButton, handler: ((PKCAlertButtonType, String) -> Void)? = nil) {
self.init()
self.handler = handler
defaultButton.addTarget(self, action: #selector(self.buttonDefaultAction(_:)), for: .touchUpInside)
self.addSubview(defaultButton)
self.addConstraints(defaultButton.verticalLayout())
self.addConstraints(defaultButton.horizontalLayout())
self.addLineView()
}
public init(_ leftButton: PKCAlertButton, rightButton: PKCAlertButton, handler: ((PKCAlertButtonType, String) -> Void)? = nil) {
self.init()
self.handler = handler
leftButton.addTarget(self, action: #selector(self.buttonLeftAction(_:)), for: .touchUpInside)
self.addSubview(leftButton)
self.addConstraints(leftButton.verticalLayout())
rightButton.addTarget(self, action: #selector(self.buttonRightAction(_:)), for: .touchUpInside)
self.addSubview(rightButton)
self.addConstraints(rightButton.verticalLayout())
let lineView = PKCLineView(.width)
self.addSubview(lineView)
self.addConstraints(lineView.verticalLayout())
self.addConstraints(NSLayoutConstraint.constraints(
withVisualFormat: "H:|-0-[view1]-0-[view2]-0-[view3]-0-|",
options: NSLayoutFormatOptions(rawValue: 0), metrics: nil,
views: ["view1": leftButton, "view2": lineView, "view3": rightButton]
))
self.addConstraint(NSLayoutConstraint(item: leftButton, attribute: .width, relatedBy: .equal, toItem: rightButton, attribute: .width, multiplier: 1, constant: 0))
self.addLineView()
}
public init(_ leftButton: PKCAlertButton, centerButton: PKCAlertButton, rightButton: PKCAlertButton, handler: ((PKCAlertButtonType, String) -> Void)? = nil) {
self.init()
self.handler = handler
leftButton.addTarget(self, action: #selector(self.buttonLeftAction(_:)), for: .touchUpInside)
self.addSubview(leftButton)
self.addConstraints(leftButton.verticalLayout())
centerButton.addTarget(self, action: #selector(self.buttonCenterAction(_:)), for: .touchUpInside)
self.addSubview(centerButton)
self.addConstraints(centerButton.verticalLayout())
rightButton.addTarget(self, action: #selector(self.buttonRightAction(_:)), for: .touchUpInside)
self.addSubview(rightButton)
self.addConstraints(rightButton.verticalLayout())
let lineView1 = PKCLineView(.width)
self.addSubview(lineView1)
self.addConstraints(lineView1.verticalLayout())
let lineView2 = PKCLineView(.width)
self.addSubview(lineView2)
self.addConstraints(lineView2.verticalLayout())
self.addConstraints(NSLayoutConstraint.constraints(
withVisualFormat: "H:|-0-[view1]-0-[view2]-0-[view3]-0-[view4]-0-[view5]-0-|",
options: NSLayoutFormatOptions(rawValue: 0), metrics: nil,
views: ["view1": leftButton, "view2": lineView1, "view3": centerButton, "view4": lineView2, "view5": rightButton]
))
self.addConstraint(NSLayoutConstraint(item: leftButton, attribute: .width, relatedBy: .equal, toItem: centerButton, attribute: .width, multiplier: 1, constant: 0))
self.addConstraint(NSLayoutConstraint(item: leftButton, attribute: .width, relatedBy: .equal, toItem: rightButton, attribute: .width, multiplier: 1, constant: 0))
self.addLineView()
}
public convenience init(_ text: String, textColor: UIColor, handler: ((PKCAlertButtonType, String) -> Void)? = nil) {
let defaultButton = PKCAlertButton(text, textColor: textColor)
self.init(defaultButton, handler: handler)
}
public convenience init(_ leftText: String, leftColor: UIColor, rightText: String, rightColor: UIColor, handler: ((PKCAlertButtonType, String) -> Void)? = nil) {
let leftButton = PKCAlertButton(leftText, textColor: leftColor)
let rightButton = PKCAlertButton(rightText, textColor: rightColor)
self.init(leftButton, rightButton: rightButton, handler: handler)
}
public convenience init(_ leftText: String, leftColor: UIColor, centerText: String, centerColor: UIColor, rightText: String, rightColor: UIColor, handler: ((PKCAlertButtonType, String) -> Void)? = nil) {
let leftButton = PKCAlertButton(leftText, textColor: leftColor)
let centerButton = PKCAlertButton(centerText, textColor: centerColor)
let rightButton = PKCAlertButton(rightText, textColor: rightColor)
self.init(leftButton, centerButton: centerButton, rightButton: rightButton, handler: handler)
}
@objc private func buttonLeftAction(_ sender: PKCAlertButton){
self.handler?(.left, sender.title)
self.delegate?.pkcButtonAction()
}
@objc private func buttonCenterAction(_ sender: PKCAlertButton){
self.handler?(.center, sender.title)
self.delegate?.pkcButtonAction()
}
@objc private func buttonRightAction(_ sender: PKCAlertButton){
self.handler?(.right, sender.title)
self.delegate?.pkcButtonAction()
}
@objc private func buttonDefaultAction(_ sender: PKCAlertButton){
self.handler?(.default, sender.title)
self.delegate?.pkcButtonAction()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 868ed2225c585f1330a26a9e06616a4f | 36.447115 | 207 | 0.663757 | 4.74939 | false | false | false | false |
theappbusiness/TABCommunicate | Example/Tests/TABCommunicatorTests.swift | 1 | 2592 | //
// TABCommunicatorTests.swift
// TABCommunicate
//
// Created by Neil Horton on 04/04/2016.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import XCTest
@testable import TABCommunicate
class TABCommunicatorTests: XCTestCase {
var sut: TABCommunicator<MockTABCommunicable>!
var delegate: MockTABCommunicatorDelegate!
let testConfiguration = TABCommunicateConfiguration(serviceName: "test", numberOfRetryAttempts: 3, retryDelay: 0.1, password: "testPassword")
override func setUp() {
super.setUp()
delegate = MockTABCommunicatorDelegate()
sut = TABCommunicator(configuration: testConfiguration, delegate: delegate)
}
override func tearDown() {
sut = nil
delegate = nil
super.tearDown()
}
func test_communicableDataRecieved_createsObjectForDelegate() {
let validData = DataHelper.toDataFromDict(["test": "test"])
let expectation = expectationWithDescription("delegate informed")
delegate.expectation = expectation
sut.communicableDataRecieved(validData)
waitForExpectationsWithTimeout(2.0) { error in
XCTAssertNotNil(self.delegate.capturedCommunicable)
}
}
func test_newNumberOfPeers_whenNoPeersConnected_returnsFalse() {
let expectation = expectationWithDescription("delegate informed")
delegate.expectation = expectation
sut.newNumberOfPeers(0)
waitForExpectationsWithTimeout(2.0) { error in
XCTAssert(self.delegate.capturedConnected! == false)
}
}
func test_newNumberOfPeers_whenSomePeersConnected_returnsTrue() {
let expectation = expectationWithDescription("delegate informed")
delegate.expectation = expectation
sut.newNumberOfPeers(1)
waitForExpectationsWithTimeout(2.0) { error in
XCTAssert(self.delegate.capturedConnected! == true)
}
}
func test_communicableDataRecieved_passesObjectToInitialisedBlock() {
let expectation = expectationWithDescription("Object passed to block")
sut = TABCommunicator(configuration: testConfiguration) { _ in
expectation.fulfill()
}
let validData = DataHelper.toDataFromDict(["test": "test"])
sut.communicableDataRecieved(validData)
waitForExpectationsWithTimeout(2.0) { error in
if error != nil { XCTFail() }
}
}
func test_sendCommunicableObject_callsServiceAndSetsCompletion() {
let mockService = MockTABCommunicateServiceManager()
sut.communicateServiceManager = mockService
sut.sendCommunicableObject(MockTABCommunicable()) {result in}
XCTAssertNotNil(mockService.capturedCompletion)
}
}
| mit | c80cb8bebdccaba8a883d60054ab7304 | 30.987654 | 143 | 0.738325 | 4.651706 | false | true | false | false |
PureSwift/Bluetooth | Sources/BluetoothHCI/LowEnergyFeature.swift | 1 | 6474 | //
// LowEnergyFeature.swift
// Bluetooth
//
// Created by Alsey Coleman Miller on 3/29/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
/**
LE Feature Support
The set of features supported by a Link Layer is represented by a bit mask called FeatureSet. The value of FeatureSet shall not change while the Controller has a connection to another device. A peer device may cache information about features that the device supports. The Link Layer may cache information about features that a peer supports during a connection.
Within FeatureSet, a bit set to 0 indicates that the Link Layer Feature is not supported in this Controller; a bit set to 1 indicates that the Link Layer Feature is supported in this Controller.
A Link Layer shall not use a procedure that is not supported by the peer’s Link Layer. A Link Layer shall not transmit a PDU listed in the following subsections unless it supports at least one of the features that requires support for that PDU.
The bit positions for each Link Layer Feature shall be as shown in Table 4.4. This table also shows if these bits are valid between Controllers. If a bit is shown as not valid, using ‘N’, then this bit shall be ignored upon receipt by the peer Controller.
*/
@frozen
public enum LowEnergyFeature: UInt64, BitMaskOption {
/// LE Encryption
case encryption = 0b0000000000000001
/// Connection Parameters Request Procedure
case connectionParametersRequestProcedure = 0b0000000000000010
/// Extended Reject Indication
case extendedRejectIndication = 0b0000000000000100
/// Slave-initiated Features Exchange
case slaveInitiatedFeaturesExchange = 0b0000000000001000
/// LE Ping
case ping = 0b0000000000010000
/// LE Data Packet Length Extension
case dataPacketLengthExtension = 0b0000000000100000
/// LE Privacy
case privacy = 0b0000000001000000
/// Extended Scanner Filter Policies
case extendedScannerFilterPolicies = 0b0000000010000000
/// LE 2M PHY
case le2mPhy = 0b0000000100000000
/// Stable Modulation Index - Transmitter
case stableModulationIndexTransmitter = 0b0000001000000000
/// Stable Modulation Index - Receiver
case stableModulationIndexReceiver = 0b0000010000000000
/// LE Coded PHY
case codedPhy = 0b0000100000000000
/// LE Extended Advertising
case extendedAdvertising = 0b0001000000000000
/// LE Periodic Advertising
case periodicAdvertising = 0b0010000000000000
/// Channel Selection Algorithm #2
case channelSelectionAlgorithm2 = 0b0100000000000000
/// LE Power Class 1
case powerClass1 = 0b1000000000000000
/// Minimum Number of Used Channels Procedure
case minimumNumberofUsedChannelsProcedure = 0b10000000000000000
public static let allCases: [LowEnergyFeature] = [
.encryption,
.connectionParametersRequestProcedure,
.extendedRejectIndication,
.slaveInitiatedFeaturesExchange,
.ping,
.dataPacketLengthExtension,
.privacy,
.extendedScannerFilterPolicies,
.le2mPhy,
.stableModulationIndexTransmitter,
.stableModulationIndexReceiver,
.codedPhy,
.extendedAdvertising,
.periodicAdvertising,
.channelSelectionAlgorithm2,
.powerClass1,
.minimumNumberofUsedChannelsProcedure
]
}
// MARK: - CustomStringConvertible
extension LowEnergyFeature: CustomStringConvertible {
public var description: String {
return name
}
}
// MARK: - Values
public extension LowEnergyFeature {
/// FeatureSet field’s bit mapping to Controller features
internal var values: (isValid: Bool, name: String) {
@inline(__always)
get {
guard let value = featureSet[self]
else { fatalError("Invalid enum \(self)" ) }
return value
}
}
/// Whether the feaure is valid from Controller to Controller.
var isValidControllerToController: Bool {
return values.isValid
}
/// Name of LE feature.
var name: String {
return values.name
}
}
/// FeatureSet field’s bit mapping to Controller features
internal let featureSet: [LowEnergyFeature: (isValid: Bool, name: String)] = [
// swiftlint:disable colon
.encryption: (true, "LE Encryption"),
.connectionParametersRequestProcedure: (true, "Connection Parameters Request Procedure"),
.extendedRejectIndication: (true, "Extended Reject Indication"),
.slaveInitiatedFeaturesExchange: (true, "Slave-initiated Features Exchange"),
.ping: (false, "LE Ping"),
.dataPacketLengthExtension: (true, "LE Data Packet Length Extension"),
.privacy: (false, "LL Privacy"),
.extendedScannerFilterPolicies: (true, "Extended Scanner Filter Policies"),
.le2mPhy: (true, "LE 2M PHY"),
.stableModulationIndexTransmitter: (true, "Stable Modulation Index - Transmitter"),
.stableModulationIndexReceiver: (true, "Stable Modulation Index - Receiver"),
.codedPhy: (true, "LE Coded PHY"),
.extendedAdvertising: (false, "LE Extended Advertising"),
.periodicAdvertising: (false, "LE Periodic Advertising"),
.channelSelectionAlgorithm2: (true, "Channel Selection Algorithm #2"),
.powerClass1: (true, "LE Power Class 1"),
.minimumNumberofUsedChannelsProcedure: (false, "Minimum Number of Used Channels Procedure")
]
// swiftlint:enable colon
// MARK: - Supporting Types
public typealias LowEnergyFeatureSet = BitMaskOptionSet<LowEnergyFeature>
| mit | ace45051c66ccdc6e60c9c41bcd065eb | 39.39375 | 363 | 0.618598 | 5.280229 | false | false | false | false |
bitboylabs/selluv-ios | selluv-ios/Pods/ObjectMapper/Sources/DateFormatterTransform.swift | 134 | 1838 | //
// DateFormatterTransform.swift
// ObjectMapper
//
// Created by Tristan Himmelman on 2015-03-09.
//
// The MIT License (MIT)
//
// Copyright (c) 2014-2016 Hearst
//
// 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
open class DateFormatterTransform: TransformType {
public typealias Object = Date
public typealias JSON = String
public let dateFormatter: DateFormatter
public init(dateFormatter: DateFormatter) {
self.dateFormatter = dateFormatter
}
open func transformFromJSON(_ value: Any?) -> Date? {
if let dateString = value as? String {
return dateFormatter.date(from: dateString)
}
return nil
}
open func transformToJSON(_ value: Date?) -> String? {
if let date = value {
return dateFormatter.string(from: date)
}
return nil
}
}
| mit | fbc1a5015df780d8ed632c02ee7e0bc5 | 33.037037 | 81 | 0.737758 | 4.177273 | false | false | false | false |
sonnygauran/trailer | Shared/PRStatus.swift | 1 | 2226 | import Foundation
let darkStatusRed = MAKECOLOR(0.8, 0.5, 0.5, 1.0)
let darkStatusYellow = MAKECOLOR(0.9, 0.8, 0.3, 1.0)
let darkStatusGreen = MAKECOLOR(0.6, 0.8, 0.6, 1.0)
let lightStatusRed = MAKECOLOR(0.5, 0.2, 0.2, 1.0)
let lightStatusYellow = MAKECOLOR(0.6, 0.5, 0.0, 1.0)
let lightStatusGreen = MAKECOLOR(0.3, 0.5, 0.3, 1.0)
let dateFormatter = { () -> NSDateFormatter in
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle
dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle
return dateFormatter
}()
final class PRStatus: DataItem {
@NSManaged var descriptionText: String?
@NSManaged var state: String?
@NSManaged var targetUrl: String?
@NSManaged var url: String?
@NSManaged var userId: NSNumber?
@NSManaged var userName: String?
@NSManaged var pullRequest: PullRequest
class func statusWithInfo(info: [NSObject : AnyObject], fromServer: ApiServer) -> PRStatus {
let s = DataItem.itemWithInfo(info, type: "PRStatus", fromServer: fromServer) as! PRStatus
if s.postSyncAction?.integerValue != PostSyncAction.DoNothing.rawValue {
s.url = N(info, "url") as? String
s.state = N(info, "state") as? String
s.targetUrl = N(info, "target_url") as? String
if let ds = N(info, "description") as? String {
s.descriptionText = ds.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
}
if let userInfo = N(info, "creator") as? [NSObject : AnyObject] {
s.userName = N(userInfo, "login") as? String
s.userId = N(userInfo, "id") as? NSNumber
}
}
return s
}
func colorForDarkDisplay() -> COLOR_CLASS {
switch state! {
case "pending":
return darkStatusYellow
case "success":
return darkStatusGreen
default:
return darkStatusRed
}
}
func colorForDisplay() -> COLOR_CLASS {
switch state! {
case "pending":
return lightStatusYellow
case "success":
return lightStatusGreen
default:
return lightStatusRed
}
}
func displayText() -> String {
if let desc = descriptionText {
return String(format: "%@ %@", dateFormatter.stringFromDate(createdAt!), desc)
} else {
return "(No description)"
}
}
}
| mit | 53a1f8cb47da18d0fda631b81e4a3b63 | 27.909091 | 121 | 0.690925 | 3.424615 | false | false | false | false |
Kamaros/ELDeveloperKeyboard | Keyboard/Suggestion/SuggestionTrie.swift | 1 | 4755 | //
// SuggestionTrie.swift
// ELDeveloperKeyboard
//
// Created by Eric Lin on 2014-07-03.
// Copyright (c) 2014 Eric Lin. All rights reserved.
//
import Foundation
/**
An implementation of the SuggestionProvider protocol that uses a ternary search tree (trie) to store and search for terms.
*/
class SuggestionTrie: SuggestionProvider {
// MARK: Properties
private var root: SuggestionNode?
// MARK: Constructors
init() {}
// MARK: SuggestionProvider methods
func suggestionsForPrefix(prefix: String) -> [String] {
if let node = searchForNodeMatchingPrefix(prefix, rootNode: root) {
var weightedSuggestions = [WeightedString]()
findSuggestionsForNode(node.equalKid, suggestions: &weightedSuggestions)
return weightedSuggestions
.sorted { $0.weight >= $1.weight }
.map { $0.term }
}
return []
}
func loadWeightedStrings(weightedStrings: [WeightedString]) {
for ws in weightedStrings {
insertString(ws.term, weight: ws.weight)
}
}
func clear() {
deleteNode(&root)
}
// MARK: Helper Methods
private func insertString(s: String, weight: Int) {
if let node = searchForNodeMatchingPrefix(s, rootNode: root) {
node.isWordEnd = true
node.weight = weight
} else {
insertString(s, charIndex: 0, weight: weight, node: &root)
}
}
private func insertString(s: String, charIndex: Int, weight: Int, inout node: SuggestionNode?) {
let charCount = count(s)
if charCount > 0 {
if node == nil {
if charCount == charIndex + 1 {
node = SuggestionNode(term: s, weight: weight)
} else {
node = SuggestionNode(term: s[0..<charIndex + 1])
}
}
if s[charIndex] < node!.char {
insertString(s, charIndex: charIndex, weight: weight, node: &node!.loKid)
} else if s[charIndex] > node!.char {
insertString(s, charIndex: charIndex, weight: weight, node: &node!.hiKid)
} else if charCount > charIndex + 1 {
insertString(s, charIndex: charIndex + 1, weight: weight, node: &node!.equalKid)
}
}
}
private func searchForNodeMatchingPrefix(prefix: String, rootNode: SuggestionNode?) -> SuggestionNode? {
let charCount = count(prefix)
if rootNode == nil || charCount == 0 {
return nil
} else if charCount == 1 && prefix == rootNode!.char {
return rootNode
}
if prefix[0] < rootNode!.char {
return searchForNodeMatchingPrefix(prefix, rootNode: rootNode!.loKid)
} else if prefix[0] > rootNode!.char {
return searchForNodeMatchingPrefix(prefix, rootNode: rootNode!.hiKid)
} else {
return searchForNodeMatchingPrefix(prefix[1..<charCount], rootNode: rootNode!.equalKid)
}
}
private func findSuggestionsForNode(node: SuggestionNode?, inout suggestions: [WeightedString]) {
if let n = node {
if n.isWordEnd {
suggestions.append(WeightedString(term: n.term, weight: n.weight))
}
findSuggestionsForNode(n.loKid, suggestions: &suggestions)
findSuggestionsForNode(n.equalKid, suggestions: &suggestions)
findSuggestionsForNode(n.hiKid, suggestions: &suggestions)
}
}
private func deleteNode(inout node: SuggestionNode?) {
if let n = node {
deleteNode(&n.loKid)
deleteNode(&n.equalKid)
deleteNode(&n.hiKid)
node = nil
}
}
/**
A SuggestionTrie node, representing a term.
*/
private class SuggestionNode {
// MARK: Properties
let term: String
var weight: Int
var char: String {
return term[count(term) - 1]
}
var isWordEnd: Bool
var loKid: SuggestionNode?
var equalKid: SuggestionNode?
var hiKid: SuggestionNode?
// MARK: Constructors
init(term: String, isWordEnd: Bool, weight: Int) {
self.term = term
self.isWordEnd = isWordEnd
self.weight = weight
}
convenience init(term: String, weight: Int) {
self.init(term: term, isWordEnd: true, weight: weight)
}
convenience init(term: String) {
self.init(term: term, isWordEnd: false, weight: 0)
}
}
} | apache-2.0 | f4875b401d80b58fb8a9300595b1f12c | 30.496689 | 126 | 0.562566 | 4.507109 | false | false | false | false |
bitboylabs/selluv-ios | selluv-ios/Pods/ObjectMapper/Sources/ToJSON.swift | 50 | 5659 | //
// ToJSON.swift
// ObjectMapper
//
// Created by Tristan Himmelman on 2014-10-13.
//
// The MIT License (MIT)
//
// Copyright (c) 2014-2016 Hearst
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
private func setValue(_ value: Any, map: Map) {
setValue(value, key: map.currentKey!, checkForNestedKeys: map.keyIsNested, delimiter: map.nestedKeyDelimiter, dictionary: &map.JSON)
}
private func setValue(_ value: Any, key: String, checkForNestedKeys: Bool, delimiter: String, dictionary: inout [String : Any]) {
if checkForNestedKeys {
let keyComponents = ArraySlice(key.components(separatedBy: delimiter).filter { !$0.isEmpty }.map { $0.characters })
setValue(value, forKeyPathComponents: keyComponents, dictionary: &dictionary)
} else {
dictionary[key] = value
}
}
private func setValue(_ value: Any, forKeyPathComponents components: ArraySlice<String.CharacterView.SubSequence>, dictionary: inout [String : Any]) {
if components.isEmpty {
return
}
let head = components.first!
if components.count == 1 {
dictionary[String(head)] = value
} else {
var child = dictionary[String(head)] as? [String : Any]
if child == nil {
child = [:]
}
let tail = components.dropFirst()
setValue(value, forKeyPathComponents: tail, dictionary: &child!)
dictionary[String(head)] = child
}
}
internal final class ToJSON {
class func basicType<N>(_ field: N, map: Map) {
if let x = field as Any? , false
|| x is NSNumber // Basic types
|| x is Bool
|| x is Int
|| x is Double
|| x is Float
|| x is String
|| x is NSNull
|| x is Array<NSNumber> // Arrays
|| x is Array<Bool>
|| x is Array<Int>
|| x is Array<Double>
|| x is Array<Float>
|| x is Array<String>
|| x is Array<Any>
|| x is Array<Dictionary<String, Any>>
|| x is Dictionary<String, NSNumber> // Dictionaries
|| x is Dictionary<String, Bool>
|| x is Dictionary<String, Int>
|| x is Dictionary<String, Double>
|| x is Dictionary<String, Float>
|| x is Dictionary<String, String>
|| x is Dictionary<String, Any>
{
setValue(x, map: map)
}
}
class func optionalBasicType<N>(_ field: N?, map: Map) {
if let field = field {
basicType(field, map: map)
} else if map.shouldIncludeNilValues {
basicType(NSNull(), map: map) //If BasicType is nil, emil NSNull into the JSON output
}
}
class func object<N: BaseMappable>(_ field: N, map: Map) {
if let result = Mapper(context: map.context).toJSON(field) as Any? {
setValue(result, map: map)
}
}
class func optionalObject<N: BaseMappable>(_ field: N?, map: Map) {
if let field = field {
object(field, map: map)
}
}
class func objectArray<N: BaseMappable>(_ field: Array<N>, map: Map) {
let JSONObjects = Mapper(context: map.context).toJSONArray(field)
setValue(JSONObjects, map: map)
}
class func optionalObjectArray<N: BaseMappable>(_ field: Array<N>?, map: Map) {
if let field = field {
objectArray(field, map: map)
}
}
class func twoDimensionalObjectArray<N: BaseMappable>(_ field: Array<Array<N>>, map: Map) {
var array = [[[String: Any]]]()
for innerArray in field {
let JSONObjects = Mapper(context: map.context).toJSONArray(innerArray)
array.append(JSONObjects)
}
setValue(array, map: map)
}
class func optionalTwoDimensionalObjectArray<N: BaseMappable>(_ field: Array<Array<N>>?, map: Map) {
if let field = field {
twoDimensionalObjectArray(field, map: map)
}
}
class func objectSet<N: BaseMappable>(_ field: Set<N>, map: Map) where N: Hashable {
let JSONObjects = Mapper(context: map.context).toJSONSet(field)
setValue(JSONObjects, map: map)
}
class func optionalObjectSet<N: BaseMappable>(_ field: Set<N>?, map: Map) where N: Hashable {
if let field = field {
objectSet(field, map: map)
}
}
class func objectDictionary<N: BaseMappable>(_ field: Dictionary<String, N>, map: Map) {
let JSONObjects = Mapper(context: map.context).toJSONDictionary(field)
setValue(JSONObjects, map: map)
}
class func optionalObjectDictionary<N: BaseMappable>(_ field: Dictionary<String, N>?, map: Map) {
if let field = field {
objectDictionary(field, map: map)
}
}
class func objectDictionaryOfArrays<N: BaseMappable>(_ field: Dictionary<String, [N]>, map: Map) {
let JSONObjects = Mapper(context: map.context).toJSONDictionaryOfArrays(field)
setValue(JSONObjects, map: map)
}
class func optionalObjectDictionaryOfArrays<N: BaseMappable>(_ field: Dictionary<String, [N]>?, map: Map) {
if let field = field {
objectDictionaryOfArrays(field, map: map)
}
}
}
| mit | cc346303d48c5739c3c99a88c4a35b59 | 30.614525 | 150 | 0.693585 | 3.530256 | false | false | false | false |
CodeMozart/MHzSinaWeibo-Swift- | SinaWeibo(stroyboard)/SinaWeibo/Classes/Discover/DiscoverViewController.swift | 1 | 3139 | //
// DiscoverViewController.swift
// SinaWeibo
//
// Created by Minghe on 11/6/15.
// Copyright © 2015 Stanford swift. All rights reserved.
//
import UIKit
class DiscoverViewController: BaseTableViewController {
override func viewDidLoad() {
super.viewDidLoad()
if !login {
visitorView?.setupVisitorInfo("visitordiscover_image_message", title: "登录后,最新、最热微博尽在掌握,不再会与实事潮流擦肩而过")
return
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 642fdc287f339b3fdeffea01d100be36 | 31.442105 | 157 | 0.675211 | 5.41652 | false | false | false | false |
eurofurence/ef-app_ios | Packages/EurofurenceComponents/Sources/EventDetailComponent/Component/EventDetailComponentBuilder.swift | 1 | 1396 | import ComponentBase
import Foundation
import UIKit.UIViewController
public class EventDetailComponentBuilder {
private let eventDetailViewModelFactory: EventDetailViewModelFactory
private let interactionRecorder: EventInteractionRecorder
private var sceneFactory: EventDetailSceneFactory
private var hapticEngine: SelectionChangedHaptic
public init(
eventDetailViewModelFactory: EventDetailViewModelFactory,
interactionRecorder: EventInteractionRecorder
) {
self.eventDetailViewModelFactory = eventDetailViewModelFactory
self.interactionRecorder = interactionRecorder
sceneFactory = StoryboardEventDetailSceneFactory()
hapticEngine = CocoaTouchHapticEngine()
}
@discardableResult
public func with(_ sceneFactory: EventDetailSceneFactory) -> Self {
self.sceneFactory = sceneFactory
return self
}
@discardableResult
public func with(_ hapticEngine: SelectionChangedHaptic) -> Self {
self.hapticEngine = hapticEngine
return self
}
public func build() -> EventDetailComponentFactory {
EventDetailComponentFactoryImpl(
sceneFactory: sceneFactory,
eventDetailViewModelFactory: eventDetailViewModelFactory,
hapticEngine: hapticEngine,
interactionRecorder: interactionRecorder
)
}
}
| mit | 08afad91a2adf9dbbc0c8f12509904a8 | 30.727273 | 72 | 0.730659 | 6.43318 | false | false | false | false |
eurofurence/ef-app_ios | Packages/EurofurenceApplication/Tests/EurofurenceApplicationTests/Application/Components/News/Test Doubles/FakeCompositionalNewsSceneFactory.swift | 1 | 1344 | import EurofurenceApplication
import UIKit
class FakeCompositionalNewsSceneFactory: CompositionalNewsSceneFactory {
let scene = FakeCompositionalNewsScene()
func makeCompositionalNewsScene() -> UIViewController & CompositionalNewsScene {
scene
}
}
class FakeCompositionalNewsScene: UIViewController, CompositionalNewsScene {
enum LoadingIndicatorState: Equatable {
case unknown
case visible
case hidden
}
private(set) var installedDataSources = [TableViewMediator]()
private(set) var loadingIndicatorState: LoadingIndicatorState = .unknown
private var delegate: CompositionalNewsSceneDelegate?
func setDelegate(_ delegate: CompositionalNewsSceneDelegate) {
self.delegate = delegate
}
func install(dataSource: TableViewMediator) {
installedDataSources.append(dataSource)
}
func showLoadingIndicator() {
loadingIndicatorState = .visible
}
func hideLoadingIndicator() {
loadingIndicatorState = .hidden
}
func simulateSceneReady() {
delegate?.sceneReady()
}
func simulateRefreshRequested() {
delegate?.reloadRequested()
}
func simulateSettingsTapped(sender: Any) {
delegate?.settingsTapped(sender: sender)
}
}
| mit | a2bf7935b9a63e3cbbf30a5cd7763182 | 24.358491 | 84 | 0.683036 | 5.419355 | false | false | false | false |
AkikoZ/PocketHTTP | PocketHTTP/PocketHTTP/Request/ResponseInfoViewController.swift | 1 | 1788 | //
// ResponseInfoViewController.swift
// PocketHTTP
//
// Created by 朱子秋 on 2017/1/30.
// Copyright © 2017年 朱子秋. All rights reserved.
//
import UIKit
class ResponseInfoViewController: UITableViewController {
var responseInfo: HTTPURLResponse!
private lazy var orderedHeaders: [(key: String, value: String)] = {
var orderedHeaders = [(key: String, value: String)]()
for (key, value) in self.responseInfo.allHeaderFields {
orderedHeaders.append((key: key as! String, value: value as! String))
}
return orderedHeaders
}()
override func viewDidLoad() {
super.viewDidLoad()
tableView.tableFooterView = UIView()
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return section == 0 ? 1 : orderedHeaders.count
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return section == 0 ? "Status Code" : "Response Headers"
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "InfoCell", for: indexPath)
if indexPath.section == 0 {
cell.textLabel!.text = String(responseInfo.statusCode)
cell.detailTextLabel!.text = HTTPURLResponse.localizedString(forStatusCode: responseInfo.statusCode)
} else {
cell.textLabel!.text = orderedHeaders[indexPath.row].key
cell.detailTextLabel!.text = orderedHeaders[indexPath.row].value
}
return cell
}
}
| gpl-3.0 | ebd74847f6e16f72f422b4a607f55a65 | 33.096154 | 112 | 0.65877 | 4.870879 | false | false | false | false |
AaronMT/firefox-ios | Client/Frontend/Browser/Tab.swift | 4 | 25747 | /* 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 WebKit
import Storage
import Shared
import SwiftyJSON
import XCGLogger
fileprivate var debugTabCount = 0
func mostRecentTab(inTabs tabs: [Tab]) -> Tab? {
var recent = tabs.first
tabs.forEach { tab in
if let time = tab.lastExecutedTime, time > (recent?.lastExecutedTime ?? 0) {
recent = tab
}
}
return recent
}
protocol TabContentScript {
static func name() -> String
func scriptMessageHandlerName() -> String?
func userContentController(_ userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage)
}
@objc
protocol TabDelegate {
func tab(_ tab: Tab, didAddSnackbar bar: SnackBar)
func tab(_ tab: Tab, didRemoveSnackbar bar: SnackBar)
func tab(_ tab: Tab, didSelectFindInPageForSelection selection: String)
func tab(_ tab: Tab, didSelectSearchWithFirefoxForSelection selection: String)
@objc optional func tab(_ tab: Tab, didCreateWebView webView: WKWebView)
@objc optional func tab(_ tab: Tab, willDeleteWebView webView: WKWebView)
}
@objc
protocol URLChangeDelegate {
func tab(_ tab: Tab, urlDidChangeTo url: URL)
}
struct TabState {
var isPrivate: Bool = false
var url: URL?
var title: String?
var favicon: Favicon?
}
class Tab: NSObject {
fileprivate var _isPrivate: Bool = false
internal fileprivate(set) var isPrivate: Bool {
get {
return _isPrivate
}
set {
if _isPrivate != newValue {
_isPrivate = newValue
}
}
}
var tabState: TabState {
return TabState(isPrivate: _isPrivate, url: url, title: displayTitle, favicon: displayFavicon)
}
// PageMetadata is derived from the page content itself, and as such lags behind the
// rest of the tab.
var pageMetadata: PageMetadata?
var consecutiveCrashes: UInt = 0
var canonicalURL: URL? {
if let string = pageMetadata?.siteURL,
let siteURL = URL(string: string) {
// If the canonical URL from the page metadata doesn't contain the
// "#" fragment, check if the tab's URL has a fragment and if so,
// append it to the canonical URL.
if siteURL.fragment == nil,
let fragment = self.url?.fragment,
let siteURLWithFragment = URL(string: "\(string)#\(fragment)") {
return siteURLWithFragment
}
return siteURL
}
return self.url
}
var userActivity: NSUserActivity?
var webView: WKWebView?
var tabDelegate: TabDelegate?
weak var urlDidChangeDelegate: URLChangeDelegate? // TODO: generalize this.
var bars = [SnackBar]()
var favicons = [Favicon]()
var lastExecutedTime: Timestamp?
var sessionData: SessionData?
fileprivate var lastRequest: URLRequest?
var restoring: Bool = false
var pendingScreenshot = false
var url: URL? {
didSet {
if let _url = url, let internalUrl = InternalURL(_url), internalUrl.isAuthorized {
url = URL(string: internalUrl.stripAuthorization)
}
}
}
var mimeType: String?
var isEditing: Bool = false
// When viewing a non-HTML content type in the webview (like a PDF document), this URL will
// point to a tempfile containing the content so it can be shared to external applications.
var temporaryDocument: TemporaryDocument?
/// Returns true if this tab's URL is known, and it's longer than we want to store.
var urlIsTooLong: Bool {
guard let url = self.url else {
return false
}
return url.absoluteString.lengthOfBytes(using: .utf8) > AppConstants.DB_URL_LENGTH_MAX
}
// Use computed property so @available can be used to guard `noImageMode`.
var noImageMode: Bool {
didSet {
guard noImageMode != oldValue else {
return
}
contentBlocker?.noImageMode(enabled: noImageMode)
UserScriptManager.shared.injectUserScriptsIntoTab(self, nightMode: nightMode, noImageMode: noImageMode)
}
}
var nightMode: Bool {
didSet {
guard nightMode != oldValue else {
return
}
webView?.evaluateJavaScript("window.__firefox__.NightMode.setEnabled(\(nightMode))")
// For WKWebView background color to take effect, isOpaque must be false,
// which is counter-intuitive. Default is true. The color is previously
// set to black in the WKWebView init.
webView?.isOpaque = !nightMode
UserScriptManager.shared.injectUserScriptsIntoTab(self, nightMode: nightMode, noImageMode: noImageMode)
}
}
var contentBlocker: FirefoxTabContentBlocker?
/// The last title shown by this tab. Used by the tab tray to show titles for zombie tabs.
var lastTitle: String?
/// Whether or not the desktop site was requested with the last request, reload or navigation.
var changedUserAgent: Bool = false {
didSet {
if changedUserAgent != oldValue {
TabEvent.post(.didToggleDesktopMode, for: self)
}
}
}
var readerModeAvailableOrActive: Bool {
if let readerMode = self.getContentScript(name: "ReaderMode") as? ReaderMode {
return readerMode.state != .unavailable
}
return false
}
fileprivate(set) var screenshot: UIImage?
var screenshotUUID: UUID?
// If this tab has been opened from another, its parent will point to the tab from which it was opened
weak var parent: Tab?
fileprivate var contentScriptManager = TabContentScriptManager()
fileprivate let configuration: WKWebViewConfiguration
/// Any time a tab tries to make requests to display a Javascript Alert and we are not the active
/// tab instance, queue it for later until we become foregrounded.
fileprivate var alertQueue = [JSAlertInfo]()
weak var browserViewController: BrowserViewController?
init(bvc: BrowserViewController, configuration: WKWebViewConfiguration, isPrivate: Bool = false) {
self.configuration = configuration
self.nightMode = false
self.noImageMode = false
self.browserViewController = bvc
super.init()
self.isPrivate = isPrivate
debugTabCount += 1
TelemetryWrapper.recordEvent(category: .action, method: .add, object: .tab, value: isPrivate ? .privateTab : .normalTab)
}
class func toRemoteTab(_ tab: Tab) -> RemoteTab? {
if tab.isPrivate {
return nil
}
if let displayURL = tab.url?.displayURL, RemoteTab.shouldIncludeURL(displayURL) {
let history = Array(tab.historyList.filter(RemoteTab.shouldIncludeURL).reversed())
return RemoteTab(clientGUID: nil,
URL: displayURL,
title: tab.displayTitle,
history: history,
lastUsed: Date.now(),
icon: nil)
} else if let sessionData = tab.sessionData, !sessionData.urls.isEmpty {
let history = Array(sessionData.urls.filter(RemoteTab.shouldIncludeURL).reversed())
if let displayURL = history.first {
return RemoteTab(clientGUID: nil,
URL: displayURL,
title: tab.displayTitle,
history: history,
lastUsed: sessionData.lastUsedTime,
icon: nil)
}
}
return nil
}
weak var navigationDelegate: WKNavigationDelegate? {
didSet {
if let webView = webView {
webView.navigationDelegate = navigationDelegate
}
}
}
func createWebview() {
if webView == nil {
configuration.userContentController = WKUserContentController()
configuration.allowsInlineMediaPlayback = true
let webView = TabWebView(frame: .zero, configuration: configuration)
webView.delegate = self
webView.accessibilityLabel = NSLocalizedString("Web content", comment: "Accessibility label for the main web content view")
webView.allowsBackForwardNavigationGestures = true
if #available(iOS 13, *) {
webView.allowsLinkPreview = true
} else {
webView.allowsLinkPreview = false
}
// Night mode enables this by toggling WKWebView.isOpaque, otherwise this has no effect.
webView.backgroundColor = .black
// Turning off masking allows the web content to flow outside of the scrollView's frame
// which allows the content appear beneath the toolbars in the BrowserViewController
webView.scrollView.layer.masksToBounds = false
webView.navigationDelegate = navigationDelegate
restore(webView)
self.webView = webView
self.webView?.addObserver(self, forKeyPath: KVOConstants.URL.rawValue, options: .new, context: nil)
UserScriptManager.shared.injectUserScriptsIntoTab(self, nightMode: nightMode, noImageMode: noImageMode)
tabDelegate?.tab?(self, didCreateWebView: webView)
}
}
func restore(_ webView: WKWebView) {
// Pulls restored session data from a previous SavedTab to load into the Tab. If it's nil, a session restore
// has already been triggered via custom URL, so we use the last request to trigger it again; otherwise,
// we extract the information needed to restore the tabs and create a NSURLRequest with the custom session restore URL
// to trigger the session restore via custom handlers
if let sessionData = self.sessionData {
restoring = true
var urls = [String]()
for url in sessionData.urls {
urls.append(url.absoluteString)
}
let currentPage = sessionData.currentPage
self.sessionData = nil
var jsonDict = [String: AnyObject]()
jsonDict["history"] = urls as AnyObject?
jsonDict["currentPage"] = currentPage as AnyObject?
guard let json = JSON(jsonDict).stringify()?.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {
return
}
if let restoreURL = URL(string: "\(InternalURL.baseUrl)/\(SessionRestoreHandler.path)?history=\(json)") {
let request = PrivilegedRequest(url: restoreURL) as URLRequest
webView.load(request)
lastRequest = request
}
} else if let request = lastRequest {
webView.load(request)
} else {
print("creating webview with no lastRequest and no session data: \(self.url?.description ?? "nil")")
}
}
deinit {
debugTabCount -= 1
#if DEBUG
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
func checkTabCount(failures: Int) {
// Need delay for pool to drain.
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
if appDelegate.tabManager.tabs.count == debugTabCount {
return
}
// If this assert has false positives, remove it and just log an error.
assert(failures < 3, "Tab init/deinit imbalance, possible memory leak.")
checkTabCount(failures: failures + 1)
}
}
checkTabCount(failures: 0)
#endif
}
func close() {
contentScriptManager.uninstall(tab: self)
webView?.removeObserver(self, forKeyPath: KVOConstants.URL.rawValue)
if let webView = webView {
tabDelegate?.tab?(self, willDeleteWebView: webView)
}
webView?.navigationDelegate = nil
webView?.removeFromSuperview()
webView = nil
}
var loading: Bool {
return webView?.isLoading ?? false
}
var estimatedProgress: Double {
return webView?.estimatedProgress ?? 0
}
var backList: [WKBackForwardListItem]? {
return webView?.backForwardList.backList
}
var forwardList: [WKBackForwardListItem]? {
return webView?.backForwardList.forwardList
}
var historyList: [URL] {
func listToUrl(_ item: WKBackForwardListItem) -> URL { return item.url }
var tabs = self.backList?.map(listToUrl) ?? [URL]()
if let url = url {
tabs.append(url)
}
return tabs
}
var title: String? {
return webView?.title
}
var displayTitle: String {
if let title = webView?.title, !title.isEmpty {
return title
}
// When picking a display title. Tabs with sessionData are pending a restore so show their old title.
// To prevent flickering of the display title. If a tab is restoring make sure to use its lastTitle.
if let url = self.url, InternalURL(url)?.isAboutHomeURL ?? false, sessionData == nil, !restoring {
return Strings.AppMenuOpenHomePageTitleString
}
//lets double check the sessionData in case this is a non-restored new tab
if let firstURL = sessionData?.urls.first, sessionData?.urls.count == 1, InternalURL(firstURL)?.isAboutHomeURL ?? false {
return Strings.AppMenuOpenHomePageTitleString
}
if let url = self.url, !InternalURL.isValid(url: url), let shownUrl = url.displayURL?.absoluteString {
return shownUrl
}
guard let lastTitle = lastTitle, !lastTitle.isEmpty else {
return self.url?.displayURL?.absoluteString ?? ""
}
return lastTitle
}
var displayFavicon: Favicon? {
return favicons.max { $0.width! < $1.width! }
}
var canGoBack: Bool {
return webView?.canGoBack ?? false
}
var canGoForward: Bool {
return webView?.canGoForward ?? false
}
func goBack() {
_ = webView?.goBack()
}
func goForward() {
_ = webView?.goForward()
}
func goToBackForwardListItem(_ item: WKBackForwardListItem) {
_ = webView?.go(to: item)
}
@discardableResult func loadRequest(_ request: URLRequest) -> WKNavigation? {
if let webView = webView {
// Convert about:reader?url=http://example.com URLs to local ReaderMode URLs
if let url = request.url, let syncedReaderModeURL = url.decodeReaderModeURL, let localReaderModeURL = syncedReaderModeURL.encodeReaderModeURL(WebServer.sharedInstance.baseReaderModeURL()) {
let readerModeRequest = PrivilegedRequest(url: localReaderModeURL) as URLRequest
lastRequest = readerModeRequest
return webView.load(readerModeRequest)
}
lastRequest = request
if let url = request.url, url.isFileURL, request.isPrivileged {
return webView.loadFileURL(url, allowingReadAccessTo: url)
}
return webView.load(request)
}
return nil
}
func stop() {
webView?.stopLoading()
}
func reload() {
// If the current page is an error page, and the reload button is tapped, load the original URL
if let url = webView?.url, let internalUrl = InternalURL(url), let page = internalUrl.originalURLFromErrorPage {
webView?.replaceLocation(with: page)
return
}
if let _ = webView?.reloadFromOrigin() {
print("reloaded zombified tab from origin")
return
}
if let webView = self.webView {
print("restoring webView from scratch")
restore(webView)
}
}
func addContentScript(_ helper: TabContentScript, name: String) {
contentScriptManager.addContentScript(helper, name: name, forTab: self)
}
func getContentScript(name: String) -> TabContentScript? {
return contentScriptManager.getContentScript(name)
}
func hideContent(_ animated: Bool = false) {
webView?.isUserInteractionEnabled = false
if animated {
UIView.animate(withDuration: 0.25, animations: { () -> Void in
self.webView?.alpha = 0.0
})
} else {
webView?.alpha = 0.0
}
}
func showContent(_ animated: Bool = false) {
webView?.isUserInteractionEnabled = true
if animated {
UIView.animate(withDuration: 0.25, animations: { () -> Void in
self.webView?.alpha = 1.0
})
} else {
webView?.alpha = 1.0
}
}
func addSnackbar(_ bar: SnackBar) {
if bars.count > 2 { return } // maximum 3 snackbars allowed on a tab
bars.append(bar)
tabDelegate?.tab(self, didAddSnackbar: bar)
}
func removeSnackbar(_ bar: SnackBar) {
if let index = bars.firstIndex(of: bar) {
bars.remove(at: index)
tabDelegate?.tab(self, didRemoveSnackbar: bar)
}
}
func removeAllSnackbars() {
// Enumerate backwards here because we'll remove items from the list as we go.
bars.reversed().forEach { removeSnackbar($0) }
}
func expireSnackbars() {
// Enumerate backwards here because we may remove items from the list as we go.
bars.reversed().filter({ !$0.shouldPersist(self) }).forEach({ removeSnackbar($0) })
}
func expireSnackbars(withClass snackbarClass: String) {
bars.reversed().filter({ $0.snackbarClassIdentifier == snackbarClass }).forEach({ removeSnackbar($0) })
}
func setScreenshot(_ screenshot: UIImage?, revUUID: Bool = true) {
self.screenshot = screenshot
if revUUID {
self.screenshotUUID = UUID()
}
}
func toggleChangeUserAgent() {
changedUserAgent = !changedUserAgent
reload()
TabEvent.post(.didToggleDesktopMode, for: self)
}
func queueJavascriptAlertPrompt(_ alert: JSAlertInfo) {
alertQueue.append(alert)
}
func dequeueJavascriptAlertPrompt() -> JSAlertInfo? {
guard !alertQueue.isEmpty else {
return nil
}
return alertQueue.removeFirst()
}
func cancelQueuedAlerts() {
alertQueue.forEach { alert in
alert.cancel()
}
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
guard let webView = object as? WKWebView, webView == self.webView,
let path = keyPath, path == KVOConstants.URL.rawValue else {
return assertionFailure("Unhandled KVO key: \(keyPath ?? "nil")")
}
guard let url = self.webView?.url else {
return
}
self.urlDidChangeDelegate?.tab(self, urlDidChangeTo: url)
}
func isDescendentOf(_ ancestor: Tab) -> Bool {
return sequence(first: parent) { $0?.parent }.contains { $0 == ancestor }
}
func injectUserScriptWith(fileName: String, type: String = "js", injectionTime: WKUserScriptInjectionTime = .atDocumentEnd, mainFrameOnly: Bool = true) {
guard let webView = self.webView else {
return
}
if let path = Bundle.main.path(forResource: fileName, ofType: type),
let source = try? String(contentsOfFile: path) {
let userScript = WKUserScript(source: source, injectionTime: injectionTime, forMainFrameOnly: mainFrameOnly)
webView.configuration.userContentController.addUserScript(userScript)
}
}
func observeURLChanges(delegate: URLChangeDelegate) {
self.urlDidChangeDelegate = delegate
}
func removeURLChangeObserver(delegate: URLChangeDelegate) {
if let existing = self.urlDidChangeDelegate, existing === delegate {
self.urlDidChangeDelegate = nil
}
}
func applyTheme() {
UITextField.appearance().keyboardAppearance = isPrivate ? .dark : (ThemeManager.instance.currentName == .dark ? .dark : .light)
}
}
extension Tab: TabWebViewDelegate {
fileprivate func tabWebView(_ tabWebView: TabWebView, didSelectFindInPageForSelection selection: String) {
tabDelegate?.tab(self, didSelectFindInPageForSelection: selection)
}
fileprivate func tabWebViewSearchWithFirefox(_ tabWebViewSearchWithFirefox: TabWebView, didSelectSearchWithFirefoxForSelection selection: String) {
tabDelegate?.tab(self, didSelectSearchWithFirefoxForSelection: selection)
}
}
extension Tab: ContentBlockerTab {
func currentURL() -> URL? {
return url
}
func currentWebView() -> WKWebView? {
return webView
}
func imageContentBlockingEnabled() -> Bool {
return noImageMode
}
}
private class TabContentScriptManager: NSObject, WKScriptMessageHandler {
private var helpers = [String: TabContentScript]()
// Without calling this, the TabContentScriptManager will leak.
func uninstall(tab: Tab) {
helpers.forEach { helper in
if let name = helper.value.scriptMessageHandlerName() {
tab.webView?.configuration.userContentController.removeScriptMessageHandler(forName: name)
}
}
}
@objc func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
for helper in helpers.values {
if let scriptMessageHandlerName = helper.scriptMessageHandlerName(), scriptMessageHandlerName == message.name {
helper.userContentController(userContentController, didReceiveScriptMessage: message)
return
}
}
}
func addContentScript(_ helper: TabContentScript, name: String, forTab tab: Tab) {
if let _ = helpers[name] {
assertionFailure("Duplicate helper added: \(name)")
}
helpers[name] = helper
// If this helper handles script messages, then get the handler name and register it. The Browser
// receives all messages and then dispatches them to the right TabHelper.
if let scriptMessageHandlerName = helper.scriptMessageHandlerName() {
tab.webView?.configuration.userContentController.add(self, name: scriptMessageHandlerName)
}
}
func getContentScript(_ name: String) -> TabContentScript? {
return helpers[name]
}
}
private protocol TabWebViewDelegate: AnyObject {
func tabWebView(_ tabWebView: TabWebView, didSelectFindInPageForSelection selection: String)
func tabWebViewSearchWithFirefox(_ tabWebViewSearchWithFirefox: TabWebView, didSelectSearchWithFirefoxForSelection selection: String)
}
class TabWebView: WKWebView, MenuHelperInterface {
fileprivate weak var delegate: TabWebViewDelegate?
// Updates the `background-color` of the webview to match
// the theme if the webview is showing "about:blank" (nil).
func applyTheme() {
if url == nil {
let backgroundColor = ThemeManager.instance.current.browser.background.hexString
evaluateJavaScript("document.documentElement.style.backgroundColor = '\(backgroundColor)';")
}
window?.backgroundColor = UIColor.theme.browser.background
}
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
return super.canPerformAction(action, withSender: sender) || action == MenuHelper.SelectorFindInPage
}
@objc func menuHelperFindInPage() {
evaluateJavaScript("getSelection().toString()") { result, _ in
let selection = result as? String ?? ""
self.delegate?.tabWebView(self, didSelectFindInPageForSelection: selection)
}
}
@objc func menuHelperSearchWithFirefox() {
evaluateJavaScript("getSelection().toString()") { result, _ in
let selection = result as? String ?? ""
self.delegate?.tabWebViewSearchWithFirefox(self, didSelectSearchWithFirefoxForSelection: selection)
}
}
internal override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
// The find-in-page selection menu only appears if the webview is the first responder.
becomeFirstResponder()
return super.hitTest(point, with: event)
}
}
///
// Temporary fix for Bug 1390871 - NSInvalidArgumentException: -[WKContentView menuHelperFindInPage]: unrecognized selector
//
// This class only exists to contain the swizzledMenuHelperFindInPage. This class is actually never
// instantiated. It only serves as a placeholder for the method. When the method is called, self is
// actually pointing to a WKContentView. Which is not public, but that is fine, we only need to know
// that it is a UIView subclass to access its superview.
//
class TabWebViewMenuHelper: UIView {
@objc func swizzledMenuHelperFindInPage() {
if let tabWebView = superview?.superview as? TabWebView {
tabWebView.evaluateJavaScript("getSelection().toString()") { result, _ in
let selection = result as? String ?? ""
tabWebView.delegate?.tabWebView(tabWebView, didSelectFindInPageForSelection: selection)
}
}
}
}
| mpl-2.0 | 5e32962a46379e51fb8a09dfb26d82e8 | 34.859331 | 201 | 0.636618 | 5.257709 | false | false | false | false |
bananafish911/SmartReceiptsiOS | SmartReceipts/Exchange/OpenExchangeRates.swift | 3 | 2260 | //
// OpenExchangeRates.swift
// SmartReceipts
//
// Created by Jaanus Siim on 02/06/16.
// Copyright © 2016 Will Baumann. All rights reserved.
//
import Foundation
private let OpenEchangeRatesAPIHistorycalAddress = "https://openexchangerates.org/api/historical/"
class OpenExchangeRates {
static let sharedInstance = OpenExchangeRates()
fileprivate var rates = [String: [ExchangeRate]]()
func exchangeRate(_ base: String, target: String, onDate date: Date, forceRefresh: Bool, completion: @escaping (NSDecimalNumber?, NSError?) -> ()) {
let dayString = date.dayString()
let dayCurrencyKey = "\(dayString)-\(base)"
Logger.debug("Retrieve \(base) to \(target) on \(dayString)")
if !forceRefresh, let dayValues = rates[dayCurrencyKey], let rate = dayValues.filter({ $0.currency == target}).first {
Logger.debug("Have cache hit")
completion(rate.rate, nil)
return
} else if (forceRefresh) {
Logger.debug("Refresh forced")
}
Logger.debug("Perform remote fetch")
let requestURL = URL(string: "\(OpenEchangeRatesAPIHistorycalAddress)\(dayString).json?base=\(base)&app_id=\(OpenExchangeAppID)")!
Logger.debug("\(requestURL)")
let request = URLRequest(url: requestURL)
let task = URLSession.shared.dataTask(with: request, completionHandler: {
data, response, error in
Logger.debug("Request completed")
if let error = error {
completion(nil, error as NSError?)
return
}
guard var rates = ExchangeRate.loadFromData(data!) else {
completion(nil, nil)
return
}
if let rate = rates.filter({ $0.currency == target }).first {
completion(rate.rate, nil)
} else {
// add unsupported currency marker
rates.append(ExchangeRate(currency: target, rate: .minusOne()))
completion(.minusOne(), nil)
}
self.rates[dayCurrencyKey] = rates
})
task.resume()
}
}
| agpl-3.0 | aff2af293dd3c5457ce55166e661bf45 | 34.857143 | 152 | 0.571492 | 4.816631 | false | false | false | false |
sdhjl2000/swiftdialog | SwiftDialogExample/Constants.swift | 1 | 1520 | //
// Constants.swift
// OAuthSwift
//
// Created by Dongri Jin on 7/17/14.
// Copyright (c) 2014 Dongri Jin. All rights reserved.
//
import Foundation
let Twitter =
[
"consumerKey": "***",
"consumerSecret": "***"
]
let Salesforce =
[
"consumerKey": "***",
"consumerSecret": "***"
]
let Flickr =
[
"consumerKey": "***",
"consumerSecret": "***"
]
let Github =
[
"consumerKey": "ec7c4df7ec380b9b990c",
"consumerSecret": "625fd59c11453337ec3809f1a89faea00b90b7fc"
]
let Instagram =
[
"consumerKey": "***",
"consumerSecret": "***"
]
let Foursquare =
[
"consumerKey": "***",
"consumerSecret": "***"
]
let Fitbit =
[
"consumerKey": "***",
"consumerSecret": "***"
]
let Withings =
[
"consumerKey": "***",
"consumerSecret": "***"
]
let Linkedin =
[
"consumerKey": "***",
"consumerSecret": "***"
]
let Linkedin2 =
[
"consumerKey": "***",
"consumerSecret": "***"
]
let Dropbox =
[
"consumerKey": "***",
"consumerSecret": "***"
]
let Dribbble =
[
"consumerKey": "***",
"consumerSecret": "***"
]
let BitBucket =
[
"consumerKey": "***",
"consumerSecret": "***"
]
let GoogleDrive =
[
"consumerKey": "***",
"consumerSecret": "***"
]
let Smugmug =
[
"consumerKey": "***",
"consumerSecret": "***"
]
let Intuit =
[
"consumerKey": "***",
"consumerSecret": "***"
]
let Zaim =
[
"consumerKey": "***",
"consumerSecret": "***"
]
let Tumblr =
[
"consumerKey": "***",
"consumerSecret": "***"
]
| apache-2.0 | f87e3264a1268614a903a5a270455336 | 14.049505 | 64 | 0.530263 | 3.333333 | false | false | false | false |
danielsaidi/KeyboardKit | Sources/KeyboardKit/Keyboard/ObservableKeyboardContext.swift | 1 | 1369 | //
// ObservableKeyboardContext.swift
// KeyboardKit
//
// Created by Daniel Saidi on 2020-06-15.
// Copyright © 2021 Daniel Saidi. All rights reserved.
//
import UIKit
/**
This keyboard context is an `ObservableObject` and provides
observable properties.
*/
open class ObservableKeyboardContext: KeyboardContext, ObservableObject {
public init(
locale: Locale = .current,
device: UIDevice = .current,
controller: KeyboardInputViewController,
keyboardType: KeyboardType = .alphabetic(.lowercased)) {
self.locale = locale
self.device = device
self.keyboardType = keyboardType
self.sync(with: controller)
}
public let device: UIDevice
@Published public var keyboardType: KeyboardType
@Published public var deviceOrientation: UIInterfaceOrientation = .portrait
@Published public var hasDictationKey: Bool = false
@Published public var hasFullAccess: Bool = false
@Published public var locale: Locale
@Published public var needsInputModeSwitchKey: Bool = true
@Published public var primaryLanguage: String?
@Published public var textDocumentProxy: UITextDocumentProxy = PreviewTextDocumentProxy()
@Published public var textInputMode: UITextInputMode?
@Published public var traitCollection: UITraitCollection = UITraitCollection()
}
| mit | f2f4ee79e4230b5b83f49722df0e67f3 | 33.2 | 93 | 0.725146 | 5.142857 | false | false | false | false |
KosyanMedia/Aviasales-iOS-SDK | AviasalesSDKTemplate/Source/HotelsSource/Filters/FilterCellFactories/FilterCells/SelectionFilterCell.swift | 1 | 796 | import UIKit
class SelectionFilterCell: HLDividerCell {
@IBOutlet weak var customAccessoryView: UIImageView!
@IBOutlet weak var titleLeftConstraint: NSLayoutConstraint!
@IBOutlet var titleToAccessoryViewConstraint: NSLayoutConstraint?
var checkboxOnImage: UIImage? {
return UIImage(named:"filterCheckboxOn")
}
var checkboxOffImage: UIImage? {
return UIImage(named:"filterCheckboxOff")
}
var active: Bool = false {
didSet {
updateActiveState()
}
}
func updateActiveState() {
customAccessoryView.image = active ? checkboxOnImage : checkboxOffImage
}
func setup(_ item: FilterSelectionItem) {
active = item.active
titleLabel.text = item.title
item.cell = self
}
}
| mit | 35886e51702ffe5b9bedd156b6a82805 | 23.875 | 79 | 0.665829 | 5.006289 | false | false | false | false |
1457792186/JWSwift | 熊猫TV2/XMTV/Classes/Main/ViewModel/BaseVM.swift | 2 | 2218 | //
// BaseVM.swift
// XMTV
//
// Created by Mac on 2017/1/11.
// Copyright © 2017年 Mac. All rights reserved.
//
import UIKit
class BaseVM: NSObject {
// MARK: - items, total, type
lazy var anchorGroups: [AnchorGroup] = [AnchorGroup]()
func loadAnchorGroupData(isLiveData : Bool, URLString : String, parameters : [String : Any]? = nil, finishedCallback : @escaping () -> ()) {
NetworkTool.request(type: .GET, urlString: URLString, paramters: parameters) { (result) in
guard let dict = result as? [String : Any] else { return }
if isLiveData {
guard let dictionary = dict["data"] as? [String : Any] else { return }
self.anchorGroups.append(AnchorGroup(dict: dictionary))
} else {
guard let arr = dict["data"] as? [[String : Any]] else { return }
for dict in arr {
self.anchorGroups.append(AnchorGroup(dict: dict))
}
}
finishedCallback()
}
}
// MARK: - items, total
lazy var searchGroup: [SearchModel] = [SearchModel]()
func loadSearchData(URLString : String, parameters : [String : Any]? = nil, finishedCallback : @escaping () -> ()) {
NetworkTool.request(type: .GET, urlString: URLString, paramters: parameters) { (result) in
guard let dict = result as? [String : Any] else { return }
guard let dictionary = dict["data"] as? [String : Any] else { return }
self.searchGroup.append(SearchModel(dict: dictionary))
finishedCallback()
}
}
// MARK: - items, total
// lazy var searchGroup: [SearchModel] = [SearchModel]()
// func loadSearchData(URLString : String, parameters : [String : Any]? = nil, finishedCallback : @escaping () -> ()) {
// NetworkTool.request(type: .GET, urlString: URLString, paramters: parameters) { (result) in
// guard let dict = result as? [String : Any] else { return }
// guard let dictionary = dict["data"] as? [String : Any] else { return }
// self.searchGroup.append(SearchModel(dict: dictionary))
// finishedCallback()
// }
// }
}
| apache-2.0 | d3b90d5ec151a55a17c2e53e9ad92bc3 | 42.431373 | 144 | 0.581038 | 4.179245 | false | false | false | false |
iCrany/iOSExample | iOSExample/Module/TextKitExample/View/ClickableLabel.swift | 1 | 4231 | //
// ClickableLabel.swift
// iOSExample
//
// Created by iCrany on 2017/6/26.
// Copyright (c) 2017 iCrany. All rights reserved.
//
import Foundation
import UIKit
class ClickableLabel: UILabel {
let layoutManager: NSLayoutManager = NSLayoutManager()
let textContainer: NSTextContainer = NSTextContainer(size: CGSize.zero)
var textStorage: NSTextStorage = NSTextStorage() {
didSet {
NSLog("textStorage: \(textStorage) \n layoutManager: \(self.layoutManager)")
textStorage.addLayoutManager(layoutManager)
}
}
var onClick: ((UILabel, Int) -> Void)?
var onClickLiftCycle: ((UILabel, UIEvent?) -> Void)?
open override var attributedText: NSAttributedString? {
didSet {
if let attributedTextTemp = attributedText {
self.textStorage = NSTextStorage.init(attributedString: attributedTextTemp)
} else {
self.textStorage = NSTextStorage.init()
}
}
}
open override var lineBreakMode: NSLineBreakMode {
didSet {
self.textContainer.lineBreakMode = lineBreakMode
}
}
open override var numberOfLines: Int {
didSet {
self.textContainer.maximumNumberOfLines = numberOfLines
}
}
// MARK: Init method
override init(frame: CGRect) {
super.init(frame: frame)
self.setup()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Override method
open override func layoutSubviews() {
super.layoutSubviews()
self.textContainer.size = self.bounds.size
}
open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
NSLog("touchesBegin event: \(String(describing: event))")
self.onClickLiftCycle?(self, event)
}
open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
NSLog("touchesEnded event: \(String(describing: event))")
self.onClickLiftCycle?(self, event)
}
open override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesCancelled(touches, with: event)
self.onClickLiftCycle?(self, event)
}
// MARK: Private method
private func setup() {
self.isUserInteractionEnabled = true
self.layoutManager.addTextContainer(self.textContainer)
self.textContainer.lineFragmentPadding = 0//TODO: What this mean?
self.textContainer.lineBreakMode = self.lineBreakMode
self.textContainer.maximumNumberOfLines = self.numberOfLines
let tapGesture: UITapGestureRecognizer = UITapGestureRecognizer.init()
tapGesture.addTarget(self, action: #selector(didTapAction(sender:)))
self.addGestureRecognizer(tapGesture)
}
// MARK: Event Response
@objc func didTapAction(sender: UITapGestureRecognizer) {
guard sender.view != nil else {
return
}
let locationOfTouchInLabel: CGPoint = sender.location(in: sender.view!)
let labelSize: CGSize = sender.view!.bounds.size
let textBoundingBox: CGRect = self.layoutManager.usedRect(for: self.textContainer)
let textContainerOffset: CGPoint = CGPoint.init(x: (labelSize.width - textBoundingBox.size.width) * 0.5 - textBoundingBox.origin.x,
y: (labelSize.height - textBoundingBox.size.height) * 0.5 - textBoundingBox.origin.y)
NSLog("locationOfTouchInLabel: \(locationOfTouchInLabel)")
NSLog("labelSize: \(labelSize)")
NSLog("textBoundingBox: \(textBoundingBox)")
NSLog("textContainerOffset: \(textContainerOffset)")
let locationOfTouchInTextContainer: CGPoint = CGPoint.init(x: locationOfTouchInLabel.x - textContainerOffset.x, y: locationOfTouchInLabel.y - textContainerOffset.y)
let indexOfCharacter: Int = self.layoutManager.characterIndex(for: locationOfTouchInTextContainer, in: self.textContainer, fractionOfDistanceBetweenInsertionPoints: nil)
self.onClick?(self, indexOfCharacter)
}
}
| mit | dad5b7fd80f2f80b0f04f757ed64bedf | 35.162393 | 177 | 0.671236 | 4.954333 | false | false | false | false |
mitochrome/complex-gestures-demo | apps/GestureRecognizer/Carthage/Checkouts/swift-protobuf/Sources/protoc-gen-swift/Descriptor+Extensions.swift | 3 | 9563 | // Sources/protoc-gen-swift/Descriptor+Extensions.swift - Additions to Descriptors
//
// Copyright (c) 2014 - 2017 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
import PluginLibrary
extension FileDescriptor {
/// True if this file should perserve unknown enums within the enum.
var hasUnknownEnumPreservingSemantics: Bool {
return syntax == .proto3
}
/// True of primative field types should have field presence.
var hasPrimativeFieldPresence: Bool {
return syntax == .proto2
}
var isBundledProto: Bool {
return SwiftProtobufInfo.isBundledProto(file: proto)
}
}
extension Descriptor {
/// Returns True if this is the Any WKT
var isAnyMessage: Bool {
return (file.syntax == .proto3 &&
fullName == ".google.protobuf.Any" &&
file.name == "google/protobuf/any.proto")
}
/// Returns True if this message recurisvely contains a required field.
/// This is a helper for generating isInitialized methods.
///
/// The logic for this check comes from google/protobuf; the C++ and Java
/// generators specificly.
func hasRequiredFields() -> Bool {
var alreadySeen = Set<String>()
func hasRequiredFieldsInner(_ descriptor: Descriptor) -> Bool {
if alreadySeen.contains(descriptor.fullName) {
// First required thing found causes this to return true, so one can
// assume if it is already visited, it didn't have required fields.
return false
}
alreadySeen.insert(descriptor.fullName)
// If it can support extensions, then return true as the extension could
// have a required field.
if !descriptor.extensionRanges.isEmpty {
return true
}
for f in descriptor.fields {
if f.label == .required {
return true
}
switch f.type {
case .group, .message:
if hasRequiredFieldsInner(f.messageType) {
return true
}
default:
break
}
}
return false
}
return hasRequiredFieldsInner(self)
}
/// A `String` containing a comma-delimited list of Swift range expressions
/// covering the extension ranges for this message.
///
/// This expression list is suitable as a pattern match in a `case`
/// statement. For example, `"case 5..<10, 20..<30:"`.
var swiftExtensionRangeExpressions: String {
return extensionRanges.lazy.map {
$0.swiftRangeExpression
}.joined(separator: ", ")
}
/// A `String` containing a Swift Boolean expression that tests if the given
/// variable is in any of the extension ranges for this message.
///
/// - Parameter variable: The name of the variable to test in the expression.
/// - Returns: A `String` containing the Boolean expression.
func swiftExtensionRangeBooleanExpression(variable: String) -> String {
return extensionRanges.lazy.map {
"(\($0.swiftBooleanExpression(variable: variable)))"
}.joined(separator: " || ")
}
}
extension FieldDescriptor {
/// True if this field should have presence support
var hasFieldPresence: Bool {
if label == .repeated { // Covers both Arrays and Maps
return false
}
if oneofIndex != nil {
// When in a oneof, no presence is provided.
return false
}
switch type {
case .group, .message:
// Groups/messages always get field presence.
return true
default:
// Depends on the context the message was declared in.
return file.hasPrimativeFieldPresence
}
}
func swiftType(namer: SwiftProtobufNamer) -> String {
if isMap {
let mapDescriptor: Descriptor = messageType
let keyField = mapDescriptor.fields[0]
let keyType = keyField.swiftType(namer: namer)
let valueField = mapDescriptor.fields[1]
let valueType = valueField.swiftType(namer: namer)
return "Dictionary<" + keyType + "," + valueType + ">"
}
let result: String
switch type {
case .double: result = "Double"
case .float: result = "Float"
case .int64: result = "Int64"
case .uint64: result = "UInt64"
case .int32: result = "Int32"
case .fixed64: result = "UInt64"
case .fixed32: result = "UInt32"
case .bool: result = "Bool"
case .string: result = "String"
case .group: result = namer.fullName(message: messageType)
case .message: result = namer.fullName(message: messageType)
case .bytes: result = "Data"
case .uint32: result = "UInt32"
case .enum: result = namer.fullName(enum: enumType)
case .sfixed32: result = "Int32"
case .sfixed64: result = "Int64"
case .sint32: result = "Int32"
case .sint64: result = "Int64"
}
if label == .repeated {
return "[\(result)]"
}
return result
}
func swiftStorageType(namer: SwiftProtobufNamer) -> String {
let swiftType = self.swiftType(namer: namer)
switch label {
case .repeated:
return swiftType
case .optional, .required:
if hasFieldPresence {
return "\(swiftType)?"
} else {
return swiftType
}
}
}
var protoGenericType: String {
precondition(!isMap)
switch type {
case .double: return "Double"
case .float: return "Float"
case .int64: return "Int64"
case .uint64: return "UInt64"
case .int32: return "Int32"
case .fixed64: return "Fixed64"
case .fixed32: return "Fixed32"
case .bool: return "Bool"
case .string: return "String"
case .group: return "Group"
case .message: return "Message"
case .bytes: return "Bytes"
case .uint32: return "UInt32"
case .enum: return "Enum"
case .sfixed32: return "SFixed32"
case .sfixed64: return "SFixed64"
case .sint32: return "SInt32"
case .sint64: return "SInt64"
}
}
func swiftDefaultValue(namer: SwiftProtobufNamer) -> String {
if isMap {
return "[:]"
}
if label == .repeated {
return "[]"
}
if let defaultValue = explicitDefaultValue {
switch type {
case .double:
switch defaultValue {
case "inf": return "Double.infinity"
case "-inf": return "-Double.infinity"
case "nan": return "Double.nan"
default: return defaultValue
}
case .float:
switch defaultValue {
case "inf": return "Float.infinity"
case "-inf": return "-Float.infinity"
case "nan": return "Float.nan"
default: return defaultValue
}
case .string:
return stringToEscapedStringLiteral(defaultValue)
case .bytes:
return escapedToDataLiteral(defaultValue)
case .enum:
let enumValue = enumType.value(named: defaultValue)!
return namer.dottedRelativeName(enumValue: enumValue)
default:
return defaultValue
}
}
switch type {
case .bool: return "false"
case .string: return "String()"
case .bytes: return "SwiftProtobuf.Internal.emptyData"
case .group, .message:
return namer.fullName(message: messageType) + "()"
case .enum:
return namer.dottedRelativeName(enumValue: enumType.defaultValue)
default:
return "0"
}
}
/// Calculates the traits type used for maps and extensions, they
/// are used in decoding and visiting.
func traitsType(namer: SwiftProtobufNamer) -> String {
if isMap {
let mapDescriptor: Descriptor = messageType
let keyField = mapDescriptor.fields[0]
let keyTraits = keyField.traitsType(namer: namer)
let valueField = mapDescriptor.fields[1]
let valueTraits = valueField.traitsType(namer: namer)
switch valueField.type {
case .message: // Map's can't have a group as the value
return "SwiftProtobuf._ProtobufMessageMap<\(keyTraits),\(valueTraits)>"
case .enum:
return "SwiftProtobuf._ProtobufEnumMap<\(keyTraits),\(valueTraits)>"
default:
return "SwiftProtobuf._ProtobufMap<\(keyTraits),\(valueTraits)>"
}
}
switch type {
case .double: return "SwiftProtobuf.ProtobufDouble"
case .float: return "SwiftProtobuf.ProtobufFloat"
case .int64: return "SwiftProtobuf.ProtobufInt64"
case .uint64: return "SwiftProtobuf.ProtobufUInt64"
case .int32: return "SwiftProtobuf.ProtobufInt32"
case .fixed64: return "SwiftProtobuf.ProtobufFixed64"
case .fixed32: return "SwiftProtobuf.ProtobufFixed32"
case .bool: return "SwiftProtobuf.ProtobufBool"
case .string: return "SwiftProtobuf.ProtobufString"
case .group, .message: return namer.fullName(message: messageType)
case .bytes: return "SwiftProtobuf.ProtobufBytes"
case .uint32: return "SwiftProtobuf.ProtobufUInt32"
case .enum: return namer.fullName(enum: enumType)
case .sfixed32: return "SwiftProtobuf.ProtobufSFixed32"
case .sfixed64: return "SwiftProtobuf.ProtobufSFixed64"
case .sint32: return "SwiftProtobuf.ProtobufSInt32"
case .sint64: return "SwiftProtobuf.ProtobufSInt64"
}
}
}
extension EnumDescriptor {
// True if this enum should perserve unknown enums within the enum.
var hasUnknownPreservingSemantics: Bool {
return file.hasUnknownEnumPreservingSemantics
}
func value(named: String) -> EnumValueDescriptor? {
for v in values {
if v.name == named {
return v
}
}
return nil
}
}
| mit | b4c5c523988664f2017ee5deae42fbb3 | 30.665563 | 82 | 0.652829 | 4.321283 | false | false | false | false |
cdmx/MiniMancera | miniMancera/View/HomeSplash/VHomeSplashCellOptionsButton.swift | 1 | 2272 | import UIKit
class VHomeSplashCellOptionsButton:UIButton
{
private weak var viewImage:UIImageView!
private weak var viewTitle:UILabel!
private let kTitleMargin:CGFloat = 30
private let kAlphaSelected:CGFloat = 0.3
private let kAlphaNotSelected:CGFloat = 1
init(
image:UIImage,
text:String,
alignment:NSTextAlignment)
{
super.init(frame:CGRect.zero)
clipsToBounds = true
backgroundColor = UIColor.clear
translatesAutoresizingMaskIntoConstraints = false
let viewImage:UIImageView = UIImageView()
viewImage.isUserInteractionEnabled = false
viewImage.translatesAutoresizingMaskIntoConstraints = false
viewImage.clipsToBounds = true
viewImage.contentMode = UIViewContentMode.center
viewImage.image = image
self.viewImage = viewImage
let viewTitle:UILabel = UILabel()
viewTitle.translatesAutoresizingMaskIntoConstraints = false
viewTitle.backgroundColor = UIColor.clear
viewTitle.isUserInteractionEnabled = false
viewTitle.textAlignment = alignment
viewTitle.font = UIFont.bold(size:16)
viewTitle.textColor = UIColor.white
viewTitle.text = text
self.viewTitle = viewTitle
addSubview(viewImage)
addSubview(viewTitle)
NSLayoutConstraint.equals(
view:viewImage,
toView:self)
NSLayoutConstraint.equalsVertical(
view:viewTitle,
toView:self)
NSLayoutConstraint.equalsHorizontal(
view:viewTitle,
toView:self,
margin:kTitleMargin)
hover()
}
required init?(coder:NSCoder)
{
return nil
}
override var isSelected:Bool
{
didSet
{
hover()
}
}
override var isHighlighted:Bool
{
didSet
{
hover()
}
}
//MARK: private
private func hover()
{
if isSelected || isHighlighted
{
viewImage.alpha = kAlphaSelected
}
else
{
viewImage.alpha = kAlphaNotSelected
}
}
}
| mit | 4b9e2e85a65551e421183cac0da77876 | 23.967033 | 67 | 0.591109 | 5.737374 | false | false | false | false |
Dewire/dehub-ios | Model/Services.swift | 2 | 561 | //
// Services.swift
// DeHub
//
// Created by Kalle Lindström on 12/06/16.
// Copyright © 2016 Dewire. All rights reserved.
//
import Foundation
public class Services {
public static let shared = { () -> Services in
let state = State()
let api = GistApi(resourceFactory: ResourceFactory(baseUrl: "https://api.github.com"), state: state)
return Services(api: api, state: state)
}()
public let api: GistApi
public let state: State
init(
api: GistApi,
state: State
) {
self.api = api
self.state = state
}
}
| mit | d150427d83ada975f9a808cf03779e4d | 18.275862 | 104 | 0.63864 | 3.49375 | false | false | false | false |
sunshineclt/NKU-Helper | NKU Helper/Model和帮助类/Model/Course.swift | 1 | 6389 | //
// Course.swift
// NKU Helper
//
// Created by 陈乐天 on 15/9/18.
// Copyright © 2015年 陈乐天. All rights reserved.
//
import UIKit
import RealmSwift
/**
课程类
* * * * *
last modified:
- date: 2016.10.12
- author: 陈乐天
- since: Swift3.0
- version: 1.0
*/
class Course: Object {
// MARK:- Property
/// 主键
dynamic var key = 0
/// 选课序号
dynamic var ID = "未知"
/// 课程编号
dynamic var number = "未知"
/// 课程名称
dynamic var name = "未知"
/// 教师姓名
dynamic var teacherName = "未知"
/// 颜色
dynamic var color: Color?
/// 课时
let courseTimes = LinkingObjects(fromType: CourseTime.self, property: "forCourse")
/// 任务
let tasks = LinkingObjects(fromType: Task.self, property: "forCourse")
/// 设置主键
///
/// - returns: 主键
override static func primaryKey() -> String? {
return "key"
}
// MARK:- 实例方法
/// 创建一个课程对象
///
/// - parameter key: 主键
/// - parameter ID: 选课序号
/// - parameter number: 课程编号
/// - parameter name: 课程名称
/// - parameter teacherName: 教师姓名
///
/// - returns: 创建的课程对象
convenience init(key:Int, ID:String, number:String, name:String, teacherName:String) {
self.init()
self.key = key
self.ID = ID
self.number = number
self.name = name
self.teacherName = teacherName
}
/// 存储课程信息
///
/// - throws: StoragedDataError.realmError
func save() throws {
do {
let realm = try Realm()
try realm.write({
realm.add(self)
})
} catch {
throw StoragedDataError.realmError
}
}
// MARK:- 类方法
/// 增加一个课时
/// - important: 若这门课不存在则创建,若存在则加入到其课时中
/// - important: 课程和课时均已保存
///
/// - parameter key: 主键
/// - parameter ID: 选课序号
/// - parameter number: 课程编号
/// - parameter name: 课程名称
/// - parameter classroom: 教室
/// - parameter weekOddEven: 单双周
/// - parameter teacherName: 教师姓名
/// - parameter weekday: 周几
/// - parameter startSection: 开始的节数
/// - parameter sectionNumber: 持续的节数
/// - parameter startWeek: 开始的周数
/// - parameter endWeek: 结束的周数
///
/// - throws: StoragedDataError.realmError
///
/// - returns: 若这门课不存在则返回创建的Course实例,若存在则加入课时后返回nil
class func saveCourseTimeWith(key:Int, ID:String, number:String, name:String, classroom:String, weekOddEven:String, teacherName:String, weekday:Int, startSection:Int, sectionNumber:Int, startWeek:Int, endWeek:Int) throws {
do {
let realm = try Realm()
let existedCourses = realm.objects(Course.self).filter("ID == '\(ID)'")
if let existedCourse = existedCourses.first {
// 这门课存在,直接将课时加入
let courseTime = CourseTime(key: key, classroom: classroom, weekOddEven: weekOddEven, weekday: weekday, startSection: startSection, sectionNumber: sectionNumber, startWeek: startWeek, endWeek: endWeek, forCourse: existedCourse)
try courseTime.save()
} else {
// 这门课不存在,新建一门课
let course = Course(key: key, ID: ID, number: number, name: name, teacherName: teacherName)
try course.save()
let courseTime = CourseTime(key: key, classroom: classroom, weekOddEven: weekOddEven, weekday: weekday, startSection: startSection, sectionNumber: sectionNumber, startWeek: startWeek, endWeek: endWeek, forCourse: course)
try courseTime.save()
}
}
catch {
throw StoragedDataError.realmError
}
}
/// 获取一周中某一天的所有课时
/// - note: 按照加载顺序排列
///
/// - parameter weekday: 星期几(周日为0,周一为1)
///
/// - throws: StoragedDataError.realmError、StoragedDataError.noClassesInStorage
///
/// - returns: 那一天的所有课时
class func getCourseTimes(onWeekday weekday: Int) throws -> Results<CourseTime> {
guard CourseLoadedAgent.sharedInstance.isCourseLoaded else {
throw StoragedDataError.noCoursesInStorage
}
do {
let convertedWeekday = weekday == 0 ? 7 : weekday
let realm = try Realm()
return realm.objects(CourseTime.self).filter("weekday == \(convertedWeekday)").sorted(byProperty: "key")
} catch {
throw StoragedDataError.realmError
}
}
/// 获取所有课程
/// - note: 按照加载顺序排列
///
/// - throws: StoragedDataError.noClassesInStorage、StoragedDataError.realmError
///
/// - returns: 所有课程
class func getAllCourses() throws -> Results<Course> {
guard CourseLoadedAgent.sharedInstance.isCourseLoaded else {
throw StoragedDataError.noCoursesInStorage
}
do {
let realm = try Realm()
return realm.objects(Course.self).sorted(byProperty: "key")
} catch {
throw StoragedDataError.realmError
}
}
/// 删除所有课程信息
/// - important: 必须先删除课时信息,与课程相关的任务信息,再删除课程信息
///
/// - throws: StoragedDataError.realmError
class func deleteAllCourses() throws {
do {
let realm = try Realm()
let data = try getAllCourses()
try realm.write({
realm.delete(data)
})
CourseLoadedAgent.sharedInstance.signCourseToUnloaded()
} catch StoragedDataError.noCoursesInStorage {
CourseLoadedAgent.sharedInstance.signCourseToUnloaded()
} catch {
CourseLoadedAgent.sharedInstance.signCourseToUnloaded()
throw StoragedDataError.realmError
}
}
}
| gpl-3.0 | 57df108b90051b69c12eee2cbd0ed5ab | 29.652406 | 243 | 0.57746 | 3.928718 | false | false | false | false |
alblue/swift | test/SILGen/collection_subtype_upcast.swift | 1 | 1770 |
// RUN: %target-swift-emit-silgen -module-name collection_subtype_upcast -enable-sil-ownership -sdk %S/Inputs %s | %FileCheck %s
struct S { var x, y: Int }
// CHECK-LABEL: sil hidden @$s25collection_subtype_upcast06array_C00D0SayypGSayAA1SVG_tF :
// CHECK: bb0([[ARG:%.*]] : @guaranteed $Array<S>):
// CHECK: debug_value [[ARG]]
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: // function_ref
// CHECK: [[FN:%.*]] = function_ref @$ss15_arrayForceCastySayq_GSayxGr0_lF
// CHECK: [[RESULT:%.*]] = apply [[FN]]<S, Any>([[ARG_COPY]]) : $@convention(thin) <τ_0_0, τ_0_1> (@guaranteed Array<τ_0_0>) -> @owned Array<τ_0_1>
// CHECK: destroy_value [[ARG_COPY]]
// CHECK: return [[RESULT]]
func array_upcast(array: [S]) -> [Any] {
return array
}
extension S : Hashable {
var hashValue : Int {
return x + y
}
}
func ==(lhs: S, rhs: S) -> Bool {
return true
}
// FIXME: This entrypoint name should not be bridging-specific
// CHECK-LABEL: sil hidden @$s25collection_subtype_upcast05dict_C00D0SDyAA1SVypGSDyAESiG_tF :
// CHECK: bb0([[ARG:%.*]] : @guaranteed $Dictionary<S, Int>):
// CHECK: debug_value [[ARG]]
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: // function_ref
// CHECK: [[FN:%.*]] = function_ref @$ss17_dictionaryUpCastySDyq0_q1_GSDyxq_GSHRzSHR0_r2_lF
// CHECK: [[RESULT:%.*]] = apply [[FN]]<S, Int, S, Any>([[ARG_COPY]]) : $@convention(thin) <τ_0_0, τ_0_1, τ_0_2, τ_0_3 where τ_0_0 : Hashable, τ_0_2 : Hashable> (@guaranteed Dictionary<τ_0_0, τ_0_1>) -> @owned Dictionary<τ_0_2, τ_0_3>
// CHECK: destroy_value [[ARG_COPY]]
// CHECK: return [[RESULT]]
func dict_upcast(dict: [S: Int]) -> [S: Any] {
return dict
}
// It's not actually possible to test this for Sets independent of
// the bridging rules.
| apache-2.0 | 2d348f634f42bad8f16b6d0d22bc25bb | 39.837209 | 234 | 0.63041 | 2.814103 | false | false | false | false |
sersoft-gmbh/AutoLayout_Macoun16 | AutoLayoutTricks/UIStackView/BadViewController.swift | 1 | 2711 | //
// BadViewController.swift
// AutoLayoutTricks
//
// Created by Florian Friedrich on 27/06/16.
// Copyright © 2016 ser.soft GmbH. All rights reserved.
//
import UIKit
import FFUIKit
import FFFoundation
class BadViewController: UIViewController {
let stackView: UIStackView = {
let view = UIStackView()
view.enableAutoLayout()
view.axis = .vertical
view.spacing = 20
view.alignment = .center
view.distribution = .equalCentering
return view
}()
let topView: UIView = {
let view = UIView()
view.enableAutoLayout()
view.backgroundColor = .blue
view.layer.cornerRadius = 25
return view
}()
fileprivate(set) lazy var bottomView: UIButton = {
let button = UIButton(type: .system)
button.enableAutoLayout()
button.addTarget(self, action: #selector(BadViewController.toggleTopView(_:)), for: .touchUpInside)
button.setTitle("Mal da, mal weg", for: UIControlState())
return button
}()
fileprivate var topViewWidthConstraint: NSLayoutConstraint!
fileprivate var topViewHeightConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
view.addSubview(stackView)
topViewWidthConstraint = createTopViewWidthConstraint()
topViewHeightConstraint = createTopViewHeightConstraint()
let constraints = [
"H:|-(>=0)-[stackView]-(>=0)-|",
"V:|-(>=0)-[stackView]-(>=0)-|",
].constraints(with: ["stackView": stackView]) + [
stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
stackView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
topViewWidthConstraint,
topViewHeightConstraint
]
constraints.activate()
[topView, bottomView].forEach(stackView.addArrangedSubview)
}
func createTopViewWidthConstraint() -> NSLayoutConstraint {
return topView.widthAnchor.constraint(equalToConstant: 50)
}
func createTopViewHeightConstraint() -> NSLayoutConstraint {
return topView.heightAnchor.constraint(equalToConstant: 50)
}
@IBAction func toggleTopView(_ sender: AnyObject?) {
UIView.animate(withDuration: 0.3, animations: {
// Force layout cycle
self.topViewHeightConstraint.isActive.toggle()
// Adds a 0-Height constraint (created by UIStackView)
self.topView.isHidden.toggle()
})
}
}
| mit | b74ef4656ef00c07ab5b550becc76618 | 31.650602 | 107 | 0.626937 | 5.345168 | false | false | false | false |
seankim2/TodayWeather | ios/watch Extension/WatchTWeatherComplication.swift | 1 | 81070 | //
// WatchTWeatherComplication.swift
// watch Extension
//
// Created by KwangHo Kim on 2017. 10. 27..
//
import Foundation
import ClockKit
import WatchKit
class WatchTWeatherComplication: NSObject, CLKComplicationDataSource, CLLocationManagerDelegate {
var strCurImgName : String = "Sun"; // Current Weather status image
var strAddress : String = ""; // Address
var currentTemp : Float = 0; // Current Temperature
var strAirState : String = ""; // Air state or Huminity
var colorAirState : UIColor = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1)
var attrStrAirState : NSAttributedString = NSAttributedString();
var todayPop : Int = 0;
var todayMinTemp : Int = 0;
var todayMaxTemp : Int = 0;
var isTimeReloaded : Bool = false
var isWeatherRequested : Bool = false
// Location Infomation
var manager: CLLocationManager = CLLocationManager()
var curLatitude : Double = 0;
var curLongitude : Double = 0;
#if false
struct CityInfo {
var identifier : Any;
var strAddress : String;
var currentPosition : Bool;
var index : Int;
var weatherData : Dictionary<String, Any>;
var name : String;
var country : String;
var dictLocation : Dictionary<String, Any>;
init() {
identifier = "cityInfoID"
strAddress = "";
currentPosition = true;
index = 0;
weatherData = [:];
name = "name"
country = "KR"
dictLocation = [:];
}
}
#endif
//var currentCity : CityInfo? = nil;
var currentCity = CityInfo();
//var shuffledDaumKeys : NSMutableArray = [String]() as! NSMutableArray;
var shuffledDaumKeys : NSMutableArray = NSMutableArray();
//var nextDate: Date?
func getSupportedTimeTravelDirections(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTimeTravelDirections) -> Void) {
print("getSupportedTimeTravelDirections");
handler([])
}
func getTimelineStartDate(for complication: CLKComplication, withHandler handler: @escaping (Date?) -> Void) {
print("getTimelineStartDate");
handler(nil)
}
func getTimelineEndDate(for complication: CLKComplication, withHandler handler: @escaping (Date?) -> Void) {
print("getTimelineEndDate");
handler(nil)
}
func getPrivacyBehavior(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationPrivacyBehavior) -> Void) {
print("getPrivacyBehavior");
handler(.showOnLockScreen)
}
func getCurrentTimelineEntry(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTimelineEntry?) -> Void) {
print("getCurrentTimelineEntry")
var entry: CLKComplicationTimelineEntry?
//let timestamp = UserDefaults.standard.double(forKey: "timeStamp")
//let date = Date(timeIntervalSince1970: timestamp)
//nextDate = date
// Call the handler with the current timeline entry
switch complication . family {
case .modularSmall :
print("modularSmall")
let curImage = UIImage(named: "\(String(describing: strCurImgName))")
print("\(strCurImgName)")
#if false
let template = CLKComplicationTemplateModularSmallSimpleImage ()
if(curImage != nil) {
print("current Image is existed!!!")
template.imageProvider = CLKImageProvider(onePieceImage: curImage!)
}
#endif
let template = CLKComplicationTemplateModularSmallStackImage()
if(curImage != nil) {
print("current Image is existed!!!")
template.line1ImageProvider = CLKImageProvider(onePieceImage: curImage!)
}
print("country : \(currentCity.country)")
if( (currentCity.country == "KR" ) ||
(currentCity.country == "(null)" )
// (currentCity.country == nil)
) {
//template.line2TextProvider = CLKSimpleTextProvider(text: "\(currentTemp)˚ \(attrStrAirState)")
template.line2TextProvider = CLKSimpleTextProvider(text: "\(currentTemp)˚ \(strAirState)")
//template.tintColor = colorAirState;
} else {
template.line2TextProvider = CLKSimpleTextProvider(text: "\(currentTemp)˚")
}
handler ( CLKComplicationTimelineEntry ( date : Date (), complicationTemplate : template ))
case .modularLarge :
#if false
print("modularLarge")
let template = CLKComplicationTemplateModularLargeStandardBody()
print("\(String(describing: strAddress))")
template.headerTextProvider = CLKSimpleTextProvider(text: "\(todayPop)% \(String(describing: strAddress)) \(currentTemp)˚")
template.body1TextProvider = CLKSimpleTextProvider(text: "\(String(describing:strAirState))")
template.body2TextProvider = CLKSimpleTextProvider(text: "\(todayMinTemp)˚ / \(todayMaxTemp)˚")
let strUmbImgName : String = "Umbrella"; // Current Weather status image
let umbImage = UIImage(named: String(describing: strUmbImgName))
if(umbImage != nil ) {
template.headerImageProvider = CLKImageProvider(onePieceImage: umbImage!)
}
template.tintColor = colorAirState;
entry = CLKComplicationTimelineEntry(date: Date(), complicationTemplate: template)
handler(entry)
#endif
case .utilitarianSmall :
let curImage = UIImage(named: "\(String(describing: strCurImgName))")
let template = CLKComplicationTemplateUtilitarianSmallFlat()
if(curImage != nil) {
print("current Image is existed!!!")
template.imageProvider = CLKImageProvider(onePieceImage: curImage!)
}
if( (currentCity.country == "KR" ) ||
(currentCity.country == "(null)" )
// (currentCity.country == nil)
) {
//template.line2TextProvider = CLKSimpleTextProvider(text: "\(currentTemp)˚ \(attrStrAirState)")
template.textProvider = CLKSimpleTextProvider(text: "\(currentTemp)˚ \(strAirState)")
//template.tintColor = colorAirState;
} else {
template.textProvider = CLKSimpleTextProvider(text: "\(currentTemp)˚")
}
handler ( CLKComplicationTimelineEntry ( date : Date (), complicationTemplate : template ))
case .circularSmall :
let curImage = UIImage(named: "\(String(describing: strCurImgName))")
let template = CLKComplicationTemplateCircularSmallStackImage()
if(curImage != nil) {
print("current Image is existed!!!")
template.line1ImageProvider = CLKImageProvider(onePieceImage: curImage!)
}
if( (currentCity.country == "KR" ) ||
(currentCity.country == "(null)" )
// (currentCity.country == nil)
) {
//template.line2TextProvider = CLKSimpleTextProvider(text: "\(currentTemp)˚ \(attrStrAirState)")
template.line2TextProvider = CLKSimpleTextProvider(text: "\(currentTemp)˚ \(strAirState)")
//template.tintColor = colorAirState;
} else {
template.line2TextProvider = CLKSimpleTextProvider(text: "\(currentTemp)˚")
}
handler ( CLKComplicationTimelineEntry ( date : Date (), complicationTemplate : template ))
case .extraLarge :
let curImage = UIImage(named: "\(String(describing: strCurImgName))")
let template = CLKComplicationTemplateExtraLargeStackImage()
if(curImage != nil) {
print("current Image is existed!!!")
template.line1ImageProvider = CLKImageProvider(onePieceImage: curImage!)
}
if( (currentCity.country == "KR" ) ||
(currentCity.country == "(null)" )
// (currentCity.country == nil)
) {
//template.line2TextProvider = CLKSimpleTextProvider(text: "\(currentTemp)˚ \(attrStrAirState)")
template.line2TextProvider = CLKSimpleTextProvider(text: "\(currentTemp)˚ \(strAirState)")
//template.tintColor = colorAirState;
} else {
template.line2TextProvider = CLKSimpleTextProvider(text: "\(currentTemp)˚")
}
handler ( CLKComplicationTimelineEntry ( date : Date (), complicationTemplate : template ))
default :
print ( "Unknown complication type: \(complication.family) " )
handler ( nil )
}
}
func getCurrentHealth() -> Int {
// This would be used to retrieve current Chairman Cow health data
// for display on the watch. For testing, this always returns a
// constant.
return 4
}
func getNextRequestedUpdateDateWithHandler(handler: (NSDate?) -> Void) {
// Update hourly
handler(NSDate(timeIntervalSinceNow: 60*60))
print("getNextRequestedUpdateDateWithHandler");
}
func getPlaceholderTemplateForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationTemplate?) -> Void) {
print("getPlaceholderTemplateForComplication");
#if false
var template: CLKComplicationTemplate? = nil
switch complication.family {
case .modularSmall:
let modularTemplate = CLKComplicationTemplateCircularSmallRingText()
modularTemplate.textProvider = CLKSimpleTextProvider(text: "abc--")
modularTemplate.fillFraction = 1
modularTemplate.ringStyle = CLKComplicationRingStyle.closed
template = modularTemplate
print("modularSmall");
case .modularLarge:
let modularTemplate = CLKComplicationTemplateCircularSmallRingText()
modularTemplate.textProvider = CLKSimpleTextProvider(text: "def--")
modularTemplate.fillFraction = 1
modularTemplate.ringStyle = CLKComplicationRingStyle.closed
template = modularTemplate
print("modularLarge");
case .utilitarianSmall:
let modularTemplate = CLKComplicationTemplateCircularSmallRingText()
modularTemplate.textProvider = CLKSimpleTextProvider(text: "------")
modularTemplate.fillFraction = 1
modularTemplate.ringStyle = CLKComplicationRingStyle.closed
template = modularTemplate
print("utilitarianSmall");
case .utilitarianSmallFlat:
let modularTemplate = CLKComplicationTemplateCircularSmallRingText()
modularTemplate.textProvider = CLKSimpleTextProvider(text: "------")
modularTemplate.fillFraction = 1
modularTemplate.ringStyle = CLKComplicationRingStyle.closed
template = modularTemplate
print("utilitarianSmallFlat");
case .utilitarianLarge:
let modularTemplate = CLKComplicationTemplateCircularSmallRingText()
modularTemplate.textProvider = CLKSimpleTextProvider(text: "------")
modularTemplate.fillFraction = 1
modularTemplate.ringStyle = CLKComplicationRingStyle.closed
template = modularTemplate
print("utilitarianLarge");
case .circularSmall:
let modularTemplate = CLKComplicationTemplateCircularSmallRingText()
modularTemplate.textProvider = CLKSimpleTextProvider(text: "------")
modularTemplate.fillFraction = 1
modularTemplate.ringStyle = CLKComplicationRingStyle.closed
template = modularTemplate
print("circularSmall");
case .extraLarge:
let modularTemplate = CLKComplicationTemplateCircularSmallRingText()
modularTemplate.textProvider = CLKSimpleTextProvider(text: "------")
modularTemplate.fillFraction = 1
modularTemplate.ringStyle = CLKComplicationRingStyle.closed
template = modularTemplate
print("extraLarge");
}
handler(template)
#endif
handler(defaultTemplate())
}
func defaultTemplate() -> CLKComplicationTemplateModularLargeStandardBody {
let placeholder = CLKComplicationTemplateModularLargeStandardBody();
placeholder.headerTextProvider = CLKSimpleTextProvider(text: "Transit")
placeholder.body1TextProvider = CLKSimpleTextProvider(text: "Next bus in:")
placeholder.body2TextProvider = CLKSimpleTextProvider(text: "")
return placeholder
}
func getCurrentTimelineEntryForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationTimelineEntry?) -> Void) {
print("getCurrentTimelineEntryForComplication")
if complication.family == .modularSmall {
let template = CLKComplicationTemplateCircularSmallRingText()
template.textProvider = CLKSimpleTextProvider(text: "modularSmall")
template.fillFraction = Float(getCurrentHealth()) / 10.0
template.ringStyle = CLKComplicationRingStyle.closed
let timelineEntry = CLKComplicationTimelineEntry(date: NSDate() as Date, complicationTemplate: template)
handler(timelineEntry)
} else if complication.family == .modularLarge {
//CLKComplicationTemplateModularLargeStandardBody *t = [[CLKComplicationTemplateModularLargeStandardBody alloc] init];
//t.headerTextProvider = [CLKSimpleTextProvider textProviderWithText:data[@"Waxing gibbous"]];
//t.body1TextProvider = [CLKSimpleTextProvider textProviderWithText:data[@"Moonrise 5:27PM"]];
//t.body2TextProvider = [CLKTimeIntervalTextProvider textProviderWithStartDate:[NSDate date] endDate:[NSDate dateWithTimeIntervalSinceNow:((6*60*60)+(18*60))];
let template = CLKComplicationTemplateCircularSmallRingText()
template.textProvider = CLKSimpleTextProvider(text: "modularLarge")
template.fillFraction = Float(getCurrentHealth()) / 10.0
template.ringStyle = CLKComplicationRingStyle.closed
let timelineEntry = CLKComplicationTimelineEntry(date: NSDate() as Date, complicationTemplate: template)
handler(timelineEntry)
} else if complication.family == .utilitarianSmall {
let template = CLKComplicationTemplateCircularSmallRingText()
template.textProvider = CLKSimpleTextProvider(text: "utilitarianSmall")
template.fillFraction = Float(getCurrentHealth()) / 10.0
template.ringStyle = CLKComplicationRingStyle.closed
let timelineEntry = CLKComplicationTimelineEntry(date: NSDate() as Date, complicationTemplate: template)
handler(timelineEntry)
} else if complication.family == .utilitarianSmallFlat {
let template = CLKComplicationTemplateCircularSmallRingText()
template.textProvider = CLKSimpleTextProvider(text: "utilitarianSmallFlat")
template.fillFraction = Float(getCurrentHealth()) / 10.0
template.ringStyle = CLKComplicationRingStyle.closed
let timelineEntry = CLKComplicationTimelineEntry(date: NSDate() as Date, complicationTemplate: template)
handler(timelineEntry)
} else if complication.family == .utilitarianLarge {
let template = CLKComplicationTemplateCircularSmallRingText()
template.textProvider = CLKSimpleTextProvider(text: "utilitarianLarge")
template.fillFraction = Float(getCurrentHealth()) / 10.0
template.ringStyle = CLKComplicationRingStyle.closed
let timelineEntry = CLKComplicationTimelineEntry(date: NSDate() as Date, complicationTemplate: template)
handler(timelineEntry)
} else if complication.family == .circularSmall {
let template = CLKComplicationTemplateCircularSmallRingText()
//template.textProvider = CLKSimpleTextProvider(text: "\(getCurrentHealth())")
template.textProvider = CLKSimpleTextProvider(text: "circularSmall")
template.fillFraction = Float(getCurrentHealth()) / 10.0
template.ringStyle = CLKComplicationRingStyle.closed
let timelineEntry = CLKComplicationTimelineEntry(date: NSDate() as Date, complicationTemplate: template)
handler(timelineEntry)
} else if complication.family == .extraLarge {
let template = CLKComplicationTemplateCircularSmallRingText()
template.textProvider = CLKSimpleTextProvider(text: "extraLarge")
template.fillFraction = Float(getCurrentHealth()) / 10.0
template.ringStyle = CLKComplicationRingStyle.closed
let timelineEntry = CLKComplicationTimelineEntry(date: NSDate() as Date, complicationTemplate: template)
handler(timelineEntry)
} else {
handler(nil)
}
}
func getTimelineEntries(for complication: CLKComplication, before date: Date, limit: Int, withHandler handler: @escaping ([CLKComplicationTimelineEntry]?) -> Void) {
// Call the handler with the timeline entries prior to the given date
print("getTimelineEntries before");
handler(nil)
}
func getTimelineEntries(for complication: CLKComplication, after date: Date, limit: Int, withHandler handler: @escaping ([CLKComplicationTimelineEntry]?) -> Void) {
// Call the handler with the timeline entries after to the given date
print("getTimelineEntries after date : \(date) limit : \(limit)");
if( isTimeReloaded == false) {
let defaults = UserDefaults(suiteName: "group.net.wizardfactory.todayweather")
defaults?.synchronize()
if defaults == nil {
print("defaults is nuil!")
} else {
print(defaults!)
}
if let units = defaults?.string(forKey: "units") {
print(units)
watchTWUtil.setTemperatureUnit(strUnits: units);
}
if let daumKeys = defaults?.string(forKey: "daumServiceKeys") {
print(daumKeys)
watchTWUtil.setDaumServiceKeys(strDaumKeys: daumKeys);
}
// test - FIXME
var nextCity : CityInfo? = CityInfo();
print("nextCity : \(String(describing: nextCity))");
currentCity = CityInfo.loadCurrentCity();
#if false
nextCity?.currentPosition = true;
nextCity?.country = "KR";
print("nextCity : \(String(describing: nextCity))");
let archivedObject : NSData = NSKeyedArchiver.archivedData(withRootObject: nextCity!) as NSData;
print("archivedObject : \(String(describing: archivedObject))");
defaults?.set(archivedObject, forKey: "currentCity")
defaults?.synchronize();
if let archivedObject = defaults?.object(forKey: "currentCity") {
print("archivedObject : \(archivedObject)");
//currentCity = (CityInfo *)[NSKeyedUnarchiver unarchiveObjectWithData:archivedObject];
//currentCity = (NSKeyedUnarchiver.unarchiveObject(with: archivedObject as! Data) as? CityInfo)!;
currentCity = NSKeyedUnarchiver.unarchiveObject(with: (archivedObject as! Data)) as! WatchTWeatherComplication.CityInfo ;
if (currentCity == nil) {
print("UnarchiveObjectWithData is failed!!!")
}
else {
print("Current City : \(String(describing: currentCity))");
}
} else {
print("Current City is not existed!!!")
}
#endif
print("currentPosition : \(String(describing: currentCity.currentPosition))")
print("country : \(String(describing: currentCity.country))")
print("strAddress : \(String(describing: currentCity.strAddress))")
print("dictLocation : \(String(describing: currentCity.dictLocation))")
#if true
if (currentCity.currentPosition == true){
//manager.delegate = self
//manager.desiredAccuracy = kCLLocationAccuracyBest;
// Update if you move 200 meter
//manager.distanceFilter = 200;
//manager.allowsBackgroundLocationUpdates = true;
//manager.requestAlwaysAuthorization();
//manager.requestWhenInUseAuthorization
//manager.startUpdatingLocation();
//manager.requestLocation()
// Temporally use loaded data. after request location successfully, we will change
if( (currentCity.country == "KR" ) ||
(currentCity.country == "(null)" )
// (currentCity.country == nil)
)
{
print("strAddress : \(String(describing: currentCity.strAddress))")
processKRAddress((currentCity.strAddress)!);
}
else
{
//let keys = ["lat", "lng"];
//let values = [40.71, -74.00];
//let dict = NSDictionary.init(objects: values, forKeys: keys as [NSCopying])
processGlobalAddressForComplicaton(location: currentCity.dictLocation as NSDictionary?);
}
}
else
{
if( (currentCity.country == "KR" ) ||
(currentCity.country == "(null)" )
// (currentCity.country == nil)
)
{
print("strAddress : \(String(describing: currentCity.strAddress))")
processKRAddress((currentCity.strAddress)!);
}
else
{
//let keys = ["lat", "lng"];
//let values = [40.71, -74.00];
//let dict = NSDictionary.init(objects: values, forKeys: keys as [NSCopying])
processGlobalAddressForComplicaton(location: currentCity.dictLocation as NSDictionary?);
}
}
#endif
isTimeReloaded = true;
}
handler(nil)
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("error:: \(error.localizedDescription)")
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == .authorizedWhenInUse {
manager.requestLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
//NSDate* eventDate = newLocation.timestamp;
//NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
print("location:: \(locations)")
if locations.first != nil {
print("location:: \(locations)")
//if(fabs(howRecent) < 5.0)
//{
//[locationManager stopUpdatingLocation];
curLatitude = (locations.last?.coordinate.latitude)!;
curLongitude = (locations.last?.coordinate.longitude)!;
print("[locationManager] latitude : %f, longitude : %f", curLatitude, curLongitude)
getAddressFromGoogle(latitude: curLatitude, longitude: curLongitude);
//}
#if false
self.lat = String(format:"%.4f", (locations.last?.coordinate.latitude)!)
self.lon = String(format:"%.4f", (locations.last?.coordinate.longitude)!)
let geoCoder = CLGeocoder()
geoCoder.reverseGeocodeLocation(locations.last!, completionHandler: { (placemarks, error) -> Void in
guard let placeMark: CLPlacemark = placemarks?[0] else {
return
}
guard let state = placeMark.administrativeArea as String! else {
return
}
self.state = state
})
#endif
}
}
#if false
func requestedUpdateDidBegin(){
print("requestedUpdateDidBegin");
manager.delegate = self
manager.requestLocation()
let server=CLKComplicationServer.sharedInstance()
for comp in (server.activeComplications)! {
server.reloadTimeline(for: comp)
}
}
#endif
var backgroundUrlSession:URLSession?
var pendingBackgroundURLTask:WKURLSessionRefreshBackgroundTask?
func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) {
print("#### WKRefreshBackgroundTask ####")
manager.delegate = self
manager.requestLocation()
for task in backgroundTasks {
if let refreshTask = task as? WKApplicationRefreshBackgroundTask {
// this task is completed below, our app will then suspend while the download session runs
print("application task received, start URL session, WKApplicationRefreshBackgroundTask")
manager.delegate = self
manager.requestLocation()
}
else if let urlTask = task as? WKURLSessionRefreshBackgroundTask
{
print("application task received, start URL session, WKURLSessionRefreshBackgroundTask")
manager.delegate = self
manager.requestLocation()
} else {
print("else")
manager.delegate = self
manager.requestLocation()
}
}
}
func getAddressFromGoogle(latitude:Double, longitude: Double)
{
//40.7127837, -74.0059413 <- New York
#if false //GLOBAL_TEST
// FIXME - for emulator - delete me
//let lat : Double = 40.7127837;
//let longi : Double = -74.0059413;
// 오사카
//float lat = 34.678395;
//float longi = 135.4601303;
//
let lat : Double = 37.5665350;
let longi : Double = 126.9779690;
curLatitude = lat;
curLongitude = longi;
//https://maps.googleapis.com/maps/api/geocode/json?latlng=40.7127837,-74.0059413
let strURL : String = String(format:"%@%f,%f", watchTWReq.STR_GOOGLE_COORD2ADDR_URL, lat, longi);
#else
let strURL : String = String(format:"%s%f,%f", watchTWReq.STR_GOOGLE_COORD2ADDR_URL, latitude, longitude);
#endif
print("[getAddressFromGoogle]url : \(strURL)");
requestAsyncByURLSession(url:strURL, reqType:InterfaceController.TYPE_REQUEST.ADDR_GOOGLE);
}
func processKRAddress( _ address : String) {
let array = address.characters.split(separator: " ").map(String.init)
var addr1 : String? = nil;
var addr2 : String? = nil;
var addr3 : String? = nil;
var lastChar : String? = nil;
print("array.count => \(array.count)");
if(array.count == 0) {
print("address is empty!!!");
return
}
if (array.count == 2) {
addr1 = array[1]
}
else if (array.count == 5) {
addr1 = array[1];
addr2 = array[2] + array[3];
addr3 = array[4];
}
else if (array.count == 4) {
let index : Int = array[3].characters.count - 1;
addr1 = array[1];
lastChar = (array[3] as NSString).substring(from:index);
if ( lastChar == "구" ) {
addr2 = array[2] + array[3];
}
else {
addr2 = array[2];
addr3 = array[3];
}
}
else if ( array.count == 3) {
let index : Int = array[2].characters.count - 1;
addr1 = array[1];
lastChar = (array[2] as NSString).substring(from:index);
if ( lastChar == "읍" ) || ( lastChar == "면" ) || ( lastChar == "동" ) {
addr2 = array[1];
addr3 = array[2];
}
else {
addr2 = array[2];
}
}
dump(array);
print("[processKRAddress] => addr1:\(String(describing: addr1)), addr2:\(String(describing: addr2)), addr3:\(String(describing: addr3))");
let URL = watchTWReq.makeRequestURL(addr1:addr1!, addr2:addr2!, addr3:addr3!, country:"KR");
requestAsyncByURLSession(url:URL, reqType:InterfaceController.TYPE_REQUEST.WEATHER_KR);
//print("nssURL : %s", nssURL);
}
func processGlobalAddressForComplicaton(location : NSDictionary?) {
if let strURL : String = watchTWReq.makeGlobalRequestURL(locDict : location!) {
requestAsyncByURLSession(url:strURL, reqType:InterfaceController.TYPE_REQUEST.WEATHER_GLOBAL);
print("[processGlobalAddressForComplicaton] strURL : \(strURL)");
}
}
func requestAsyncByURLSession( url : String, reqType : InterfaceController.TYPE_REQUEST) {
print("url : \(url)");
let strURL : URL! = URL(string: url);
print("[requestAsyncByURLSession] url : \(strURL), request type : \(reqType)");
var request = URLRequest.init(url: strURL);
if( reqType == InterfaceController.TYPE_REQUEST.WEATHER_KR) {
request.setValue("ko-kr,ko;q=0.8,en-us;q=0.5,en;q=0.3", forHTTPHeaderField: "Accept-Language");
}
let task = URLSession.shared.dataTask(with: request, completionHandler: {(data, response, error) -> Void in
if let data = data {
// Do stuff with the data
//print("data : \(data)");
self.makeJSON( with : data, type : reqType);
} else {
print("Failed to fetch \(strURL) : \(String(describing: error))");
}
})
task.resume();
}
func requestAsyncByURLSessionForRetry( url : String, reqType : InterfaceController.TYPE_REQUEST, nsdData:NSDictionary) {
let strURL : URL! = URL(string: url);
print("[requestAsyncByURLSession] url : \(strURL), request type : \(reqType)");
var request = URLRequest.init(url: strURL);
if( reqType == InterfaceController.TYPE_REQUEST.WEATHER_KR) {
request.setValue("ko-kr,ko;q=0.8,en-us;q=0.5,en;q=0.3", forHTTPHeaderField: "Accept-Language");
}
let task = URLSession.shared.dataTask(with: request, completionHandler: {(data, response, error) -> Void in
if let data = data {
// Do stuff with the data
//print("data : \(data)");
let httpResponse :HTTPURLResponse = response as! HTTPURLResponse;
let code : Int = Int(httpResponse.statusCode);
if( (code == 401) || (code == 429) ) {
print("key is not authorized or keys is all used. retry!!! nsdData : \(nsdData)");
let lat = Double(nsdData["latitude"] as! String);
let long = Double(nsdData["longitude"] as! String);
let count = Int(nsdData["tryCount"] as! String);
self.getAddressFromDaum(latitude: lat!, longitude:long!, tryCount:count!);
} else {
self.makeJSON( with : data, type : reqType);
}
} else {
print("Failed to fetch \(strURL) : \(String(describing: error))");
}
})
task.resume();
}
func parseKRAddress(jsonDict : NSDictionary) {
var dict : NSDictionary? = nil;
var strFullName : String;
var strName : String;
var strName0 : String;
var strName1 : String;
var strName2 : String;
var strName3 : String;
var strURL : String? = nil;
dict = jsonDict.object(forKey:"error") as? NSDictionary;
print("error dict : \(String(describing: dict))");
if(dict != nil)
{
print("error message : %s", dict?.object(forKey:"message") as! String);
}
else
{
print("I am valid json data!!!");
strFullName = jsonDict.object(forKey:"fullName") as! String;
strName = jsonDict.object(forKey:"name") as! String;
strName0 = jsonDict.object(forKey:"name0") as! String;
strName1 = jsonDict.object(forKey:"name1") as! String;
strName2 = jsonDict.object(forKey:"name2") as! String;
strName3 = jsonDict.object(forKey:"name3") as! String;
var strName22 : String = strName2.replacingOccurrences(of: " ", with: "");
#if USE_DEBUG
print("nssFullName : %s", strFullName);
print("nssName : %s", strName);
print("nssName0 : %s", strName0);
print("nssName1 : %s", strName1);
print("nssName22 : %s", strName22);
print("nssName3 : %s", strName3);
#endif
strURL = watchTWReq.makeRequestURL(addr1:strName1, addr2:strName22, addr3:strName3, country:"KR");
requestAsyncByURLSession(url:strURL!, reqType:InterfaceController.TYPE_REQUEST.WEATHER_KR);
}
}
func parseGlobalGeocode(jsonDict : NSDictionary?) {
if(jsonDict == nil) {
print("[parseGlobalGeocode] jsonDict is nil!");
return;
}
let strStatus : String = jsonDict!.object(forKey:"status") as! String;
if(strStatus != "OK") {
print("strStatus[\(strStatus)] is not OK");
return;
}
//print("jsonDict : \(jsonDict)" );
if let arrResults : NSArray = jsonDict!.object(forKey:"results") as? NSArray{
print("[parseGlobalGeocode] arrResults is \(arrResults)");
if(arrResults.count <= 0) {
print("[parseGlobalGeocode] arrResults is 0 or less than 0!!!");
return;
}
let dictResults : NSDictionary = arrResults[0] as! NSDictionary;
//print("dictResults : \(dictResults)");
let dictGeometry : NSDictionary? = dictResults.object(forKey: "geometry") as? NSDictionary;
if(dictGeometry == nil) {
print("[parseGlobalGeocode] dictGeometry is nil!");
return;
}
//print("nsdGeometry : \(nsdGeometry)";
let dictLocation : NSDictionary? = dictGeometry?.object(forKey:"location") as? NSDictionary;
if(dictLocation == nil) {
print("[parseGlobalGeocode] nsdLocation is nil!");
return;
}
//[self updateCurLocation:nsdLocation];
print("dictLocation : \(String(describing: dictLocation))");
processGlobalAddressForComplicaton(location: dictLocation);
} else {
print("[parseGlobalGeocode] nsdResults is nil!");
return;
}
}
func makeJSON( with jsonData : Data, type reqType : InterfaceController.TYPE_REQUEST) {
do {
guard let parsedResult = try JSONSerialization.jsonObject(with: jsonData, options: .allowFragments) as? NSDictionary else {
return
}
//print("Parsed Result: \(parsedResult)")
if(reqType == InterfaceController.TYPE_REQUEST.ADDR_DAUM) {
parseKRAddress(jsonDict: (parsedResult as NSDictionary));
}
else if(reqType == InterfaceController.TYPE_REQUEST.ADDR_GOOGLE) {
parseGoogleAddress(jsonDict: (parsedResult as? Dictionary<String, AnyObject>)!);
}
else if(reqType == InterfaceController.TYPE_REQUEST.GEO_GOOGLE) {
parseGlobalGeocode(jsonDict: (parsedResult as NSDictionary));
}
else if(reqType == InterfaceController.TYPE_REQUEST.WEATHER_GLOBAL) {
print("reqType == WATCH_COMPLICATION_GLOBAL");
processWeatherResultsAboutCompGlobal(jsonDict: parsedResult as? Dictionary<String, AnyObject>)
if(isWeatherRequested == false) {
refreshComplications();
isWeatherRequested = true;
}
}
else if(reqType == InterfaceController.TYPE_REQUEST.WEATHER_KR) {
print("reqType == WEATHER_KR");
processWeatherResultsWithCompKR(jsonDict: parsedResult as? Dictionary<String, AnyObject>)
if(isWeatherRequested == false) {
refreshComplications();
isWeatherRequested = true;
}
}
} catch {
print("Error: \(error.localizedDescription)")
}
}
func parseGoogleAddress(jsonDict : Dictionary<String, Any>)
{
//print("\(jsonDict)");
let strStatus : String = jsonDict["status"] as! String;
if(strStatus != "OK") {
print("strStatus[\(strStatus)] is not OK");
return;
}
let arrResults : NSArray = jsonDict["results"] as! NSArray;
//print("\(arrResults)");
var arrSubLevel2Types : Array = ["political", "sublocality", "sublocality_level_2"];
var arrSubLevel1Types : Array = ["political", "sublocality", "sublocality_level_1"];
var arrLocalTypes : Array = ["locality", "political"];
let strCountryTypes : String = String(format:"country");
var strSubLevel2Name : String? = nil;
var strSubLevel1Name : String? = nil;
var strLocalName : String? = nil;
var strCountryName : String? = nil;
for i in 0 ..< arrResults.count {
let dictResult : NSDictionary? = arrResults[i] as? NSDictionary;
if(dictResult == nil) {
print("nsdResult is null!!!");
continue;
}
//print("\(i) \(String(describing: dictResult))");
let arrAddressComponents : NSArray = dictResult?.object(forKey:"address_components") as! NSArray;
for j in 0 ..< arrAddressComponents.count {
var strAddrCompType0 : String? = nil;
var strAddrCompType1 : String? = nil;
var strAddrCompType2 : String? = nil;
let dictAddressComponent : NSDictionary = arrAddressComponents[j] as! NSDictionary;
let arrAddrCompTypes : NSArray = dictAddressComponent.object(forKey:"types") as! NSArray;
for k in 0 ..< arrAddrCompTypes.count {
if(k == 0) {
strAddrCompType0 = arrAddrCompTypes[k] as? String;
}
if(k == 1) {
strAddrCompType1 = arrAddrCompTypes[k] as? String;
}
if(k == 2) {
strAddrCompType2 = arrAddrCompTypes[k] as? String;
}
}
if(strAddrCompType0 == nil) {
strAddrCompType0 = String(format:"emptyType");
}
if(strAddrCompType1 == nil) {
strAddrCompType1 = String(format:"emptyType");
}
if(strAddrCompType2 == nil) {
strAddrCompType2 = String(format:"emptyType");
}
if ( ( strAddrCompType0 == arrSubLevel2Types[0] )
&& ( strAddrCompType1 == arrSubLevel2Types[1] )
&& ( strAddrCompType2 == arrSubLevel2Types[2] ) ) {
strSubLevel2Name = dictAddressComponent.object(forKey: "short_name") as? String;
}
if ( (strAddrCompType0 == arrSubLevel1Types[0] )
&& ( strAddrCompType1 == arrSubLevel1Types[1] )
&& ( strAddrCompType2 == arrSubLevel1Types[2] ) ) {
strSubLevel1Name = dictAddressComponent.object(forKey: "short_name") as? String;
}
if ( (strAddrCompType0 == arrLocalTypes[0] )
&& ( strAddrCompType1 == arrLocalTypes[1] ) ) {
strLocalName = dictAddressComponent.object(forKey: "short_name") as? String;
}
if (strAddrCompType0 == strCountryTypes ) {
strCountryName = dictAddressComponent.object(forKey: "short_name") as? String;
}
if ((strSubLevel2Name != nil) && (strSubLevel1Name != nil)
&& (strLocalName != nil) && (strCountryName != nil) ) {
break;
}
}
if ((strSubLevel2Name != nil) && (strSubLevel1Name != nil)
&& (strLocalName != nil) && (strCountryName != nil) ) {
break;
}
}
var strName : String? = nil;
var strAddress : String = String(format:"");
print("strSubLevel2Name : \(String(describing: strSubLevel2Name))");
print("strSubLevel1Name : \(String(describing: strSubLevel1Name))");
print("strLocalName : \(String(describing: strLocalName))");
print("strCountryName : \(String(describing: strCountryName))");
//국내는 동단위까지 표기해야 함.
if (strCountryName == "KR") {
if (strSubLevel2Name != nil) {
//strAddress = String(format:"%s", strSubLevel2Name!);
//strName = String(format:"%s", strSubLevel2Name!);
strAddress = strSubLevel2Name!;
strName = strSubLevel2Name!;
}
}
print("[parseGlobalAddress] 1 strAddress : \(String(describing: strAddress))");
if (strSubLevel1Name != nil) {
//strAddress = String(format:"%s %s", strAddress, strSubLevel1Name!);
strAddress = strAddress + " " + strSubLevel1Name!;
if (strName == nil)
{
//strName = String(format:"%s", strSubLevel1Name!);
strName = strSubLevel1Name!;
}
}
print("[parseGlobalAddress] 2 strAddress : \(String(describing: strAddress))");
if (strLocalName != nil) {
//strAddress = String(format:"%s %s", strAddress, strLocalName!);
strAddress = strAddress + " " + strLocalName!;
if (strName == nil)
{
//strName = String(format:"%s", strLocalName!);
strName = strLocalName!;
}
}
print("[parseGlobalAddress] 3 strAddress : \(String(describing: strAddress))");
if (strCountryName != nil) {
//strAddress = String(format:"%s %s", strAddress, strCountryName!);
strAddress = strAddress + " " + strCountryName!;
if (strName == nil) {
//strName = String(format:"%s", strCountryName!);
strName = strCountryName!;
}
}
print("[parseGlobalAddress] 4 strAddress : \(String(describing: strAddress))");
if ( (strName == nil) || (strName == strCountryName) ) {
print("Fail to find location address");
}
//[self updateCurCityInfo:nssName address:nssAddress country:nssCountryName];
print("[parseGlobalAddress] curLatitude : \(curLatitude), curLongitude : \(curLongitude)");
if( strCountryName == "KR" ) {
getAddressFromDaum(latitude: curLatitude, longitude: curLongitude, tryCount: 0);
} else {
print("[parseGlobalAddress] Get locations by using name!!! strAddress : \(String(describing: strAddress))");
getGeocodeFromGoogle(strAddress: strAddress);
}
}
func getGeocodeFromGoogle(strAddress:String)
{
//https://maps.googleapis.com/maps/api/geocode/json?address=
#if false
//var set : CharacterSet = CharacterSet.urlHostAllowed();
let urlSet = CharacterSet.urlFragmentAllowed
.union(.urlHostAllowed)
.union(.urlPasswordAllowed)
.union(.urlQueryAllowed)
.union(.urlUserAllowed)
let urlAllowed = CharacterSet.urlFragmentAllowed
.union(.urlHostAllowed)
.union(.urlPasswordAllowed)
.union(.urlQueryAllowed)
.union(.urlUserAllowed)
#endif
//var strEncAddress : String = strAddress.stringpe [nssAddress stringByAddingPercentEncodingWithAllowedCharacters:set];
if let strEncAddress = strAddress.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) {
print(strEncAddress) // "http://www.mapquestapi.com/geocoding/v1/batch?key=YOUR_KEY_HERE&callback=renderBatch&location=Pottsville,PA&location=Red%20Lion&location=19036&location=1090%20N%20Charlotte%20St,%20Lancaster,%20PA"
//let strURL : String = String(format:"%s%s", watchTWReq.STR_GOOGLE_ADDR2COORD_URL, strEncAddress);
let strURL : String = watchTWReq.STR_GOOGLE_ADDR2COORD_URL + strEncAddress;
print("[getGeocodeFromGoogle] Address : \(strAddress)" );
print("[getGeocodeFromGoogle] EncAddress : \(strEncAddress)" );
print("[getGeocodeFromGoogle] url : \(strURL)" );
requestAsyncByURLSession(url:strURL, reqType:InterfaceController.TYPE_REQUEST.GEO_GOOGLE);
}
}
func getAddressFromDaum(latitude : Double, longitude : Double, tryCount : Int) {
//35.281741, 127.292345 <- 곡성군 에러
// FIXME - for emulator - delete me
//latitude = 35.281741;
//longitude = 127.292345;
var strDaumKey : String? = nil;
var nextTryCount : Int = 0;
#if false
if(tryCount == 0) {
let nsmaDaumKeys : NSMutableArray? = watchTWUtil.getDaumServiceKeys();
//if let nsmaDaumKeys : NSMutableArray = watchTWUtil.getDaumServiceKeys() {
let strFirstKey : String = nsmaDaumKeys!.object(at: 0) as! String
if( (nsmaDaumKeys?.count == 0) || (strFirstKey == "0") ) { // 0, 1(Default)로 들어올때 처리
print("[getAddressFromDaum] Keys of NSDefault is empty!!!");
strDaumKey = String(format:"%s", watchTWReq.DAUM_SERVICE_KEY);
} else {
//shuffledDaumKeys = [[NSMutableArray alloc] init];
shuffledDaumKeys = watchTWUtil.shuffleDatas(nsaDatas: nsmaDaumKeys!);
strDaumKey = String(format:"%s", shuffledDaumKeys[tryCount] as! CVarArg);
print("[getAddressFromDaum] shuffled first nssDaumKey : \(String(describing: strDaumKey))");
}
// } else {
// print("222");
// }
}
else
{
if(tryCount >= shuffledDaumKeys.count)
{
print("We are used all keys. you have to ask more keys!!!");
return;
}
strDaumKey = String(format:"%s", shuffledDaumKeys[tryCount] as! CVarArg);
print("[getAddressFromDaum] tryCount:\(tryCount) shuffled next nssDaumKey : \(String(describing: strDaumKey))");
}
#endif
strDaumKey = watchTWReq.DAUM_SERVICE_KEY;
nextTryCount = tryCount + 1;
// let strURL : String = String(format:"%s%s%s%s%f%s%f%s%s", watchTWReq.STR_DAUM_COORD2ADDR_URL, watchTWReq.STR_APIKEY, strDaumKey!, watchTWReq.STR_LONGITUDE, longitude, watchTWReq.STR_LATITUDE, latitude, watchTWReq.STR_INPUT_COORD, watchTWReq.STR_OUTPUT_JSON);
let strURL : String = watchTWReq.STR_DAUM_COORD2ADDR_URL + watchTWReq.STR_APIKEY + strDaumKey! + watchTWReq.STR_LONGITUDE + String(format:"%f",longitude) + watchTWReq.STR_LATITUDE + String(format:"%f",latitude) + watchTWReq.STR_INPUT_COORD + watchTWReq.STR_OUTPUT_JSON;
print("url : \(strURL)");
let dictRetryData : NSDictionary = [ Float(latitude): "latitude",
Float(longitude) : "longitude",
Int(nextTryCount) : "tryCount" ];
requestAsyncByURLSessionForRetry(url:strURL, reqType:InterfaceController.TYPE_REQUEST.ADDR_DAUM, nsdData: dictRetryData);
}
func getChangedColorAirStateForComp( strAirState : String) -> NSMutableAttributedString {
var String : NSMutableAttributedString = NSMutableAttributedString(string:strAirState);
var sRange : NSRange? = nil;
var stateColor : UIColor? = nil;
var font = UIFont.boldSystemFont(ofSize : 11.0);
let nssAirState = strAirState as NSString;
let strGood = NSLocalizedString("LOC_GOOD", comment:"좋음");
let strModerate = NSLocalizedString("LOC_MODERATE", comment:"보통");
let strSensitive = NSLocalizedString("LOC_UNHEALTHY_FOR_SENSITIVE_GROUPS", comment:"민감군주의");
let strUnhealthy = NSLocalizedString("LOC_UNHEALTHY", comment:"나쁨");
let strVeryUnhealty = NSLocalizedString("LOC_VERY_UNHEALTHY", comment:"매우나쁨");
let strHaz = NSLocalizedString("LOC_HAZARDOUS", comment:"위험");
#if false
if(watch.is42 == true) {
print("watch size is 42mm!!! ");
font = UIFont.boldSystemFont(ofSize : 13.0);
} else {
print("watch size is 32mm!!! ");
}
#endif
if(strAirState.hasSuffix(strGood))
{
sRange = nssAirState.range(of:strGood);
//NSMakeRange(firstBraceIndex.startIndex, firstClosingBraceIndex.endIndex)
stateColor = UIColor.init(argb:0xff32a1ff);
}
else if(strAirState.hasSuffix(strModerate))
{
sRange = nssAirState.range(of:strModerate); //원하는 텍스트라는 글자의 위치가져오기
stateColor = UIColor.init(argb:0xff7acf16);
}
else if(strAirState.hasSuffix(strSensitive))
{
sRange = nssAirState.range(of:strSensitive); //원하는 텍스트라는 글자의 위치가져오기
stateColor = UIColor.init(argb:0xfffd934c); // 나쁨과 동일
}
else if(strAirState.hasSuffix(strVeryUnhealty))
{
sRange = nssAirState.range(of:strVeryUnhealty); //원하는 텍스트라는 글자의 위치가져오기
stateColor = UIColor.init(argb:0xffff7070);
}
else if(strAirState.hasSuffix(strUnhealthy))
{
sRange = nssAirState.range(of:strUnhealthy); //원하는 텍스트라는 글자의 위치가져오기
stateColor = UIColor.init(argb:0xfffd934c);
}
else if(strAirState.hasSuffix(strHaz))
{
sRange = nssAirState.range(of:strHaz); //원하는 텍스트라는 글자의 위치가져오기
stateColor = UIColor.init(argb:0xffff7070); // 매우나쁨과 동일
}
else
{
//sRange = Foundation.NSNotFound;
stateColor = UIColor.black;
return String;
}
// chagnge "●"
String = NSMutableAttributedString(string:"●");
sRange = NSMakeRange(0, 0);
colorAirState = stateColor!;
String.addAttribute(NSAttributedStringKey.foregroundColor, value:stateColor!, range:sRange!); //attString의 Range위치에 있는 "Nice"의 글자의
String.addAttribute(NSAttributedStringKey.font, value:font, range:sRange!); //attString의 Range위치에 있는 "Nice"의 글자의
return String;
}
func getAirStateForComp( _ currentArpltnDict : Dictionary<String, Any> ) -> String {
let khaiGrade : Int32 = (currentArpltnDict["khaiGrade"] as AnyObject).int32Value // 통합대기
let pm10Grade : Int32 = (currentArpltnDict["pm10Grade"] as AnyObject).int32Value // 미세먼지
let pm25Grade : Int32 = (currentArpltnDict["pm25Grade"] as AnyObject).int32Value // 초미세먼지
let khaiValue : Int32 = (currentArpltnDict["khaiValue"] as AnyObject).int32Value // 통합대기
let pm10Value : Int32 = (currentArpltnDict["pm10Value"] as AnyObject).int32Value // 미세먼지
let pm25Value : Int32 = (currentArpltnDict["pm25Value"] as AnyObject).int32Value // 초미세먼지
let strKhaiStr : String = currentArpltnDict["khaiStr"] as! String // 통합대기
//let strPm10Str : String = currentArpltnDict["pm10Str"] as! String // 통합대기
//let strPm25Str : String = currentArpltnDict["pm25Str"] as! String // 통합대기
var strResults : String;
print("All air state is same!!! khaiGrade : \(khaiGrade), pm10Grade : \(pm10Grade), pm25Grade : \(pm25Grade)");
// Grade가 동일하면 통합대기 값을 전달, 동일할때 우선순위 통합대기 > 미세먼지 > 초미세먼지
if( (khaiGrade == pm10Grade) && (pm10Grade == pm25Grade) )
{
if( (khaiGrade == 0) && (pm10Grade == 0) && (pm25Grade == 0) )
{
print("All air state is zero !!!");
}
else
{
strResults = "\(khaiValue)";
return strResults;
}
}
else
{
if( (khaiGrade > pm10Grade) && (khaiGrade > pm25Grade) )
{
strResults = "\(khaiValue)";
return strResults;
}
else if ( (khaiGrade == pm10Grade) && (khaiGrade > pm25Grade) )
{
strResults = "\(khaiValue)";
return strResults;
}
else if ( (khaiGrade < pm10Grade) && (khaiGrade > pm25Grade) )
{
strResults = "\(pm10Value)㎍";
return strResults;
}
else if ( (khaiGrade > pm10Grade) && (khaiGrade == pm25Grade) )
{
strResults = "\(khaiValue)";
return strResults;
}
else if ( (khaiGrade < pm10Grade) && (khaiGrade == pm25Grade) )
{
strResults = "\(pm10Value)㎍";
return strResults;
}
else if ( (khaiGrade > pm10Grade) && (khaiGrade < pm25Grade) )
{
strResults = "\(pm25Value)㎍";
return strResults;
}
else if ( (khaiGrade == pm10Grade) && (khaiGrade < pm25Grade) )
{
strResults = "\(pm25Value)㎍";
return strResults;
}
else if ( (khaiGrade < pm10Grade) && (khaiGrade < pm25Grade) )
{
if ( pm10Grade > pm25Grade)
{
strResults = "\(pm10Value)㎍";
return strResults;
}
else if ( pm10Grade == pm25Grade)
{
strResults = "\(pm10Value)㎍";
return strResults;
}
else if ( pm10Grade < pm25Grade)
{
strResults = "\(pm25Value)㎍";
return strResults;
}
}
}
if( (strKhaiStr == "") || (strKhaiStr == "(null)") ) {
strResults = "";
} else {
strResults = "\(khaiValue)";
}
return strResults;
}
func processWeatherResultsWithCompKR( jsonDict : Dictionary<String, AnyObject>?) {
var todayDict : Dictionary<String, Any>;
// Date
var strDateTime : String!;
//var strTime : String? = nil;
// Image
//var strCurIcon : String? = nil;
var strCurImgName : String? = nil;
// Address
var strAddress : String? = nil;
// Pop
var numberTodPop : NSNumber;
var todayPop : Int = 0;
// current temperature
var numberT1h : NSNumber;
var numberTaMin : NSNumber;
var numberTaMax : NSNumber;
if(jsonDict == nil)
{
print("jsonDict is nil!!!");
return;
}
//print("processWeatherResultsWithShowMore : \(String(describing: jsonDict))");
//setCurJsonDict( dict : jsonDict! ) ;
// Address
if let strRegionName : String = jsonDict?["regionName"] as? String {
print("strRegionName is \(strRegionName).")
strAddress = strRegionName;
} else {
print("That strRegionName is not in the jsonDict dictionary.")
}
if let strCityName : String = jsonDict?["cityName"] as? String {
print("strCityName is \(strCityName).")
strAddress = strCityName;
} else {
print("That strCityName is not in the jsonDict dictionary.")
}
if let strTownName : String = jsonDict?["townName"] as? String {
print("strTownName is \(strTownName).")
strAddress = strTownName;
} else {
print("That strTownName is not in the jsonDict dictionary.")
}
// if address is current position... add this emoji
//목격자
//유니코드: U+1F441 U+200D U+1F5E8, UTF-8: F0 9F 91 81 E2 80 8D F0 9F 97 A8
print("strAddress \(String(describing: strAddress)))")
strAddress = NSString(format: "👁🗨%@˚", strAddress!) as String
let tempUnit : TEMP_UNIT? = watchTWUtil.getTemperatureUnit();
//#if KKH
// Current
if let currentDict : Dictionary<String, Any> = jsonDict?["current"] as? Dictionary<String, Any>{
//print("currentDict is \(currentDict).")
if let strCurIcon : String = currentDict["skyIcon"] as? String {
//strCurImgName = "weatherIcon2-color/\(strCurIcon).png";
strCurImgName = strCurIcon;
} else {
print("That strCurIcon is not in the jsonDict dictionary.")
}
if let strTime : String = currentDict["time"] as? String {
let index = strTime.index(strTime.startIndex, offsetBy: 2)
//let strHour = strTime.substring(to:index);
let strHour = strTime[..<index];
//let strMinute = strTime.substring(from:index);
let strMinute = strTime[index...];
strDateTime = NSLocalizedString("LOC_UPDATE", comment:"업데이트") + " " + strHour + ":" + strMinute;
print("strTime => \(strTime)")
print("strHour => \(strHour)")
print("strMinute => \(strMinute)")
} else {
print("That strTime is not in the jsonDict dictionary.")
strDateTime = "";
}
print("strDateTime => \(strDateTime)")
if let currentArpltnDict : Dictionary<String, Any> = currentDict["arpltn"] as? Dictionary<String, Any> {
strAirState = getAirStateForComp(currentArpltnDict);
//"LOC_GOOD" = "Good";
//"LOC_MODERATE" = "Moderate";
//"LOC_UNHEALTHY_FOR_SENSITIVE_GROUPS"= "Unhealthy for sensitive groups";
//"LOC_UNHEALTHY" = "Unhealthy";
//"LOC_VERY_UNHEALTHY" = "Very unhealthy";
//"LOC_HAZARDOUS" = "Hazardous";
// Test (Good, Moderate, Unhealthy for sensitive groups, Unhealthy, Very unhealthy, Hazardous)
//strAirState = "AQI 78 Hazardous";
attrStrAirState = getChangedColorAirStateForComp(strAirState:strAirState);
print("[processWeatherResultsWithCompKR] attrStrAirState : \(String(describing: attrStrAirState))");
print("[processWeatherResultsWithCompKR] strAirState : \(String(describing: strAirState))");
} else {
print("That currentArpltnDict is not in the jsonDict dictionary.")
}
if (currentDict["t1h"] != nil)
{
numberT1h = currentDict["t1h"] as! NSNumber;
currentTemp = Float(numberT1h.doubleValue);
if(tempUnit == TEMP_UNIT.FAHRENHEIT) {
currentTemp = Float(watchTWUtil.convertFromCelsToFahr(cels: currentTemp));
}
print("[processWeatherResultsWithCompKR] currentTemp : \(currentTemp)");
}
} else {
print("That currentDict is not in the jsonDict dictionary.")
}
//currentHum = [[currentDict valueForKey:@"reh"] intValue];
todayDict = watchTWUtil.getTodayDictionary(jsonDict: jsonDict!);
// Today
if (todayDict["taMin"] != nil) {
numberTaMin = todayDict["taMin"] as! NSNumber;
todayMinTemp = Int(numberTaMin.intValue);
} else {
print("That idTaMin is not in the todayDict dictionary.")
}
if(tempUnit == TEMP_UNIT.FAHRENHEIT)
{
todayMinTemp = Int( watchTWUtil.convertFromCelsToFahr(cels: Float(todayMinTemp) ) );
}
if (todayDict["taMax"] != nil) {
numberTaMax = todayDict["taMax"] as! NSNumber;
todayMaxTemp = Int(numberTaMax.intValue);
} else {
print("That numberTaMax is not in the todayDict dictionary.")
}
if(tempUnit == TEMP_UNIT.FAHRENHEIT)
{
todayMaxTemp = Int(watchTWUtil.convertFromCelsToFahr(cels: Float(todayMaxTemp) )) ;
}
if (todayDict["pop"] != nil) {
numberTodPop = todayDict["pop"] as! NSNumber;
todayPop = Int(numberTodPop.intValue);
} else {
print("That pop is not in the todayDict dictionary.")
}
print("todayMinTemp: \(todayMinTemp), todayMaxTemp:\(todayMaxTemp)");
print("todayPop: \(todayPop)");
#if false
DispatchQueue.global(qos: .background).async {
// Background Thread
DispatchQueue.main.async {
// Run UI Updates
if(strDateTime != nil) {
self.updateDateLabel.setText("\(strDateTime!)");
}
print("=======> date : \(strDateTime!)");
if( (strAddress == nil) || ( strAddress == "(null)" ))
{
self.addressLabel.setText("");
}
else
{
self.addressLabel.setText("\(strAddress!)");
}
print("=======> strCurImgName : \(strCurImgName!)");
if(strCurImgName != nil) {
self.curWeatherImage.setImage ( UIImage(named:strCurImgName!) );
}
if(tempUnit == TEMP_UNIT.FAHRENHEIT) {
self.curTempLabel.setText( NSString(format: "%d˚", currentTemp) as String );
} else {
self.curTempLabel.setText( NSString(format: "%.01f˚", currentTemp) as String);
}
print("[processWeatherResultsWithCompKR] attrStrAirState2 : \(String(describing: attrStrAirState))");
self.airAQILabel.setAttributedText( attrStrAirState );
self.minMaxLabel.setText(NSString(format: "%d˚/ %d˚", todayMinTemp, todayMaxTemp) as String );
self.precLabel.setText(NSString(format: "%d%%", todayPop) as String );
}
}
#endif
}
func processWeatherResultsAboutCompGlobal( jsonDict : Dictionary<String, AnyObject>?) {
var currentDict : Dictionary<String, Any>;
//var currentArpltnDict : Dictionary<String, Any>;
var todayDict : Dictionary<String, Any>? = nil;
// Date
var strDateTime : String!;
//var strTime : String? = nil;
// Temperature
var tempUnit : TEMP_UNIT? = TEMP_UNIT.CELSIUS;
// Dust
var attrStrAirState : NSAttributedString = NSAttributedString();
//NSMutableAttributedString *nsmasAirState = nil;
// Pop
var numberTodPop : NSNumber;
// Humid
var numberTodHumid : NSNumber;
var todayHumid = 0;
if(jsonDict == nil)
{
print("jsonDict is nil!!!");
return;
}
//print("processWeatherResultsWithShowMore : \(String(describing: jsonDict))");
//setCurJsonDict( dict : jsonDict! ) ;
// Address
//NSLog(@"mCurrentCityIdx : %d", mCurrentCityIdx);
//NSMutableDictionary* nsdCurCity = [mCityDictList objectAtIndex:mCurrentCityIdx];
//NSLog(@"[processWeatherResultsAboutGlobal] nsdCurCity : %@", nsdCurCity);
// Address
//nssAddress = [nsdCurCity objectForKey:@"name"];
//nssCountry = [nsdCurCity objectForKey:@"country"];
//if(nssCountry == nil)
//{
// nssCountry = @"KR";
//}
//NSLog(@"[Global]nssAddress : %@, nssCountry : %@", nssAddress, nssCountry);
// if address is current position... add this emoji
//목격자
//유니코드: U+1F441 U+200D U+1F5E8, UTF-8: F0 9F 91 81 E2 80 8D F0 9F 97 A8
//print("strAddress \(String(describing: strAddress)))")
//strAddress = NSString(format: "👁🗨%@˚", strAddress!) as String
strAddress = NSString(format: "뉴욕") as String;
// Current
if let thisTimeArr : NSArray = jsonDict?["thisTime"] as? NSArray {
if(thisTimeArr.count == 2) {
currentDict = thisTimeArr[1] as! Dictionary<String, Any>; // Use second index; That is current weahter.
} else {
currentDict = thisTimeArr[0] as! Dictionary<String, Any>; // process about thisTime
}
print("bbbb")
if let strCurIcon : String = currentDict["skyIcon"] as? String {
//strCurImgName = "weatherIcon2-color/\(strCurIcon).png";
print("ccccc")
strCurImgName = strCurIcon;
print("strCurImgName : \(strCurImgName)")
} else {
print("That strCurIcon is not in the jsonDict dictionary.")
}
print("ddddd")
tempUnit = watchTWUtil.getTemperatureUnit();
if let strTime : String = currentDict["date"] as? String {
let index = strTime.index(strTime.startIndex, offsetBy: 11)
let strHourMin = strTime[index...];
strDateTime = NSLocalizedString("LOC_UPDATE", comment:"업데이트") + " " + strHourMin;
print("strTime => \(strHourMin)")
todayDict = watchTWUtil.getTodayDictionaryInGlobal(jsonDict: jsonDict!, strTime:strTime);
if(todayDict != nil) {
if(tempUnit == TEMP_UNIT.FAHRENHEIT)
{
let idTaMin = todayDict!["tempMin_f"] as! NSNumber;
todayMinTemp = Int(truncating: idTaMin);
let idTaMax = todayDict!["tempMax_f"] as! NSNumber;
todayMaxTemp = Int(truncating: idTaMax);
}
else
{
let idTaMin = todayDict!["tempMin_c"] as! NSNumber;
todayMinTemp = Int(truncating: idTaMin);
let idTaMax = todayDict!["tempMax_c"] as! NSNumber;
todayMaxTemp = Int(truncating: idTaMax);
}
// PROBABILITY_OF_PRECIPITATION
if (todayDict!["precProb"] != nil) {
numberTodPop = todayDict!["precProb"] as! NSNumber;
todayPop = Int(numberTodPop.intValue);
} else {
print("That precProb is not in the todayDict dictionary.")
}
// HUMID
if (todayDict!["humid"] != nil) {
numberTodHumid = todayDict!["humid"] as! NSNumber;
todayHumid = Int(numberTodHumid.intValue);
} else {
print("That humid is not in the todayDict dictionary.")
}
strAirState = NSLocalizedString("LOC_HUMIDITY", comment:"습도") + " \(todayHumid)% ";
}
} else {
print("That strTime is not in the jsonDict dictionary.")
let strHourMin = "";
strDateTime = NSLocalizedString("LOC_UPDATE", comment:"업데이트") + " " + strHourMin;
}
print("strDateTime => \(strDateTime)")
if(tempUnit == TEMP_UNIT.FAHRENHEIT)
{
let idT1h = currentDict["temp_f"] as! NSNumber;
currentTemp = Float(Int(truncating: idT1h));
}
else
{
let idT1h = currentDict["temp_c"] as! NSNumber;
currentTemp = Float(truncating: idT1h);
}
}
print("todayMinTemp: \(todayMinTemp), todayMaxTemp:\(todayMaxTemp)");
print("todayPop: \(todayPop)");
print("=======> strCurImgName : \(strCurImgName)");
if let currentDict : Dictionary<String, Any> = jsonDict?["current"] as? Dictionary<String, Any>{
//print("currentDict is \(currentDict).")
if let currentArpltnDict : Dictionary<String, Any> = currentDict["arpltn"] as? Dictionary<String, Any> {
strAirState = watchTWSM.getAirState(currentArpltnDict);
// Test
//nssAirState = [NSString stringWithFormat:@"통합대기 78 나쁨"];
attrStrAirState = watchTWSM.getChangedColorAirState(strAirState:strAirState);
print("[processWeatherResultsAboutCompGlobal] attrStrAirState : \(String(describing: attrStrAirState))");
print("[processWeatherResultsAboutCompGlobal] strAirState : \(String(describing: strAirState))");
} else {
print("That currentArpltnDict is not in the jsonDict dictionary.")
}
} else {
print("That currentDict is not in the jsonDict dictionary.")
}
#if KKH
if let currentDict : Dictionary<String, Any> = jsonDict?["current"] as? Dictionary<String, Any>{
//print("currentDict is \(currentDict).")
if let currentArpltnDict : Dictionary<String, Any> = currentDict["arpltn"] as? Dictionary<String, Any> {
strAirState = watchTWSM.getAirState(currentArpltnDict);
// Test
//nssAirState = [NSString stringWithFormat:@"통합대기 78 나쁨"];
attrStrAirState = watchTWSM.getChangedColorAirState(strAirState:strAirState);
print("[processWeatherResultsWithShowMore] attrStrAirState : \(String(describing: attrStrAirState))");
print("[processWeatherResultsWithShowMore] strAirState : \(String(describing: strAirState))");
} else {
print("That currentArpltnDict is not in the jsonDict dictionary.")
}
} else {
print("That currentDict is not in the jsonDict dictionary.")
}
if(strDateTime != nil) {
self.updateDateLabel.setText("\(strDateTime!)");
}
print("=======> date : \(strDateTime!)");
if( (strAddress == nil) || ( strAddress == "(null)" ))
{
self.addressLabel.setText("");
}
else
{
self.addressLabel.setText("\(strAddress!)");
}
print("=======> strCurImgName : \(strCurImgName!)");
strCurImgName = "MoonBigCloudRainLightning";
if(strCurImgName != nil) {
self.curWeatherImage.setImage ( UIImage(named:"Moon"/*strCurImgName!*/) );
print("111=======> strCurImgName : \(strCurImgName!)");
}
if(tempUnit == TEMP_UNIT.FAHRENHEIT) {
self.curTempLabel.setText( NSString(format: "%d˚", currentTemp) as String );
} else {
self.curTempLabel.setText( NSString(format: "%.01f˚", currentTemp) as String);
}
#if KKH
print("[processWeatherResultsWithShowMore] attrStrAirState2 : \(String(describing: attrStrAirState))");
self.airAQILabel.setAttributedText( attrStrAirState );
#endif
self.minMaxLabel.setText(NSString(format: "%d˚/ %d˚", todayMinTemp, todayMaxTemp) as String );
self.precLabel.setText(NSString(format: "%d%%", todayPop) as String );
self.airAQILabel.setText(strAirState);
#endif
}
func refreshComplications() {
let server : CLKComplicationServer = CLKComplicationServer.sharedInstance();
print("refreshComplications");
for(complication) in server.activeComplications! {
print("\(complication)");
server.reloadTimeline(for: complication)
}
}
//internal func getNextRequestedUpdateDate ( handler : @ escaping ( Date?) -> Void ) {
// handler ( Date ( timeIntervalSinceNow : TimeInterval ( 10 * 60 )))
//}
// MARK: - Placeholder Templates
func getLocalizableSampleTemplate(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTemplate?) -> Void) {
// This method will be called once per supported complication, and the results will be cached
if complication . family == . utilitarianSmall {
let template = CLKComplicationTemplateUtilitarianSmallRingText ()
template . textProvider = CLKSimpleTextProvider ( text : "3" )
template . fillFraction = self.dayFraction
handler ( template )
} else {
handler ( nil )
}
}
var dayFraction : Float {
let retVal : Float
let now = Date ()
let calendar = Calendar.current
//let componentFlags = Set<Calendar.Component > ([.year, .month , .day , .WEEKOFYEAR, .hour, .minute ,.second ,.weekday, .weekdayOrdinal])
let componentFlags = Set<Calendar.Component>([.year, .month, .day, .weekOfYear, .hour, .minute, .second, .weekday, .weekdayOrdinal])
var components = calendar . dateComponents (componentFlags , from : now )
components . hour = 0
components . minute = 0
components . second = 0
let startOfDay = calendar . date ( from : components )
retVal = Float( now . timeIntervalSince ( startOfDay! )) / Float( 24 * 60 * 60 )
return retVal
}
#if KKH
func getSupportedTimeTravelDirectionsForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationTimeTravelDirections) -> Void) {
//handler([CLKComplicationTimeTravelDirections.None])
handler([])
}
func getTimelineEntriesForComplication(complication: CLKComplication, beforeDate date: NSDate, limit: Int, withHandler handler: ([CLKComplicationTimelineEntry]?) -> Void) {
handler(nil)
}
func getTimelineEntriesForComplication(complication: CLKComplication, afterDate date: NSDate, limit: Int, withHandler handler: ([CLKComplicationTimelineEntry]?) -> Void) {
handler([])
}
func getTimelineStartDateForComplication(complication: CLKComplication, withHandler handler: (NSDate?) -> Void) {
handler(NSDate())
}
func getTimelineEndDateForComplication(complication: CLKComplication, withHandler handler: (NSDate?) -> Void) {
handler(NSDate())
}
func getPrivacyBehaviorForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationPrivacyBehavior) -> Void) {
handler(CLKComplicationPrivacyBehavior.showOnLockScreen)
}
#endif
}
| mit | 36e166d66c772233f9b1268899d59324 | 42.72337 | 277 | 0.541709 | 4.861381 | false | false | false | false |
lyft/SwiftLint | Source/SwiftLintFramework/Rules/OpeningBraceRule.swift | 1 | 5578 | import Foundation
import SourceKittenFramework
private let whitespaceAndNewlineCharacterSet = CharacterSet.whitespacesAndNewlines
private extension File {
func violatingOpeningBraceRanges() -> [(range: NSRange, location: Int)] {
return match(pattern: "(?:[^( ]|[\\s(][\\s]+)\\{",
excludingSyntaxKinds: SyntaxKind.commentAndStringKinds,
excludingPattern: "(?:if|guard|while)\\n[^\\{]+?[\\s\\t\\n]\\{").map {
let branceRange = contents.bridge().range(of: "{", options: .literal, range: $0)
return ($0, branceRange.location)
}
}
}
public struct OpeningBraceRule: CorrectableRule, ConfigurationProviderRule {
public var configuration = SeverityConfiguration(.warning)
public init() {}
public static let description = RuleDescription(
identifier: "opening_brace",
name: "Opening Brace Spacing",
description: "Opening braces should be preceded by a single space and on the same line " +
"as the declaration.",
kind: .style,
nonTriggeringExamples: [
"func abc() {\n}",
"[].map() { $0 }",
"[].map({ })",
"if let a = b { }",
"while a == b { }",
"guard let a = b else { }",
"if\n\tlet a = b,\n\tlet c = d\n\twhere a == c\n{ }",
"while\n\tlet a = b,\n\tlet c = d\n\twhere a == c\n{ }",
"guard\n\tlet a = b,\n\tlet c = d\n\twhere a == c else\n{ }",
"struct Rule {}\n",
"struct Parent {\n\tstruct Child {\n\t\tlet foo: Int\n\t}\n}\n"
],
triggeringExamples: [
"func abc()↓{\n}",
"func abc()\n\t↓{ }",
"[].map()↓{ $0 }",
"[].map( ↓{ } )",
"if let a = b↓{ }",
"while a == b↓{ }",
"guard let a = b else↓{ }",
"if\n\tlet a = b,\n\tlet c = d\n\twhere a == c↓{ }",
"while\n\tlet a = b,\n\tlet c = d\n\twhere a == c↓{ }",
"guard\n\tlet a = b,\n\tlet c = d\n\twhere a == c else↓{ }",
"struct Rule↓{}\n",
"struct Rule\n↓{\n}\n",
"struct Rule\n\n\t↓{\n}\n",
"struct Parent {\n\tstruct Child\n\t↓{\n\t\tlet foo: Int\n\t}\n}\n"
],
corrections: [
"struct Rule↓{}\n": "struct Rule {}\n",
"struct Rule\n↓{\n}\n": "struct Rule {\n}\n",
"struct Rule\n\n\t↓{\n}\n": "struct Rule {\n}\n",
"struct Parent {\n\tstruct Child\n\t↓{\n\t\tlet foo: Int\n\t}\n}\n":
"struct Parent {\n\tstruct Child {\n\t\tlet foo: Int\n\t}\n}\n",
"[].map()↓{ $0 }\n": "[].map() { $0 }\n",
"[].map( ↓{ })\n": "[].map({ })\n",
"if a == b↓{ }\n": "if a == b { }\n",
"if\n\tlet a = b,\n\tlet c = d↓{ }\n": "if\n\tlet a = b,\n\tlet c = d { }\n"
]
)
public func validate(file: File) -> [StyleViolation] {
return file.violatingOpeningBraceRanges().map {
StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity,
location: Location(file: file, characterOffset: $0.location))
}
}
public func correct(file: File) -> [Correction] {
let violatingRanges = file.violatingOpeningBraceRanges().filter {
!file.ruleEnabled(violatingRanges: [$0.range], for: self).isEmpty
}
var correctedContents = file.contents
var adjustedLocations = [Location]()
for (violatingRange, location) in violatingRanges.reversed() {
correctedContents = correct(contents: correctedContents, violatingRange: violatingRange)
adjustedLocations.insert(Location(file: file, characterOffset: location), at: 0)
}
file.write(correctedContents)
return adjustedLocations.map {
Correction(ruleDescription: type(of: self).description,
location: $0)
}
}
private func correct(contents: String,
violatingRange: NSRange) -> String {
guard let indexRange = contents.nsrangeToIndexRange(violatingRange) else {
return contents
}
#if swift(>=4.0)
let capturedString = String(contents[indexRange])
#else
let capturedString = contents[indexRange]
#endif
var adjustedRange = violatingRange
var correctString = " {"
// "struct Command{" has violating string = "d{", so ignore first "d"
if capturedString.count == 2 &&
capturedString.rangeOfCharacter(from: whitespaceAndNewlineCharacterSet) == nil {
adjustedRange = NSRange(
location: violatingRange.location + 1,
length: violatingRange.length - 1
)
}
// "[].map( { } )" has violating string = "( {",
// so ignore first "(" and use "{" as correction string instead
if capturedString.hasPrefix("(") {
adjustedRange = NSRange(
location: violatingRange.location + 1,
length: violatingRange.length - 1
)
correctString = "{"
}
if let indexRange = contents.nsrangeToIndexRange(adjustedRange) {
let correctedContents = contents
.replacingCharacters(in: indexRange, with: correctString)
return correctedContents
} else {
return contents
}
}
}
| mit | 6ff84babb67b1d4c0703c31a1b2e5fe9 | 38.81295 | 100 | 0.526021 | 3.91372 | false | false | false | false |
benlangmuir/swift | test/SILOptimizer/definite_init_cross_module_swift4.swift | 20 | 9488 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -emit-module-path=%t/OtherModule.swiftmodule %S/Inputs/definite_init_cross_module/OtherModule.swift
// RUN: %target-swift-frontend -emit-sil -verify -verify-ignore-unknown -I %t -swift-version 4 %s > /dev/null -enable-objc-interop -disable-objc-attr-requires-foundation-module -import-objc-header %S/Inputs/definite_init_cross_module/BridgingHeader.h
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -emit-module-path=%t/OtherModule.swiftmodule %S/Inputs/definite_init_cross_module/OtherModule.swift
// RUN: %target-swift-frontend -emit-sil -verify -verify-ignore-unknown -I %t -swift-version 4 %s > /dev/null -enable-objc-interop -disable-objc-attr-requires-foundation-module -import-objc-header %S/Inputs/definite_init_cross_module/BridgingHeader.h
import OtherModule
extension Point {
init(xx: Double, yy: Double) {
self.x = xx // expected-warning {{initializer for struct 'Point' must use "self.init(...)" or "self = ..." because it is not in module 'OtherModule'}}
self.y = yy
}
init(xx: Double) {
self.x = xx // expected-warning {{initializer for struct 'Point' must use "self.init(...)" or "self = ..." because it is not in module 'OtherModule'}}
} // expected-error {{return from initializer without initializing all stored properties}}
init(xxx: Double, yyy: Double) {
// This is OK
self.init(x: xxx, y: yyy)
}
init(other: Point) {
// This is OK
self = other
}
init(other: Point, x: Double) {
// This is OK
self = other
self.x = x
}
init(other: Point, xx: Double) {
self.x = xx // expected-warning {{initializer for struct 'Point' must use "self.init(...)" or "self = ..." because it is not in module 'OtherModule'}}
self = other
}
init(other: Point, x: Double, cond: Bool) {
// This is OK
self = other
if cond { self.x = x }
}
init(other: Point, xx: Double, cond: Bool) {
if cond { self = other }
self.x = xx // expected-warning {{initializer for struct 'Point' must use "self.init(...)" or "self = ..." on all paths because it is not in module 'OtherModule'}}
self.y = 0
}
}
extension ImmutablePoint {
init(xx: Double, yy: Double) {
self.x = xx // expected-warning {{initializer for struct 'ImmutablePoint' must use "self.init(...)" or "self = ..." because it is not in module 'OtherModule'}}
self.y = yy
}
init(xxx: Double, yyy: Double) {
// This is OK
self.init(x: xxx, y: yyy)
}
init(other: ImmutablePoint) {
// This is OK
self = other
}
init(other: ImmutablePoint, x: Double) {
self = other
self.x = x // expected-error {{immutable value 'self.x' may only be initialized once}}
}
init(other: ImmutablePoint, xx: Double) {
self.x = xx // expected-warning {{initializer for struct 'ImmutablePoint' must use "self.init(...)" or "self = ..." because it is not in module 'OtherModule'}}
self = other // expected-error {{immutable value 'self.x' may only be initialized once}}
}
init(other: ImmutablePoint, x: Double, cond: Bool) {
// This is OK
self = other
if cond { self.x = x } // expected-error {{immutable value 'self.x' may only be initialized once}}
}
init(other: ImmutablePoint, xx: Double, cond: Bool) {
if cond { self = other }
self.x = xx // expected-error {{immutable value 'self.x' may only be initialized once}}
self.y = 0 // expected-error {{immutable value 'self.y' may only be initialized once}}
}
}
extension GenericPoint {
init(xx: T, yy: T) {
self.x = xx // expected-warning {{initializer for struct 'GenericPoint<T>' must use "self.init(...)" or "self = ..." because it is not in module 'OtherModule'}}
self.y = yy
}
init(xxx: T, yyy: T) {
// This is OK
self.init(x: xxx, y: yyy)
}
init(other: GenericPoint<T>) {
// This is OK
self = other
}
init(other: GenericPoint<T>, x: T) {
// This is OK
self = other
self.x = x
}
init(other: GenericPoint<T>, xx: T) {
self.x = xx // expected-warning {{initializer for struct 'GenericPoint<T>' must use "self.init(...)" or "self = ..." because it is not in module 'OtherModule'}}
self = other
}
init(other: GenericPoint<T>, x: T, cond: Bool) {
// This is OK
self = other
if cond { self.x = x }
}
init(other: GenericPoint<T>, xx: T, cond: Bool) {
if cond { self = other }
self.x = xx // expected-warning {{initializer for struct 'GenericPoint<T>' must use "self.init(...)" or "self = ..." on all paths because it is not in module 'OtherModule'}}
self.y = xx
}
}
extension GenericPoint where T == Double {
init(xx: Double, yy: Double) {
self.x = xx // expected-warning {{initializer for struct 'GenericPoint<Double>' must use "self.init(...)" or "self = ..." because it is not in module 'OtherModule'}}
self.y = yy
}
init(xxx: Double, yyy: Double) {
// This is OK
self.init(x: xxx, y: yyy)
}
init(other: GenericPoint<Double>) {
// This is OK
self = other
}
init(other: GenericPoint<Double>, x: Double) {
// This is OK
self = other
self.x = x
}
init(other: GenericPoint<Double>, xx: Double) {
self.x = xx // expected-warning {{initializer for struct 'GenericPoint<Double>' must use "self.init(...)" or "self = ..." because it is not in module 'OtherModule'}}
self = other
}
init(other: GenericPoint<Double>, x: Double, cond: Bool) {
// This is OK
self = other
if cond { self.x = x }
}
init(other: GenericPoint<Double>, xx: Double, cond: Bool) {
if cond { self = other }
self.x = xx // expected-warning {{initializer for struct 'GenericPoint<Double>' must use "self.init(...)" or "self = ..." on all paths because it is not in module 'OtherModule'}}
self.y = 0
}
}
typealias MyGenericPoint<Q> = GenericPoint<Q>
extension MyGenericPoint {
// FIXME: Should preserve type sugar.
init(myX: T, myY: T) {
self.x = myX // expected-warning {{initializer for struct 'GenericPoint<T>' must use "self.init(...)" or "self = ..." because it is not in module 'OtherModule'}}
self.y = myY
}
}
extension CPoint {
init(xx: Double, yy: Double) {
self.x = xx // expected-warning {{initializer for struct 'CPoint' must use "self.init(...)" or "self = ..." because the struct was imported from C}} expected-note {{use "self.init()" to initialize the struct with zero values}} {{5-5=self.init()\n}}
self.y = yy
}
init(xxx: Double, yyy: Double) {
// This is OK
self.init(x: xxx, y: yyy)
}
init(other: CPoint) {
// This is OK
self = other
}
init(other: CPoint, x: Double) {
// This is OK
self = other
self.x = x
}
init(other: CPoint, xx: Double) {
self.x = xx // expected-warning {{initializer for struct 'CPoint' must use "self.init(...)" or "self = ..." because the struct was imported from C}} expected-note {{use "self.init()" to initialize the struct with zero values}} {{5-5=self.init()\n}}
self = other
}
init(other: CPoint, x: Double, cond: Bool) {
// This is OK
self = other
if cond { self.x = x }
}
init(other: CPoint, xx: Double, cond: Bool) {
if cond { self = other }
self.x = xx // expected-warning {{initializer for struct 'CPoint' must use "self.init(...)" or "self = ..." on all paths because the struct was imported from C}}
self.y = 0
}
}
extension NonnullWrapper {
init(p: UnsafeMutableRawPointer) {
self.ptr = p // expected-warning {{initializer for struct 'NonnullWrapper' must use "self.init(...)" or "self = ..." because the struct was imported from C}}
// No suggestion for "self.init()" because this struct does not support a
// zeroing initializer.
}
}
extension PrivatePoint {
init(xxx: Double, yyy: Double) {
// This is OK
self.init(x: xxx, y: yyy)
}
init(other: PrivatePoint) {
// This is OK
self = other
}
init(other: PrivatePoint, cond: Bool) {
if cond { self = other }
} // expected-error {{return from initializer without initializing all stored properties}}
// Ideally we wouldn't mention the names of non-public stored properties
// across module boundaries, but this will go away in Swift 5 mode anyway.
init() {
} // expected-error {{return from initializer without initializing all stored properties}}
}
extension Empty {
init(x: Double) {
// This is OK
self.init()
}
init(other: Empty) {
// This is okay
self = other
}
init(other: Empty, cond: Bool) {
if cond { self = other }
} // expected-warning {{initializer for struct 'Empty' must use "self.init(...)" or "self = ..." on all paths because it is not in module 'OtherModule'}}
init(xx: Double) {
} // expected-warning {{initializer for struct 'Empty' must use "self.init(...)" or "self = ..." because it is not in module 'OtherModule'}}
}
extension GenericEmpty {
init(x: Double) {
// This is OK
self.init()
}
init(other: GenericEmpty<T>) {
// This is okay
self = other
}
init(other: GenericEmpty<T>, cond: Bool) {
if cond { self = other }
} // expected-warning {{initializer for struct 'GenericEmpty<T>' must use "self.init(...)" or "self = ..." on all paths because it is not in module 'OtherModule'}}
init(xx: Double) {
} // expected-warning {{initializer for struct 'GenericEmpty<T>' must use "self.init(...)" or "self = ..." because it is not in module 'OtherModule'}}
}
| apache-2.0 | cff49eb244a0b0bf2a17bbc52032564b | 31.604811 | 252 | 0.633959 | 3.527138 | false | false | false | false |
kenwilcox/TheForecaster | WeatherShare/ForecastNetwork.swift | 1 | 1211 | //
// ForecastNetwork.swift
// TheForecaster
//
// Created by Kenneth Wilcox on 5/25/15.
// Copyright (c) 2015 Kenneth Wilcox. All rights reserved.
//
import UIKit
public class ForecastNetwork: NSObject {
public class func requestWeather (#latitude: Double, longitude: Double, completionClosure: (responseDictionary : NSDictionary?) -> ()) {
let url = NSURL(string: "https://api.forecast.io/forecast/\(kApiKey)/\(latitude),\(longitude)")
var request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "GET"
let session = NSURLSession.sharedSession()
var weatherTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
var conversionError: NSError?
var jsonDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableLeaves, error: &conversionError) as? NSDictionary
println(jsonDictionary)
if conversionError != nil {
println(conversionError!.localizedDescription)
completionClosure(responseDictionary: nil)
} else {
completionClosure(responseDictionary: jsonDictionary!)
}
})
weatherTask.resume()
}
}
| mit | d6498b162266ed9402520c9af3d35c80 | 32.638889 | 158 | 0.700248 | 4.942857 | false | false | false | false |
srxboys/RXSwiftExtention | RXSwiftExtention/BaseController/View/RXImageScroller.swift | 1 | 8412 | //
// RXImageScroller.swift
// RXSwiftExtention
//
// Created by srx on 2017/3/30.
// Copyright © 2017年 https://github.com/srxboys. All rights reserved.
//
//轮播图
import UIKit
import Kingfisher
let IMGSIdentifer = "IMGS_cell"
class RXImageScroller: UIView {
// MARK: 定义属性
var cycleTimer : Timer?
var cycleModels : [RXImageScrollModel]? {
didSet {
// 1.刷新collectionView
collectionView.reloadData()
// 2.设置pageControl个数
pageControl.numberOfPages = cycleModels?.count ?? 0
pageControl.currentPage = 0
// 3.默认滚动到中间某一个位置
let indexPath = IndexPath(item: (cycleModels?.count ?? 0) * 10, section: 0)
collectionView.scrollToItem(at: indexPath, at: .left, animated: false)
// // 4.添加定时器
removeCycleTimer()
if(pageControl.numberOfPages == 0) { return }
addCycleTimer()
}
}
//分页
fileprivate lazy var pageControl : RXPageControl = { [unowned self] in
let pageControl = RXPageControl()
let height = self.bounds.size.height
let width = self.bounds.size.width
pageControl.frame = CGRect(x: 0, y:height-15 , width: width, height: 10)
pageControl.isUserInteractionEnabled = false
return pageControl
}()
fileprivate lazy var collectionView : UICollectionView = {[unowned self] in
let flowlayout = UICollectionViewFlowLayout()
flowlayout.minimumLineSpacing = 0;
flowlayout.minimumInteritemSpacing = 0
flowlayout.scrollDirection = .horizontal
flowlayout.itemSize = self.bounds.size
let collectionView = UICollectionView(frame: self.bounds, collectionViewLayout: flowlayout)
collectionView.delegate = self
collectionView.dataSource = self;
collectionView.backgroundColor = UIColor.white
collectionView.isPagingEnabled = true
collectionView.scrollsToTop = false
collectionView.register(ImageScrollerCell.classForCoder(), forCellWithReuseIdentifier: IMGSIdentifer)
return collectionView
}()
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(collectionView)
addSubview(pageControl)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK:- 遵守UICollectionView的数据源协议
extension RXImageScroller: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return (cycleModels?.count ?? 0)*1000
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: IMGSIdentifer, for: indexPath) as! ImageScrollerCell
cell.scrollModel = cycleModels![(indexPath as NSIndexPath).item % cycleModels!.count]
return cell
}
}
// MARK:- 遵守UICollectionView的代理协议
extension RXImageScroller: UICollectionViewDelegateFlowLayout {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
// 1.获取滚动的偏移量
let offsetX = scrollView.contentOffset.x + scrollView.bounds.width * 0.5
// 2.计算pageControl的currentIndex
pageControl.currentPage = Int(offsetX / scrollView.bounds.width) % (cycleModels?.count ?? 1)
}
//
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
removeCycleTimer()
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
addCycleTimer()
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let row = indexPath.item
RXLog("点击了 轮播图第\(row)张")
}
}
// MARK:- 对定时器的操作方法
extension RXImageScroller {
fileprivate func addCycleTimer() {
cycleTimer = Timer(timeInterval: 3.0, target: self, selector: #selector(self.scrollToNext), userInfo: nil, repeats: true)
RunLoop.main.add(cycleTimer!, forMode: RunLoopMode.commonModes)
}
fileprivate func removeCycleTimer() {
cycleTimer?.invalidate() // 从运行循环中移除
cycleTimer = nil
}
@objc fileprivate func scrollToNext() {
// 1.获取滚动的偏移量
let currentOffsetX = collectionView.contentOffset.x
let offsetX = currentOffsetX + collectionView.bounds.width
// 2.滚动该位置
collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: true)
}
}
fileprivate class ImageScrollerCell: UICollectionViewCell {
fileprivate lazy var imgView : UIImageView = { [unowned self] in
let imgView = UIImageView(frame: self.bounds)
return imgView
}()
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(imgView)
}
// MARK: 定义模型属性
var scrollModel : RXImageScrollModel? {
didSet {
let iconURL = URL(string: scrollModel?.image ?? "")!
imgView.kf.setImage(with: iconURL, placeholder: UIImage(named: "Img_default"))
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: --- 分页控制器 -----
fileprivate class RXPageControl : UIView {
/// 控件间距离
var dotSpace : CGFloat = 10
/// 选择的控件大小
var dotDiameterOn : CGFloat = 8
/// 未选择的控件的大小
var dotDiameterOff : CGFloat = 5
/// 选择的控件颜色
var onColor : UIColor = UIColor.white
/// 未选择的控件颜色
var offColor : UIColor = UIColor.white
fileprivate var nomalTransform = CGAffineTransform()
/// 数组存储
fileprivate var dotArrayM = [UIView]()
/// 当前页数
var currentPage : Int = 0 {
didSet {
if(numberOfPages == 0) { return }
if(currentPage >= numberOfPages) {
currentPage = 0
}
changeSelectedPage()
}
}
/// 总页数
var numberOfPages : Int = 0 {
didSet {
removeAll()
guard numberOfPages != 0 else { return }
createSubPageControll()
}
}
fileprivate func removeAll() {
for view in subviews {
view.removeFromSuperview()
}
dotArrayM.removeAll()
}
//MARK: - 创建字分页控制器
fileprivate func createSubPageControll() {
if(numberOfPages == 0) { return }
let width = self.bounds.size.width
let count : CGFloat = CGFloat(numberOfPages) - 1
let middle = (width-dotDiameterOff*count-dotDiameterOn-count*dotSpace)/2
for i in 0..<numberOfPages {
let index = CGFloat(i)
let x : CGFloat = index*dotDiameterOff+index*dotSpace+middle
let dotView = UIView(frame: CGRect(x: x, y: 0, width: dotDiameterOff, height: dotDiameterOff))
//解包
dotView.layer.cornerRadius = dotDiameterOff/2.0
dotView.backgroundColor = offColor
dotView.tag = i
addSubview(dotView)
if(i == 0) {
//只赋一次值
nomalTransform = dotView.transform
}
dotArrayM.append(dotView)
}
}
//MARK: - 选中某个
fileprivate func changeSelectedPage() {
guard currentPage>=0 && currentPage<dotArrayM.count else {
//无效
return
}
let diffTransform = (dotDiameterOn - dotDiameterOff)/dotDiameterOff
for dotView in dotArrayM {
if(dotView.tag == currentPage) {
dotView.transform = CGAffineTransform(scaleX: 1+diffTransform, y: 1+diffTransform)
dotView.backgroundColor = onColor
}
else {
dotView.transform = nomalTransform
dotView.backgroundColor = offColor
}
}
}
}
| mit | 9df8c4038d2113915df7c55820265149 | 30.11583 | 129 | 0.610622 | 4.983921 | false | false | false | false |
certainly/Caculator | FaceIt/FaceIt/FaceView.swift | 1 | 4039 | //
// FaceView.swift
// FaceIt
//
// Created by certainly on 2017/3/23.
// Copyright © 2017年 certainly. All rights reserved.
//
import UIKit
@IBDesignable
class FaceView: UIView {
@IBInspectable
var scale: CGFloat = 0.9 { didSet { setNeedsDisplay() } }
@IBInspectable
var eyesOpen: Bool = false { didSet { setNeedsDisplay() } }
@IBInspectable
var mouthCurvature: Double = -0.5 { didSet { setNeedsDisplay() } }
@IBInspectable
var lineWidth: CGFloat = 5.0 { didSet { setNeedsDisplay() } }
@IBInspectable
var color: UIColor = UIColor.blue { didSet { setNeedsDisplay() } }
func changeScale(byReactingTo pinchRecognizer: UIPinchGestureRecognizer) {
switch pinchRecognizer.state {
case .changed, .ended:
scale *= pinchRecognizer.scale
pinchRecognizer.scale = 1
default:
break
}
}
private var skullRadius: CGFloat {
return min(bounds.size.width, bounds.size.height) / 2 * scale
}
private var skullCenter: CGPoint {
return CGPoint(x: bounds.midX, y: bounds.midY)
}
enum Eye {
case left
case right
}
private func pathForEye(_ eye: Eye) -> UIBezierPath {
func centerOfEye(_ eye: Eye) -> CGPoint {
let eyeOffset = skullRadius / Ratios.skullRadiusToEyeOffset
var eyeCenter = skullCenter
eyeCenter.y -= eyeOffset
eyeCenter.x += ((eye == .left) ? -1 : 1) * eyeOffset
return eyeCenter
}
let eyeRadius = skullRadius / Ratios.skullRadiusToEyeRadius
let eyeCenter = centerOfEye(eye)
let path : UIBezierPath
if eyesOpen {
path = UIBezierPath(arcCenter: eyeCenter, radius: eyeRadius, startAngle: 0, endAngle: CGFloat.pi * 2, clockwise: true)
} else {
path = UIBezierPath()
path.move(to: CGPoint(x: eyeCenter.x - eyeRadius, y: eyeCenter.y))
path.addLine(to: CGPoint(x: eyeCenter.x + eyeRadius, y: eyeCenter.y))
}
path.lineWidth = lineWidth
return path
}
private func pathForMouth() -> UIBezierPath {
let mouthWidth = skullRadius / Ratios.skullRadiusToMouthWidth
let mouthHeight = skullRadius / Ratios.skullRadiusToMouthHeight
let mouthOffset = skullRadius / Ratios.skullRadiusToMouthOffset
let mouthRect = CGRect(x: skullCenter.x - mouthWidth / 2, y: skullCenter.y + mouthOffset, width: mouthWidth, height: mouthHeight)
let smileOffset = CGFloat(max(-1, min(mouthCurvature, 1))) * mouthRect.height
let start = CGPoint(x: mouthRect.minX, y: mouthRect.midY)
let end = CGPoint(x: mouthRect.maxX, y: mouthRect.midY)
let cp1 = CGPoint(x: start.x + mouthRect.width / 3 , y: start.y + smileOffset)
let cp2 = CGPoint(x: end.x - mouthRect.width / 3 , y: start.y + smileOffset)
let path = UIBezierPath()
path.move(to: start)
path.addCurve(to: end, controlPoint1: cp1, controlPoint2: cp2)
path.lineWidth = lineWidth
return path
}
private func pathForSkull() -> UIBezierPath {
let path = UIBezierPath(arcCenter: skullCenter, radius: skullRadius, startAngle: 0, endAngle: .pi * 2, clockwise: false)
path.lineWidth = lineWidth
return path
}
override func draw(_ rect: CGRect) {
// Drawing code
color.set()
pathForSkull().stroke()
pathForEye(.left).stroke()
pathForEye(.right).stroke()
pathForMouth().stroke()
}
private struct Ratios {
static let skullRadiusToEyeOffset: CGFloat = 3
static let skullRadiusToEyeRadius: CGFloat = 10
static let skullRadiusToMouthWidth: CGFloat = 1
static let skullRadiusToMouthHeight: CGFloat = 3
static let skullRadiusToMouthOffset: CGFloat = 3
}
}
| mit | 29de7cc4c8f4ba2003aa8121a850930c | 31.548387 | 137 | 0.605302 | 4.37744 | false | false | false | false |
Sephiroth87/C-swifty4 | C64/CPU+Opcodes.swift | 1 | 34735 | //
// CPU+Opcodes.swift
// C64
//
// Created by Fabio on 19/12/2016.
// Copyright © 2016 orange in a day. All rights reserved.
//
extension CPU {
//MARK: ADC
internal func adc(_ value: UInt8) {
if state.d {
var lowNybble = (state.a & 0x0F) &+ (value & 0x0F) &+ (state.c ? 1 : 0)
var highNybble = (state.a >> 4) &+ (value >> 4)
if lowNybble > 9 {
lowNybble = lowNybble &+ 6
}
if lowNybble > 0x0F {
highNybble = highNybble &+ 1
}
state.z = ((state.a &+ value &+ (state.c ? 1 : 0)) & 0xFF == 0)
state.n = (highNybble & 0x08 != 0)
state.v = ((((highNybble << 4) ^ state.a) & 0x80) != 0 && ((state.a ^ value) & 0x80) == 0)
if highNybble > 9 {
highNybble = highNybble &+ 6
}
state.c = (highNybble > 0x0F)
state.a = (highNybble << 4) | (lowNybble & 0x0F)
} else {
let tempA = UInt16(state.a)
let sum = (tempA + UInt16(value) + (state.c ? 1 : 0))
state.c = (sum > 0xFF)
state.v = (((tempA ^ UInt16(value)) & 0x80) == 0 && ((tempA ^ sum) & 0x80) != 0)
loadA(UInt8(truncatingIfNeeded: sum))
}
}
internal func adcImmediate() {
if loadDataImmediate() {
adc(state.data)
state.cycle = 0
}
}
internal func adcZeroPage() {
if loadDataZeroPage() {
adc(state.data)
state.cycle = 0
}
}
internal func adcPageBoundary() {
if loadDataAbsolute() {
if state.pageBoundaryCrossed {
state.addressHigh = state.addressHigh &+ 1
} else {
adc(state.data)
state.cycle = 0
}
}
}
internal func adcAbsolute() {
if loadDataAbsolute() {
adc(state.data)
state.cycle = 0
}
}
//MARK: ALR*
internal func alrImmediate() {
if loadDataImmediate() {
let a = state.a & state.data
state.c = ((a & 1) != 0)
loadA(a >> 1)
state.cycle = 0
}
}
//MARK: ANC*
internal func ancImmediate() {
if loadDataImmediate() {
loadA(state.a & state.data)
state.c = state.n
state.cycle = 0
}
}
//MARK: AND
internal func andImmediate() {
if loadDataImmediate() {
loadA(state.a & state.data)
state.cycle = 0
}
}
internal func andZeroPage() {
if loadDataZeroPage() {
loadA(state.a & state.data)
state.cycle = 0
}
}
internal func andPageBoundary() {
if loadDataAbsolute() {
if state.pageBoundaryCrossed {
state.addressHigh = state.addressHigh &+ 1
} else {
loadA(state.a & state.data)
state.cycle = 0
}
}
}
internal func andAbsolute() {
if loadDataAbsolute() {
loadA(state.a & state.data)
state.cycle = 0
}
}
//MARK: ANE*
internal func aneImmediate() {
if loadDataImmediate() {
//TODO: From http://www.zimmers.net/anonftp/pub/cbm/documents/chipdata/64doc, number might be different than 0xEE
loadA((state.a | 0xEE) & state.x & state.data)
state.cycle = 0
}
}
//MARK: ARR*
internal func arrImmediate() {
if loadDataImmediate() {
let tempA = state.a & state.data
state.a = (tempA >> 1) + (state.c ? 0x80 : 0)
if state.d {
state.n = state.c
state.z = (state.a == 0)
state.v = (((tempA ^ state.a) & 0x40) != 0)
if (tempA & 0x0F) + (tempA & 0x01) > 5 {
state.a = (state.a & 0xF0) | ((state.a &+ 6) & 0x0F)
}
if UInt16(tempA & 0xF0) &+ UInt16(tempA & 0x10) > 0x50 {
state.c = true
state.a = state.a &+ 0x60
} else {
state.c = false
}
} else {
state.z = (state.a == 0)
state.n = (state.a & 0x80 != 0)
state.c = ((state.a & 0x40) != 0)
state.v = (((state.a & 0x40) ^ ((state.a & 0x20) << 1)) != 0)
}
state.cycle = 0
}
}
//MARK: ASL
internal func aslAccumulator() {
if idleReadImplied() {
state.c = ((state.a & 0x80) != 0)
loadA(state.a << 1)
state.cycle = 0
}
}
internal func aslZeroPage() {
memory.writeByte(UInt16(state.addressLow), byte: state.data)
state.c = ((state.data & 0x80) != 0)
state.data = state.data << 1
}
internal func aslAbsolute() {
memory.writeByte(address, byte: state.data)
state.c = ((state.data & 0x80) != 0)
state.data = state.data << 1
}
//MARK: BCC
internal func branch() {
if idleReadImplied() {
let oldPch = pch
state.pc = state.pc &+ Int8(bitPattern: state.data)
if pch == oldPch {
if state.irqDelayCounter >= 0 {
state.irqDelayCounter += 1
}
if state.nmiDelayCounter >= 0 {
state.nmiDelayCounter += 1
}
state.cycle = 0
}
}
}
internal func branchOverflow() {
if rdyLine.state {
if state.data & 0x80 != 0 {
memory.readByte(state.pc &+ UInt16(0x100))
} else {
memory.readByte(state.pc &- UInt16(0x100))
}
state.cycle = 0
} else {
state.cycle -= 1
}
}
internal func bccRelative() {
if loadDataImmediate() {
if state.c {
state.cycle = 0
}
}
}
//MARK: BCS
internal func bcsRelative() {
if loadDataImmediate() {
if !state.c {
state.cycle = 0
}
}
}
//MARK: BEQ
internal func beqRelative() {
if loadDataImmediate() {
if !state.z {
state.cycle = 0
}
}
}
//MARK: BIT
internal func bitZeroPage() {
if loadDataZeroPage() {
state.n = ((state.data & 128) != 0)
state.v = ((state.data & 64) != 0)
state.z = ((state.data & state.a) == 0)
state.cycle = 0
}
}
internal func bitAbsolute() {
if loadDataAbsolute() {
state.n = ((state.data & 128) != 0)
state.v = ((state.data & 64) != 0)
state.z = ((state.data & state.a) == 0)
state.cycle = 0
}
}
//MARK: BMI
internal func bmiRelative() {
if loadDataImmediate() {
if !state.n {
state.cycle = 0
}
}
}
//MARK: BNE
internal func bneRelative() {
if loadDataImmediate() {
if state.z {
state.cycle = 0
}
}
}
//MARK: BPL
internal func bplRelative() {
if loadDataImmediate() {
if state.n {
state.cycle = 0
}
}
}
//MARK: BRK
internal func brkImplied() {
state.b = true
pushPch()
}
internal func brkImplied2() {
pushPcl()
}
internal func brkImplied3() {
let p = UInt8((state.c ? 0x01 : 0) |
(state.z ? 0x02 : 0) |
(state.i ? 0x04 : 0) |
(state.d ? 0x08 : 0) |
(state.b ? 0x10 : 0) |
0x20 |
(state.v ? 0x40 : 0) |
(state.n ? 0x80 : 0))
memory.writeByte(0x100 &+ state.sp, byte: p)
state.sp = state.sp &- 1
}
internal func brkImplied4() {
if state.nmiDelayCounter == 0 {
state.data = memory.readByte(0xFFFA)
} else {
state.data = memory.readByte(0xFFFE)
if state.nmiDelayCounter == 1 {
state.nmiDelayCounter = 2
}
}
}
internal func brkImplied5() {
pcl = state.data
if state.nmiDelayCounter == 0 {
pch = memory.readByte(0xFFFB)
state.nmiDelayCounter = -1
} else {
pch = memory.readByte(0xFFFF)
//TODO: there might be some delays here if NMI is not converted, but I'm not sure
}
state.i = true
state.cycle = 0
}
//MARK: BVC
internal func bvcRelative() {
if loadDataImmediate() {
if state.v {
state.cycle = 0
}
}
}
//MARK: BVS
internal func bvsRelative() {
if loadDataImmediate() {
if !state.v {
state.cycle = 0
}
}
}
//MARK: CLC
internal func clcImplied() {
if idleReadImplied() {
state.c = false
state.cycle = 0
}
}
//MARK: CLD
internal func cldImplied() {
if idleReadImplied() {
state.d = false
state.cycle = 0
}
}
//MARK: CLI
internal func cliImplied() {
if idleReadImplied() {
state.i = false
state.cycle = 0
}
}
//MARK: CLV
internal func clvImplied() {
if idleReadImplied() {
state.v = false
state.cycle = 0
}
}
//MARK: CMP
internal func cmp(_ value1: UInt8, _ value2: UInt8) {
let diff = value1 &- value2
state.z = (diff == 0)
state.n = (diff & 0x80 != 0)
state.c = (value1 >= value2)
}
internal func cmpImmediate() {
if loadDataImmediate() {
cmp(state.a, state.data)
state.cycle = 0
}
}
internal func cmpZeroPage() {
if loadDataZeroPage() {
cmp(state.a, state.data)
state.cycle = 0
}
}
internal func cmpAbsolute() {
if loadDataAbsolute() {
cmp(state.a, state.data)
state.cycle = 0
}
}
internal func cmpPageBoundary() {
if loadDataAbsolute() {
if state.pageBoundaryCrossed {
state.addressHigh = state.addressHigh &+ 1
} else {
cmp(state.a, state.data)
state.cycle = 0
}
}
}
//MARK: CPX
internal func cpxImmediate() {
if loadDataImmediate() {
cmp(state.x, state.data)
state.cycle = 0
}
}
internal func cpxZeroPage() {
if loadDataZeroPage() {
cmp(state.x, state.data)
state.cycle = 0
}
}
internal func cpxAbsolute() {
if loadDataAbsolute() {
cmp(state.x, state.data)
state.cycle = 0
}
}
//MARK: CPY
internal func cpyImmediate() {
if loadDataImmediate() {
cmp(state.y, state.data)
state.cycle = 0
}
}
internal func cpyZeroPage() {
if loadDataZeroPage() {
cmp(state.y, state.data)
state.cycle = 0
}
}
internal func cpyAbsolute() {
if loadDataAbsolute() {
cmp(state.y, state.data)
state.cycle = 0
}
}
//MARK: DCP*
internal func dcpZeroPage() {
decZeroPage()
}
internal func dcpZeroPage2() {
memory.writeByte(UInt16(state.addressLow), byte: state.data)
cmp(state.a, state.data)
state.cycle = 0
}
internal func dcpAbsolute() {
decAbsolute()
}
internal func dcpAbsolute2() {
memory.writeByte(address, byte: state.data)
cmp(state.a, state.data)
state.cycle = 0
}
//MARK: DEC
internal func decZeroPage() {
memory.writeByte(UInt16(state.addressLow), byte: state.data)
state.data = state.data &- 1
}
internal func decAbsolute() {
memory.writeByte(address, byte: state.data)
state.data = state.data &- 1
}
//MARK: DEX
internal func dexImplied() {
if idleReadImplied() {
loadX(state.x &- 1)
state.cycle = 0
}
}
//MARK: DEY
internal func deyImplied() {
if idleReadImplied() {
loadY(state.y &- 1)
state.cycle = 0
}
}
//MARK: EOR
internal func eorImmediate() {
if loadDataImmediate() {
loadA(state.a ^ state.data)
state.cycle = 0
}
}
internal func eorZeroPage() {
if loadDataZeroPage() {
loadA(state.a ^ state.data)
state.cycle = 0
}
}
internal func eorAbsolute() {
if loadDataAbsolute() {
loadA(state.a ^ state.data)
state.cycle = 0
}
}
internal func eorPageBoundary() {
if loadDataAbsolute() {
if state.pageBoundaryCrossed {
state.addressHigh = state.addressHigh &+ 1
} else {
loadA(state.a ^ state.data)
state.cycle = 0
}
}
}
//MARK: INC
internal func incZeroPage() {
memory.writeByte(UInt16(state.addressLow), byte: state.data)
state.data = state.data &+ 1
}
internal func incAbsolute() {
memory.writeByte(address, byte: state.data)
state.data = state.data &+ 1
}
//MARK: INX
internal func inxImplied() {
if idleReadImplied() {
loadX(state.x &+ 1)
state.cycle = 0
}
}
//MARK: INY
internal func inyImplied() {
if idleReadImplied() {
loadY(state.y &+ 1)
state.cycle = 0
}
}
//MARK: ISB*
internal func isbZeroPage() {
memory.writeByte(UInt16(state.addressLow), byte: state.data)
state.data = state.data &+ 1
}
internal func isbZeroPage2() {
memory.writeByte(UInt16(state.addressLow), byte: state.data)
zeroPageWriteUpdateNZ()
sbc(state.data)
state.cycle = 0
}
internal func isbAbsolute() {
memory.writeByte(address, byte: state.data)
state.data = state.data &+ 1
}
internal func isbAbsolute2() {
memory.writeByte(address, byte: state.data)
absoluteWriteUpdateNZ()
sbc(state.data)
state.cycle = 0
}
//MARK: JMP
internal func jmpAbsolute() {
if loadAddressHigh() {
state.pc = address
state.cycle = 0
}
}
internal func jmpIndirect() {
pcl = state.data
state.addressLow = state.addressLow &+ 1
pch = memory.readByte(address)
state.cycle = 0
}
//MARK: JSR
internal func jsrAbsolute() {
if loadAddressHigh() {
state.pc = address
state.cycle = 0
}
}
//MARK: LAS*
internal func lasPageBoundary() {
if loadDataAbsolute() {
if state.pageBoundaryCrossed {
state.addressHigh = state.addressHigh &+ 1
} else {
state.data &= state.sp
state.sp = state.data
state.x = state.data
loadA(state.data)
state.cycle = 0
}
}
}
internal func lasAbsolute() {
if loadDataAbsolute() {
state.data &= state.sp
state.sp = state.data
state.x = state.data
loadA(state.data)
state.cycle = 0
}
}
//MARK: LAX*
internal func laxZeroPage() {
if loadDataZeroPage() {
loadA(state.data)
loadX(state.data)
state.cycle = 0
}
}
internal func laxPageBoundary() {
if loadDataAbsolute() {
if state.pageBoundaryCrossed {
state.addressHigh = state.addressHigh &+ 1
} else {
loadA(state.data)
loadX(state.data)
state.cycle = 0
}
}
}
internal func laxAbsolute() {
if loadDataAbsolute() {
loadA(state.data)
loadX(state.data)
state.cycle = 0
}
}
//MARK: LDA
internal func ldaImmediate() {
if loadDataImmediate() {
loadA(state.data)
state.cycle = 0
}
}
internal func ldaZeroPage() {
if loadDataZeroPage() {
loadA(state.data)
state.cycle = 0
}
}
internal func ldaAbsolute() {
if loadDataAbsolute() {
loadA(state.data)
state.cycle = 0
}
}
internal func ldaPageBoundary() {
if loadDataAbsolute() {
if state.pageBoundaryCrossed {
state.addressHigh = state.addressHigh &+ 1
} else {
loadA(state.data)
state.cycle = 0
}
}
}
//MARK: LDX
internal func ldxImmediate() {
if loadDataImmediate() {
loadX(state.data)
state.cycle = 0
}
}
internal func ldxZeroPage() {
if loadDataZeroPage() {
loadX(state.data)
state.cycle = 0
}
}
internal func ldxAbsolute() {
if loadDataAbsolute() {
loadX(state.data)
state.cycle = 0
}
}
internal func ldxPageBoundary() {
if loadDataAbsolute() {
if state.pageBoundaryCrossed {
state.addressHigh = state.addressHigh &+ 1
} else {
loadX(state.data)
state.cycle = 0
}
}
}
//MARK: LDY
internal func ldyImmediate() {
if loadDataImmediate() {
loadY(state.data)
state.cycle = 0
}
}
internal func ldyZeroPage() {
if loadDataZeroPage() {
loadY(state.data)
state.cycle = 0
}
}
internal func ldyAbsolute() {
if loadDataAbsolute() {
loadY(state.data)
state.cycle = 0
}
}
internal func ldyPageBoundary() {
if loadDataAbsolute() {
if state.pageBoundaryCrossed {
state.addressHigh = state.addressHigh &+ 1
} else {
loadY(state.data)
state.cycle = 0
}
}
}
//MARK: LSR
internal func lsrAccumulator() {
if idleReadImplied() {
state.c = ((state.a & 1) != 0)
loadA(state.a >> 1)
state.cycle = 0
}
}
internal func lsrZeroPage() {
memory.writeByte(UInt16(state.addressLow), byte: state.data)
state.c = ((state.data & 1) != 0)
state.data = state.data >> 1
}
internal func lsrAbsolute() {
memory.writeByte(address, byte: state.data)
state.c = ((state.data & 1) != 0)
state.data = state.data >> 1
}
//MARK: LXA*
internal func lxaImmediate() {
if loadDataImmediate() {
//TODO: From http://www.zimmers.net/anonftp/pub/cbm/documents/chipdata/64doc, number might be different than 0xEE
state.x = state.data & (state.a | 0xEE)
loadA(state.x)
state.cycle = 0
}
}
//MARK: NOP
internal func nop() {
if idleReadImplied() {
state.cycle = 0
}
}
internal func nopZeroPage() {
if loadDataZeroPage() {
state.cycle = 0
}
}
internal func nopImmediate() {
if loadDataImmediate() {
state.cycle = 0
}
}
internal func nopPageBoundary() {
if loadDataAbsolute() {
if state.pageBoundaryCrossed {
state.addressHigh = state.addressHigh &+ 1
} else {
state.cycle = 0
}
}
}
internal func nopAbsolute() {
if loadDataAbsolute() {
state.cycle = 0
}
}
//MARK: ORA
internal func oraImmediate() {
if loadDataImmediate() {
loadA(state.a | state.data)
state.cycle = 0
}
}
internal func oraZeroPage() {
if loadDataZeroPage() {
loadA(state.a | state.data)
state.cycle = 0
}
}
internal func oraPageBoundary() {
if loadDataAbsolute() {
if state.pageBoundaryCrossed {
state.addressHigh = state.addressHigh &+ 1
} else {
loadA(state.a | state.data)
state.cycle = 0
}
}
}
internal func oraAbsolute() {
if loadDataAbsolute() {
loadA(state.a | state.data)
state.cycle = 0
}
}
//MARK: PHA
internal func phaImplied() {
memory.writeByte(0x100 &+ state.sp, byte: state.a)
state.sp = state.sp &- 1
state.cycle = 0
}
//MARK: PHP
internal func phpImplied() {
let p = UInt8((state.c ? 0x01 : 0) |
(state.z ? 0x02 : 0) |
(state.i ? 0x04 : 0) |
(state.d ? 0x08 : 0) |
(state.b ? 0x10 : 0) |
0x20 |
(state.v ? 0x40 : 0) |
(state.n ? 0x80 : 0))
memory.writeByte(0x100 &+ state.sp, byte: p)
state.sp = state.sp &- 1
state.cycle = 0
}
//MARK: PLA
internal func plaImplied() {
if rdyLine.state {
loadA(memory.readByte(0x100 &+ state.sp))
state.cycle = 0
} else {
state.cycle -= 1
}
}
//MARK: PLP
internal func plpImplied() {
if rdyLine.state {
let p = memory.readByte(0x100 &+ state.sp)
state.c = ((p & 0x01) != 0)
state.z = ((p & 0x02) != 0)
state.i = ((p & 0x04) != 0)
state.d = ((p & 0x08) != 0)
state.v = ((p & 0x40) != 0)
state.n = ((p & 0x80) != 0)
state.cycle = 0
} else {
state.cycle -= 1
}
}
//MARK: RLA*
internal func rlaZeroPage() {
rolZeroPage()
}
internal func rlaZeroPage2() {
memory.writeByte(UInt16(state.addressLow), byte: state.data)
loadA(state.a & state.data)
state.cycle = 0
}
internal func rlaAbsolute() {
rolAbsolute()
}
internal func rlaAbsolute2() {
memory.writeByte(address, byte: state.data)
loadA(state.a & state.data)
state.cycle = 0
}
//MARK: ROL
internal func rolAccumulator() {
if idleReadImplied() {
let hasCarry = state.c
state.c = ((state.a & 0x80) != 0)
loadA((state.a << 1) + (hasCarry ? 1 : 0))
state.cycle = 0
}
}
internal func rolZeroPage() {
memory.writeByte(UInt16(state.addressLow), byte: state.data)
let hasCarry = state.c
state.c = ((state.data & 0x80) != 0)
state.data = (state.data << 1) + (hasCarry ? 1 : 0)
}
internal func rolAbsolute() {
memory.writeByte(address, byte: state.data)
let hasCarry = state.c
state.c = ((state.data & 0x80) != 0)
state.data = (state.data << 1) + (hasCarry ? 1 : 0)
}
//MARK: ROR
internal func rorAccumulator() {
if idleReadImplied() {
let hasCarry = state.c
state.c = ((state.a & 1) != 0)
loadA((state.a >> 1) + (hasCarry ? 0x80 : 0))
state.cycle = 0
}
}
internal func rorZeroPage() {
memory.writeByte(UInt16(state.addressLow), byte: state.data)
let hasCarry = state.c
state.c = ((state.data & 1) != 0)
state.data = (state.data >> 1) + (hasCarry ? 0x80 : 0)
}
internal func rorAbsolute() {
memory.writeByte(address, byte: state.data)
let hasCarry = state.c
state.c = ((state.data & 1) != 0)
state.data = (state.data >> 1) + (hasCarry ? 0x80 : 0)
}
//MARK: RRA*
internal func rraZeroPage() {
rorZeroPage()
}
internal func rraZeroPage2() {
memory.writeByte(UInt16(state.addressLow), byte: state.data)
adc(state.data)
state.cycle = 0
}
internal func rraAbsolute() {
rorAbsolute()
}
internal func rraAbsolute2() {
memory.writeByte(address, byte: state.data)
adc(state.data)
state.cycle = 0
}
//MARK: RTI
internal func rtiImplied() {
if rdyLine.state {
let p = memory.readByte(0x100 &+ state.sp)
state.c = (p & 0x01 != 0)
state.z = (p & 0x02 != 0)
state.i = (p & 0x04 != 0)
state.d = (p & 0x08 != 0)
state.v = (p & 0x40 != 0)
state.n = (p & 0x80 != 0)
state.sp = state.sp &+ 1
} else {
state.cycle -= 1
}
}
internal func rtiImplied2() {
if rdyLine.state {
pcl = memory.readByte(0x100 &+ state.sp)
state.sp = state.sp &+ 1
} else {
state.cycle -= 1
}
}
internal func rtiImplied3() {
if rdyLine.state {
pch = memory.readByte(0x100 &+ state.sp)
state.cycle = 0
} else {
state.cycle -= 1
}
}
//MARK: RTS
internal func rtsImplied() {
if rdyLine.state {
pcl = memory.readByte(0x100 &+ state.sp)
state.sp = state.sp &+ 1
} else {
state.cycle -= 1
}
}
internal func rtsImplied2() {
if rdyLine.state {
pch = memory.readByte(0x100 &+ state.sp)
} else {
state.cycle -= 1
}
}
internal func rtsImplied3() {
state.pc += 1
state.cycle = 0
}
//MARK: SAX*
internal func saxZeroPage() {
state.data = state.a & state.x
memory.writeByte(UInt16(state.addressLow), byte: state.data)
state.cycle = 0
}
internal func saxAbsolute() {
state.data = state.a & state.x
memory.writeByte(address, byte: state.data)
state.cycle = 0
}
//MARK: SBC
internal func sbc(_ value: UInt8) {
if state.d {
let tempA = UInt16(state.a)
let sum = (tempA &- UInt16(value) &- (state.c ? 0 : 1))
var lowNybble = (state.a & 0x0F) &- (value & 0x0F) &- (state.c ? 0 : 1)
var highNybble = (state.a >> 4) &- (value >> 4)
if lowNybble & 0x10 != 0 {
lowNybble = lowNybble &- 6
highNybble = highNybble &- 1
}
if highNybble & 0x10 != 0 {
highNybble = highNybble &- 6
}
state.c = (sum < 0x100)
state.v = (((tempA ^ sum) & 0x80) != 0 && ((tempA ^ UInt16(value)) & 0x80) != 0)
state.z = (UInt8(truncatingIfNeeded: sum) == 0)
state.n = (sum & 0x80 != 0)
state.a = (highNybble << 4) | (lowNybble & 0x0F)
} else {
let tempA = UInt16(state.a)
let sum = (tempA &- UInt16(value) &- (state.c ? 0 : 1))
state.c = (sum <= 0xFF)
state.v = (((UInt16(state.a) ^ sum) & 0x80) != 0 && ((UInt16(state.a) ^ UInt16(value)) & 0x80) != 0)
loadA(UInt8(truncatingIfNeeded: sum))
}
}
internal func sbcImmediate() {
if loadDataImmediate() {
sbc(state.data)
state.cycle = 0
}
}
internal func sbcZeroPage() {
if loadDataZeroPage() {
sbc(state.data)
state.cycle = 0
}
}
internal func sbcPageBoundary() {
if loadDataAbsolute() {
if state.pageBoundaryCrossed {
state.addressHigh = state.addressHigh &+ 1
} else {
sbc(state.data)
state.cycle = 0
}
}
}
internal func sbcAbsolute() {
if loadDataAbsolute() {
sbc(state.data)
state.cycle = 0
}
}
//MARK: SBX*
internal func sbxImmediate() {
if loadDataImmediate() {
let value = state.a & state.x
let diff = value &- state.data
state.c = (value >= diff)
loadX(diff)
state.cycle = 0
}
}
//MARK: SEC
internal func secImplied() {
if idleReadImplied() {
state.c = true
state.cycle = 0
}
}
//MARK: SED
internal func sedImplied() {
if idleReadImplied() {
state.d = true
state.cycle = 0
}
}
//MARK: SEI
internal func seiImplied() {
if idleReadImplied() {
state.i = true
state.cycle = 0
}
}
//MARK: SHA*
internal func shaAbsolute() {
state.data = state.a & state.x & (state.addressHigh &+ 1)
memory.writeByte(address, byte: state.data)
if state.pageBoundaryCrossed {
state.addressHigh = state.data
}
state.cycle = 0
}
//MARK: SHS*
internal func shsAbsolute() {
if rdyLine.state {
memory.readByte(address)
state.sp = state.x & state.a
state.data = state.sp & (state.addressHigh &+ 1)
memory.writeByte(address, byte: state.data)
if state.pageBoundaryCrossed {
state.addressHigh = state.data
}
state.cycle = 0
} else {
state.cycle -= 1
}
}
//MARK: SHX*
internal func shxAbsolute() {
state.data = state.x & (state.addressHigh &+ 1)
memory.writeByte(address, byte: state.data)
if state.pageBoundaryCrossed {
state.addressHigh = state.data
}
state.cycle = 0
}
//MARK: SHY*
internal func shyAbsolute() {
state.data = state.y & (state.addressHigh &+ 1)
memory.writeByte(address, byte: state.data)
if state.pageBoundaryCrossed {
state.addressHigh = state.data
}
state.cycle = 0
}
//MARK: SLO*
internal func sloZeroPage() {
memory.writeByte(UInt16(state.addressLow), byte: state.data)
state.c = ((state.data & 0x80) != 0)
state.data <<= 1
}
internal func sloZeroPage2() {
memory.writeByte(UInt16(state.addressLow), byte: state.data)
loadA(state.a | state.data)
state.cycle = 0
}
internal func sloAbsolute() {
memory.writeByte(address, byte: state.data)
state.c = ((state.data & 0x80) != 0)
state.data <<= 1
}
internal func sloAbsolute2() {
memory.writeByte(address, byte: state.data)
loadA(state.a | state.data)
state.cycle = 0
}
//MARK: SRE*
internal func sreZeroPage() {
memory.writeByte(UInt16(state.addressLow), byte: state.data)
state.c = ((state.data & 0x01) != 0)
state.data >>= 1
}
internal func sreZeroPage2() {
memory.writeByte(UInt16(state.addressLow), byte: state.data)
loadA(state.a ^ state.data)
state.cycle = 0
}
internal func sreAbsolute() {
memory.writeByte(address, byte: state.data)
state.c = ((state.data & 0x01) != 0)
state.data >>= 1
}
internal func sreAbsolute2() {
memory.writeByte(address, byte: state.data)
loadA(state.a ^ state.data)
state.cycle = 0
}
//MARK: STA
internal func staZeroPage() {
state.data = state.a
memory.writeByte(UInt16(state.addressLow), byte: state.a)
state.cycle = 0
}
internal func staAbsolute() {
state.data = state.a
memory.writeByte(address, byte: state.data)
state.cycle = 0
}
//MARK: STX
internal func stxZeroPage() {
state.data = state.x
memory.writeByte(UInt16(state.addressLow), byte: state.data)
state.cycle = 0
}
internal func stxAbsolute() {
state.data = state.x
memory.writeByte(address, byte: state.data)
state.cycle = 0
}
//MARK: STY
internal func styZeroPage() {
state.data = state.y
memory.writeByte(UInt16(state.addressLow), byte: state.data)
state.cycle = 0
}
internal func styAbsolute() {
state.data = state.y
memory.writeByte(address, byte: state.data)
state.cycle = 0
}
//MARK: TAX
internal func taxImplied() {
if idleReadImplied() {
loadX(state.a)
state.cycle = 0
}
}
//MARK: TAY
internal func tayImplied() {
if idleReadImplied() {
loadY(state.a)
state.cycle = 0
}
}
//MARK: TSX
internal func tsxImplied() {
if idleReadImplied() {
loadX(state.sp)
state.cycle = 0
}
}
//MARK: TXA
internal func txaImplied() {
if idleReadImplied() {
loadA(state.x)
state.cycle = 0
}
}
//MARK: TXS
internal func txsImplied() {
if idleReadImplied() {
state.sp = state.x
state.cycle = 0
}
}
//MARK: TYA
internal func tyaImplied() {
if idleReadImplied() {
loadA(state.y)
state.cycle = 0
}
}
}
| mit | e4720d9a1a22d9eb874ba2b192aed544 | 23.221757 | 125 | 0.464905 | 3.928741 | false | false | false | false |
yigit26/YTSelectionPopupView | YTSelectionPopupView/Classes/YTSelectionPopupView.swift | 1 | 9576 | //
// YTSelectionPopupView.swift
// Pods
//
// Created by Yiğit Can Türe on 22/03/2017.
//
//
import UIKit
@objc public protocol YTSelectionPopupViewDataSource {
@objc func numberOfItems(in selectionView: YTSelectionPopupView) -> Int
@objc func titleForItem(in selectionView: YTSelectionPopupView, indexPath : IndexPath) -> String
}
@objc public protocol YTSelectionPopupViewDelegate {
/// Method
///
/// This method is only called when `optionSelectionType` is `.single` and 'optionDisplayStyle' is '.withoutTextField'.
///
///
/// - Parameters:
/// - selectionView: The selectionView that will be dismissed.
/// - item: Selected item.
/// - indexPath : Selected item's indexPath
@objc optional func singleItemSelected(in selectionView: YTSelectionPopupView, item :String, indexPath : IndexPath)
/// Method
///
/// This method is only called when -`optionSelectionType` : `.single` , 'optionDisplayStyle' : '.withTextField' - 'OK' button tapped..
///
///
/// - Parameters:
/// - selectionView: The selectionView that will be dismissed.
/// - item: Selected item.
/// - indexPath : Selected item's indexPath
/// - value : The value which is textfield.text
@objc optional func singleItemWithValueSelected(in selectionView: YTSelectionPopupView, item :String,value :String, indexPath : IndexPath)
/// Method
///
/// This method is only called when -`optionSelectionType` : `.multiple` , 'optionDisplayStyle' : '.withoutTextField' - 'OK' button tapped..
///
///
/// - Parameters:
/// - selectionView: The selectionView that will be dismissed.
/// - indexPaths: Selected items.
@objc optional func multipleSelectedIndexPaths(in selectionView:YTSelectionPopupView, indexPaths : Array<IndexPath>)
/// Method
///
/// This method is only called when -`optionSelectionType` : `.multiple` , 'optionDisplayStyle' : '.withTextField' - 'OK' button tapped..
///
///
/// - Parameters:
/// - selectionView: The selectionView that will be dismissed.
/// - items: Selected item's index,Value.
@objc optional func multipleItemsWithValuesSelected(in selectionView:YTSelectionPopupView, items : Dictionary<Int,String>)
}
@objc public enum YTSelectionPopupViewSelection: Int {
/// Single Selection.
case single
/// Multiple Selection.
case multiple
}
@objc public enum YTSelectionPopupViewDisplayStyle: Int {
/// Only item label
case withoutTextField
/// Item label and text field for value
case withTextField
}
open class YTSelectionPopupView: UIViewController, UITableViewDelegate, UITableViewDataSource {
open weak var dataSource: YTSelectionPopupViewDataSource?
open weak var delegate: YTSelectionPopupViewDelegate?
open var optionSelectionType: YTSelectionPopupViewSelection = .single
open var optionDisplayStyle: YTSelectionPopupViewDisplayStyle = .withoutTextField
open var optionBackgroundColor : UIColor = .blue
open var optionDoneButtonTintColor : UIColor = #colorLiteral(red: 0.8901960784, green: 0.9490196078, blue: 0.9921568627, alpha: 1)
open var optionCancelButtonTintColor : UIColor = #colorLiteral(red: 0.8901960784, green: 0.9490196078, blue: 0.9921568627, alpha: 1)
open var optionTitleColor : UIColor = #colorLiteral(red: 0.8901960784, green: 0.9490196078, blue: 0.9921568627, alpha: 1)
open var optionButtonTitleDone: String = "Done"
open var optionButtonTitleCancel: String = "Cancel"
open var optionPopupTitle: String = "Select"
@IBOutlet weak var backgroundView: UIView!
@IBOutlet fileprivate weak var tableView: UITableView!
@IBOutlet fileprivate weak var cancelButton: UIButton!
@IBOutlet fileprivate weak var okButton: UIButton!
@IBOutlet fileprivate weak var titleLabel: UILabel!
fileprivate var dictOfIndexesAndValues = Dictionary<Int,String>()
open static func instantiate() -> YTSelectionPopupView {
let podBundle = Bundle(for: self.classForCoder())
let bundleURL = podBundle.url(forResource: "YTSelectionPopupView", withExtension: "bundle")
var bundle: Bundle?
if let bundleURL = bundleURL {
bundle = Bundle(url: bundleURL)
}
return UIStoryboard(name: "YTSelectionPopupView", bundle: bundle).instantiateInitialViewController() as! YTSelectionPopupView
}
open override func awakeFromNib() {
super.awakeFromNib()
modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
modalTransitionStyle = UIModalTransitionStyle.crossDissolve
}
override open func viewDidLoad() {
super.viewDidLoad()
}
override open func viewWillAppear(_ animated: Bool) {
super.viewDidLoad()
self.prepareTitles()
self.prepareTable()
self.prepareBackgroundView()
}
fileprivate func prepareBackgroundView(){
self.backgroundView.layer.masksToBounds = false
self.backgroundView.layer.cornerRadius = 3.0
self.backgroundView.layer.shadowOpacity = 0.8
self.backgroundView.layer.shadowRadius = 3.0
self.backgroundView.layer.shadowOffset = CGSize(width:0.0, height:2.0)
self.backgroundView.layer.shadowColor = UIColor(red: 157/255, green: 157/255, blue: 157/255, alpha: 1.0).cgColor
self.backgroundView.backgroundColor = optionBackgroundColor
}
fileprivate func prepareTitles(){
self.okButton.setTitle(optionButtonTitleDone, for: .normal)
self.okButton.titleLabel?.textColor = optionDoneButtonTintColor
self.cancelButton.setTitle(optionButtonTitleCancel, for: .normal)
self.cancelButton.titleLabel?.textColor = optionCancelButtonTintColor
self.titleLabel.text = optionPopupTitle
self.titleLabel.textColor = optionTitleColor
}
fileprivate func prepareTable() {
self.tableView.delegate = self
self.tableView.dataSource = self
self.tableView.estimatedRowHeight = 40.0
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.allowsMultipleSelection = self.optionSelectionType == .multiple ? true : false
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let data = self.dataSource {
let title = data.titleForItem(in: self,indexPath: indexPath)
if let cell = tableView.dequeueReusableCell(withIdentifier: "YTSelectionCell", for: indexPath) as? YTSelectionCell {
cell.itemLabel?.text = title
if self.optionDisplayStyle == .withoutTextField {
cell.valueField.isHidden = true
}
return cell
}
return UITableViewCell()
}
return UITableViewCell()
}
public func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let data = self.dataSource {
return data.numberOfItems(in: self)
}
return 0
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) as? YTSelectionCell {
if self.optionSelectionType == .single && self.optionDisplayStyle == .withoutTextField {
self.delegate?.singleItemSelected!(in: self, item: cell.itemLabel.text!, indexPath: indexPath)
dismiss()
} else if self.optionSelectionType == .multiple && self.optionDisplayStyle == .withTextField {
dictOfIndexesAndValues[indexPath.row] = cell.valueField.text
}
}
}
public func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
if let index = dictOfIndexesAndValues.index(where: { (key, str) -> Bool in
key == indexPath.row
}){
dictOfIndexesAndValues.remove(at: index)
}
}
@IBAction func done(_ sender: UIButton) {
if let indexPaths = self.tableView.indexPathsForSelectedRows {
if self.optionSelectionType == .multiple {
if self.optionDisplayStyle == .withoutTextField {
self.delegate?.multipleSelectedIndexPaths!(in: self, indexPaths: indexPaths)
} else {
self.delegate?.multipleItemsWithValuesSelected!(in: self, items: dictOfIndexesAndValues)
}
} else {
let indexPath = indexPaths[0]
if let cell = self.tableView.cellForRow(at: indexPath) as? YTSelectionCell {
self.delegate?.singleItemWithValueSelected!(in: self, item: cell.itemLabel.text!, value: cell.valueField.text!, indexPath: indexPath)
}
}
}
dismiss()
}
@IBAction func cancel(_ sender: UIButton) {
dismiss()
}
fileprivate func dismiss() {
if let navigationController = self.navigationController {
navigationController.popViewController(animated: true)
} else if presentingViewController != nil {
dismiss(animated: true) {
}
}
}
}
| mit | 0ebac1c3ddb629decdf488453f5268dc | 38.237705 | 153 | 0.655943 | 5.065608 | false | false | false | false |
wangjianquan/wjq-weibo | weibo_wjq/Compose/PicPicker/PicPickerCollectionCell.swift | 1 | 1645 | //
// PicPickerCollectionCell.swift
// weibo_wjq
//
// Created by landixing on 2017/6/7.
// Copyright © 2017年 WJQ. All rights reserved.
//
import UIKit
@objc
protocol picCollectionCellDelegate : NSObjectProtocol {
@objc optional func picPickerViewCellWithaddPhotoBtnClick(_ cell : PicPickerCollectionCell)
@objc optional func PicPickerViewCellWithRemovePhotBtnClick(_ cell : PicPickerCollectionCell)
}
class PicPickerCollectionCell: UICollectionViewCell {
@IBOutlet var addBtn: UIButton!
@IBOutlet var picImage: UIImageView!
@IBOutlet var deleteBtn: UIButton!
weak var delegate: picCollectionCellDelegate?
var image: UIImage?
{
didSet {
picImage.image = image
picImage.contentMode = UIViewContentMode.scaleAspectFill
picImage.clipsToBounds = true
picImage.isHidden = image == nil
deleteBtn.isHidden = image == nil
addBtn.isUserInteractionEnabled = image == nil
}
}
override func awakeFromNib() {
super.awakeFromNib()
}
@IBAction func addBtnAction() {
if delegate?.responds(to: #selector(picCollectionCellDelegate.picPickerViewCellWithaddPhotoBtnClick(_:))) != nil {
delegate?.picPickerViewCellWithaddPhotoBtnClick!(self)
}
}
@IBAction func deleBtnAction() {
if delegate?.responds(to: #selector(picCollectionCellDelegate.PicPickerViewCellWithRemovePhotBtnClick(_:))) != nil {
delegate?.PicPickerViewCellWithRemovePhotBtnClick!(self)
}
}
}
| apache-2.0 | ee9971b2e54dc426ea421b0711610b9c | 21.805556 | 124 | 0.653471 | 5.083591 | false | false | false | false |
HJliu1123/LearningNotes-LHJ | April/HJNetworking/HJNetworking/HJHTTP.swift | 1 | 2292 | //
// HJHTTP.swift
// HJNetworking
//
// Created by liuhj on 16/4/5.
// Copyright © 2016年 liuhj. All rights reserved.
//
import UIKit
enum RequestMethod {
case Post
case Get
}
typealias aht = HJHTTP
class HJHTTP: NSObject {
private var method : RequestMethod
private let hostName = ""
private var curUrl = ""
private var parameters : [String : AnyObject] = [ : ]
static let shareInstance = HJHTTP(m : .Get)
init(m : RequestMethod) {
method = m
super.init()
setDefaultParas()
}
private func setDefaultParas() {
self.parameters = [ : ]
_ = defaultParameter().reduce("",combine :{(str, p) ->String in
self.parameters[p.0] = p.1
return ""
})
}
func fetch(url : String) ->HJHTTP {
setDefaultParas()
curUrl = "\(hostName)\(url)"
self.method = .Get
return self
}
func post(url : String) ->HJHTTP {
setDefaultParas()
curUrl = "\(hostName)\(url)"
self.method = .Post
return self
}
func paras(p : [String : AnyObject]) ->HJHTTP {
_ = p.reduce("") { (str, p) -> String in
parameters[p.0] = p.1
return ""
}
return self
}
func go(success : String ->Void, failure : NSError? ->Void) {
var smethod = ""
if method == .Get {
smethod = "GET"
} else {
smethod = "POST"
}
HJNet.request(smethod, url: curUrl, from: parameters, success: { (data) -> Void in
print("request successed in \(self.curUrl)")
let result = String(data: data!, encoding: NSUTF8StringEncoding)
success(result!)
}) { (error) -> Void in
print("request failed in \(self.curUrl)")
failure(error)
}
}
func defaultParameter() ->[String : AnyObject] {
var result : [String : AnyObject] = [ : ]
let version = NSBundle.mainBundle().infoDictionary!["CFBundleVersion"]
result["version"] = version
result["app_type"] = "HJNetworking"
return result
}
}
| apache-2.0 | 858048236a1db3c0e29658bb39f681f3 | 21.89 | 90 | 0.502403 | 4.318868 | false | false | false | false |
idoru/cedar | Spec/Swift/SwiftSpec.swift | 4 | 6273 | import Cedar
#if !EXCLUDE_SWIFT_SPECS
/// A very simple function for making assertions since Cedar provides no
/// matchers usable from Swift
private func expectThat(value: Bool, file: String = __FILE__, line: UInt = __LINE__) {
if !value {
CDRSpecFailure.specFailureWithReason("Expectation failed", fileName: file, lineNumber: Int32(line)).raise()
}
}
private var globalValue__: String?
/// This mirrors `SpecSpec`
class SwiftSpecSpec: CDRSpec {
override func declareBehaviors() {
describe("SwiftSpec") {
beforeEach {
// NSLog("=====================> I should run before all specs.")
}
afterEach {
// NSLog("=====================> I should run after all specs.")
}
describe("a nested spec") {
beforeEach {
// NSLog("=====================> I should run only before the nested specs.")
}
afterEach {
// NSLog("=====================> I should run only after the nested specs.")
}
it("should also run") {
// NSLog("=====================> Nested spec")
}
it("should also also run") {
// NSLog("=====================> Another nested spec")
}
}
context("a nested spec (context)") {
beforeEach {
// NSLog("=====================> I should run only before the nested specs.")
}
afterEach {
// NSLog("=====================> I should run only after the nested specs.")
}
it("should also run") {
// NSLog("=====================> Nested spec")
}
it("should also also run") {
// NSLog("=====================> Another nested spec")
}
}
it("should run") {
// NSLog("=====================> Spec")
}
it("should be pending", PENDING)
it("should also be pending", nil)
xit("should also be pending (xit)") {}
describe("described specs should be pending", PENDING)
describe("described specs should also be pending", nil)
xdescribe("xdescribed specs should be pending") {}
context("contexted specs should be pending", PENDING)
context("contexted specs should also be pending", nil)
xcontext("xcontexted specs should be pending") {};
describe("empty describe blocks should be pending") {}
context("empty context blocks should be pending") {}
}
describe("subjectAction") {
var value: Int = 0
subjectAction { value = 5 }
beforeEach {
value = 100
}
it("should run after the beforeEach") {
expectThat(value == 5)
}
describe("in a nested describe block") {
beforeEach {
value = 200
}
it("should run after all the beforeEach blocks") {
expectThat(value == 5)
}
}
}
describe("a describe block") {
beforeEach {
globalValue__ = nil
}
describe("that contains a beforeEach in a shared example group") {
itShouldBehaveLike("a describe context that contains a beforeEach in a Swift shared example group")
it("should not run the shared beforeEach before specs outside the shared example group") {
expectThat(globalValue__ == nil)
}
}
describe("that passes a value to the shared example context") {
beforeEach {
globalValue__ = "something"
CDRSpecHelper.specHelper().sharedExampleContext["value"] = globalValue__
}
itShouldBehaveLike("a Swift shared example group that receives a value in the context")
}
describe("that passes a value in-line to the shared example context") {
beforeEach {
globalValue__ = "something"
}
expectThat(globalValue__ == nil)
itShouldBehaveLike("a Swift shared example group that receives a value in the context") {
$0["value"] = globalValue__
}
}
itShouldBehaveLike("a Swift shared example group that contains a failing spec")
}
describe("a describe block that tries to include a shared example group that doesn't exist") {
expectExceptionWithReason("Unknown shared example group with description: 'a unicorn'") {
itShouldBehaveLike("a unicorn")
}
}
}
}
class SharedExampleGroupPoolForSwiftSpecs: CDRSharedExampleGroupPool {
override func declareSharedExampleGroups() {
sharedExamplesFor("a describe context that contains a beforeEach in a Swift shared example group") { _ in
beforeEach {
expectThat(CDRSpecHelper.specHelper().sharedExampleContext.count == 0)
globalValue__ = ""
}
it("should run the shared beforeEach before specs inside the shared example group") {
expectThat(globalValue__ != nil)
}
}
sharedExamplesFor("a Swift shared example group that receives a value in the context") { context in
it("should receive the values set in the global shared example context") {
expectThat((context["value"] as? String) == globalValue__)
}
}
sharedExamplesFor("a Swift shared example group that contains a failing spec") { _ in
it("should fail in the expected fashion") {
expectFailureWithMessage("Expectation failed") {
expectThat("wibble" == "wobble")
}
}
}
}
}
#endif
| mit | 48209dd9a477dc32258dbeab4d1c3b36 | 33.85 | 115 | 0.494819 | 5.464286 | false | false | false | false |
trashkalmar/omim | iphone/Maps/Classes/Components/RatingView/RatingView.swift | 1 | 17832 | import UIKit
@IBDesignable final class RatingView: UIView {
@IBInspectable var value: CGFloat = RatingViewSettings.Default.value {
didSet {
guard oldValue != value else { return }
let clamped = min(CGFloat(settings.starsCount), max(0, value))
if clamped == value {
update()
} else {
value = clamped
}
}
}
@IBInspectable var leftText: String? {
get { return texts[.left] }
set { texts[.left] = newValue }
}
@IBInspectable var leftTextColor: UIColor {
get { return settings.textColors[.left]! }
set {
settings.textColors[.left] = newValue
update()
}
}
var leftTextFont: UIFont {
get { return settings.textFonts[.left]! }
set {
settings.textFonts[.left] = newValue
update()
}
}
@IBInspectable var leftTextSize: CGFloat {
get { return settings.textSizes[.left]! }
set {
settings.textSizes[.left] = newValue
update()
}
}
@IBInspectable var leftTextMargin: CGFloat {
get { return settings.textMargins[.left]! }
set {
settings.textMargins[.left] = newValue
update()
}
}
@IBInspectable var rightText: String? {
get { return texts[.right] }
set { texts[.right] = newValue }
}
@IBInspectable var rightTextColor: UIColor {
get { return settings.textColors[.right]! }
set {
settings.textColors[.right] = newValue
update()
}
}
var rightTextFont: UIFont {
get { return settings.textFonts[.right]! }
set {
settings.textFonts[.right] = newValue
update()
}
}
@IBInspectable var rightTextSize: CGFloat {
get { return settings.textSizes[.right]! }
set {
settings.textSizes[.right] = newValue
update()
}
}
@IBInspectable var rightTextMargin: CGFloat {
get { return settings.textMargins[.right]! }
set {
settings.textMargins[.right] = newValue
update()
}
}
@IBInspectable var topText: String? {
get { return texts[.top] }
set { texts[.top] = newValue }
}
@IBInspectable var topTextColor: UIColor {
get { return settings.textColors[.top]! }
set {
settings.textColors[.top] = newValue
update()
}
}
var topTextFont: UIFont {
get { return settings.textFonts[.top]! }
set {
settings.textFonts[.top] = newValue
update()
}
}
@IBInspectable var topTextSize: CGFloat {
get { return settings.textSizes[.top]! }
set {
settings.textSizes[.top] = newValue
update()
}
}
@IBInspectable var topTextMargin: CGFloat {
get { return settings.textMargins[.top]! }
set {
settings.textMargins[.top] = newValue
update()
}
}
@IBInspectable var bottomText: String? {
get { return texts[.bottom] }
set { texts[.bottom] = newValue }
}
@IBInspectable var bottomTextColor: UIColor {
get { return settings.textColors[.bottom]! }
set {
settings.textColors[.bottom] = newValue
update()
}
}
var bottomTextFont: UIFont {
get { return settings.textFonts[.bottom]! }
set {
settings.textFonts[.bottom] = newValue
update()
}
}
@IBInspectable var bottomTextSize: CGFloat {
get { return settings.textSizes[.bottom]! }
set {
settings.textSizes[.bottom] = newValue
update()
}
}
@IBInspectable var bottomTextMargin: CGFloat {
get { return settings.textMargins[.bottom]! }
set {
settings.textMargins[.bottom] = newValue
update()
}
}
private var texts: [RatingViewSettings.TextSide: String] = [:] {
didSet { update() }
}
@IBInspectable var starType: Int {
get { return settings.starType.rawValue }
set {
settings.starType = RatingViewSettings.StarType(rawValue: newValue) ?? RatingViewSettings.Default.starType
settings.starPoints = RatingViewSettings.Default.starPoints[settings.starType]!
update()
}
}
@IBInspectable var starsCount: Int {
get { return settings.starsCount }
set {
settings.starsCount = newValue
update()
}
}
@IBInspectable var starSize: CGFloat {
get { return settings.starSize }
set {
settings.starSize = newValue
update()
}
}
@IBInspectable var starMargin: CGFloat {
get { return settings.starMargin }
set {
settings.starMargin = newValue
update()
}
}
@IBInspectable var filledColor: UIColor {
get { return settings.filledColor }
set {
settings.filledColor = newValue
update()
}
}
@IBInspectable var emptyColor: UIColor {
get { return settings.emptyColor }
set {
settings.emptyColor = newValue
update()
}
}
@IBInspectable var emptyBorderColor: UIColor {
get { return settings.emptyBorderColor }
set {
settings.emptyBorderColor = newValue
update()
}
}
@IBInspectable var borderWidth: CGFloat {
get { return settings.borderWidth }
set {
settings.borderWidth = newValue
update()
}
}
@IBInspectable var filledBorderColor: UIColor {
get { return settings.filledBorderColor }
set {
settings.filledBorderColor = newValue
update()
}
}
@IBInspectable var fillMode: Int {
get { return settings.fillMode.rawValue }
set {
settings.fillMode = RatingViewSettings.FillMode(rawValue: newValue) ?? RatingViewSettings.Default.fillMode
update()
}
}
@IBInspectable var minTouchRating: CGFloat {
get { return settings.minTouchRating }
set {
settings.minTouchRating = newValue
update()
}
}
@IBInspectable var filledImage: UIImage? {
get { return settings.filledImage }
set {
settings.filledImage = newValue
update()
}
}
@IBInspectable var emptyImage: UIImage? {
get { return settings.emptyImage }
set {
settings.emptyImage = newValue
update()
}
}
@IBOutlet weak var delegate: RatingViewDelegate?
var settings = RatingViewSettings() {
didSet {
update()
}
}
private let isRightToLeft = UIApplication.shared.userInterfaceLayoutDirection == .rightToLeft
public override func awakeFromNib() {
super.awakeFromNib()
setup()
update()
}
public convenience init() {
self.init(frame: CGRect())
}
public override init(frame: CGRect) {
super.init(frame: frame)
setup()
update()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
update()
}
private func setup() {
layer.backgroundColor = UIColor.clear.cgColor
isOpaque = true
}
private var viewSize = CGSize()
private var scheduledUpdate: DispatchWorkItem?
func updateImpl() {
let layers = createLayers()
layer.sublayers = layers
viewSize = calculateSizeToFitLayers(layers)
invalidateIntrinsicContentSize()
frame.size = intrinsicContentSize
}
func update() {
scheduledUpdate?.cancel()
scheduledUpdate = DispatchWorkItem { [weak self] in self?.updateImpl() }
DispatchQueue.main.async(execute: scheduledUpdate!)
}
override var intrinsicContentSize: CGSize {
return viewSize
}
private func createLayers() -> [CALayer] {
return combineLayers(starLayers: createStarLayers(), textLayers: createTextLayers())
}
private func combineLayers(starLayers: [CALayer], textLayers: [RatingViewSettings.TextSide: CALayer]) -> [CALayer] {
var layers = starLayers
var starsWidth: CGFloat = 0
layers.forEach { starsWidth = max(starsWidth, $0.position.x + $0.bounds.width) }
if let topTextLayer = textLayers[.top] {
topTextLayer.position = CGPoint()
var topTextLayerSize = topTextLayer.bounds.size
topTextLayerSize.width = max(topTextLayerSize.width, starsWidth)
topTextLayer.bounds.size = topTextLayerSize
let y = topTextLayer.position.y + topTextLayer.bounds.height + topTextMargin
layers.forEach { $0.position.y += y }
}
if let bottomTextLayer = textLayers[.bottom] {
bottomTextLayer.position = CGPoint()
var bottomTextLayerSize = bottomTextLayer.bounds.size
bottomTextLayerSize.width = max(bottomTextLayerSize.width, starsWidth)
bottomTextLayer.bounds.size = bottomTextLayerSize
let star = layers.first!
bottomTextLayer.position.y = star.position.y + star.bounds.height + bottomTextMargin
}
let leftTextLayer: CALayer?
let leftMargin: CGFloat
let rightTextLayer: CALayer?
let rightMargin: CGFloat
if isRightToLeft {
leftTextLayer = textLayers[.right]
leftMargin = rightTextMargin
rightTextLayer = textLayers[.left]
rightMargin = leftTextMargin
} else {
leftTextLayer = textLayers[.left]
leftMargin = leftTextMargin
rightTextLayer = textLayers[.right]
rightMargin = rightTextMargin
}
if let leftTextLayer = leftTextLayer {
leftTextLayer.position = CGPoint()
let star = layers.first!
leftTextLayer.position.y = star.position.y + (star.bounds.height - leftTextLayer.bounds.height) / 2
let x = leftTextLayer.position.x + leftTextLayer.bounds.width + leftMargin
layers.forEach { $0.position.x += x }
textLayers[.top]?.position.x += x
textLayers[.bottom]?.position.x += x
}
if let rightTextLayer = rightTextLayer {
rightTextLayer.position = CGPoint()
let star = layers.last!
rightTextLayer.position = CGPoint(x: star.position.x + star.bounds.width + rightMargin,
y: star.position.y + (star.bounds.height - rightTextLayer.bounds.height) / 2)
}
layers.append(contentsOf: textLayers.values)
return layers
}
private func createStarLayers() -> [CALayer] {
var ratingRemainder = value
var starLayers: [CALayer] = (0 ..< settings.starsCount).map { _ in
let fillLevel = starFillLevel(ratingRemainder: ratingRemainder)
let layer = createCompositeStarLayer(fillLevel: fillLevel)
ratingRemainder -= 1
return layer
}
if isRightToLeft {
starLayers.reverse()
}
positionStarLayers(starLayers)
return starLayers
}
private func positionStarLayers(_ layers: [CALayer]) {
var positionX: CGFloat = 0
layers.forEach {
$0.position.x = positionX
positionX += $0.bounds.width + settings.starMargin
}
}
private func createTextLayers() -> [RatingViewSettings.TextSide: CALayer] {
var layers: [RatingViewSettings.TextSide: CALayer] = [:]
for (side, text) in texts {
let font = settings.textFonts[side]!.withSize(settings.textSizes[side]!)
let size = NSString(string: text).size(withAttributes: [NSAttributedStringKey.font: font])
let layer = CATextLayer()
layer.bounds = CGRect(origin: CGPoint(),
size: CGSize(width: ceil(size.width), height: ceil(size.height)))
layer.anchorPoint = CGPoint()
layer.string = text
layer.font = CGFont(font.fontName as CFString)
layer.fontSize = font.pointSize
layer.foregroundColor = settings.textColors[side]!.cgColor
layer.contentsScale = UIScreen.main.scale
layers[side] = layer
}
return layers
}
private func starFillLevel(ratingRemainder: CGFloat) -> CGFloat {
guard ratingRemainder < 1 else { return 1 }
guard ratingRemainder > 0 else { return 0 }
switch settings.fillMode {
case .full: return round(ratingRemainder)
case .half: return round(ratingRemainder * 2) / 2
case .precise: return ratingRemainder
}
}
private func calculateSizeToFitLayers(_ layers: [CALayer]) -> CGSize {
var size = CGSize()
layers.forEach { layer in
size.width = max(size.width, layer.frame.maxX)
size.height = max(size.height, layer.frame.maxY)
}
return size
}
private func createCompositeStarLayer(fillLevel: CGFloat) -> CALayer {
guard fillLevel > 0 && fillLevel < 1 else { return createStarLayer(fillLevel >= 1) }
return createPartialStar(fillLevel: fillLevel)
}
func createPartialStar(fillLevel: CGFloat) -> CALayer {
let filledStar = createStarLayer(true)
let emptyStar = createStarLayer(false)
let parentLayer = CALayer()
parentLayer.contentsScale = UIScreen.main.scale
parentLayer.bounds = filledStar.bounds
parentLayer.anchorPoint = CGPoint()
parentLayer.addSublayer(emptyStar)
parentLayer.addSublayer(filledStar)
if isRightToLeft {
let rotation = CATransform3DMakeRotation(CGFloat.pi, 0, 1, 0)
filledStar.transform = CATransform3DTranslate(rotation, -filledStar.bounds.size.width, 0, 0)
}
filledStar.bounds.size.width *= fillLevel
return parentLayer
}
private func createStarLayer(_ isFilled: Bool) -> CALayer {
let size = settings.starSize
let containerLayer = createContainerLayer(size)
if let image = isFilled ? settings.filledImage : settings.emptyImage {
let imageLayer = createContainerLayer(size)
imageLayer.frame = containerLayer.bounds
imageLayer.contents = image.cgImage
imageLayer.contentsGravity = kCAGravityResizeAspect
if image.renderingMode == .alwaysTemplate {
containerLayer.mask = imageLayer
containerLayer.backgroundColor = (isFilled ? settings.filledColor : settings.emptyColor).cgColor
} else {
containerLayer.addSublayer(imageLayer)
}
} else {
let fillColor = isFilled ? settings.filledColor : settings.emptyColor
let strokeColor = isFilled ? settings.filledBorderColor : settings.emptyBorderColor
let lineWidth = settings.borderWidth
let path = createStarPath(settings.starPoints, size: size, lineWidth: lineWidth)
let shapeLayer = createShapeLayer(path.cgPath,
lineWidth: lineWidth,
fillColor: fillColor,
strokeColor: strokeColor,
size: size)
containerLayer.addSublayer(shapeLayer)
}
return containerLayer
}
private func createContainerLayer(_ size: CGFloat) -> CALayer {
let layer = CALayer()
layer.contentsScale = UIScreen.main.scale
layer.anchorPoint = CGPoint()
layer.masksToBounds = true
layer.bounds.size = CGSize(width: size, height: size)
layer.isOpaque = true
return layer
}
private func createShapeLayer(_ path: CGPath, lineWidth: CGFloat, fillColor: UIColor, strokeColor: UIColor, size: CGFloat) -> CALayer {
let layer = CAShapeLayer()
layer.anchorPoint = CGPoint()
layer.contentsScale = UIScreen.main.scale
layer.strokeColor = strokeColor.cgColor
layer.fillRule = kCAFillRuleEvenOdd
layer.fillColor = fillColor.cgColor
layer.lineWidth = lineWidth
layer.lineJoin = kCALineJoinRound
layer.lineCap = kCALineCapRound
layer.bounds.size = CGSize(width: size, height: size)
layer.masksToBounds = true
layer.path = path
layer.isOpaque = true
return layer
}
private func createStarPath(_ starPoints: [CGPoint], size: CGFloat, lineWidth: CGFloat) -> UIBezierPath {
let sizeWithoutLineWidth = size - lineWidth * 2
let factor = sizeWithoutLineWidth / RatingViewSettings.Default.starPointsBoxSize
let points = starPoints.map { CGPoint(x: $0.x * factor + lineWidth,
y: $0.y * factor + lineWidth) }
let path: UIBezierPath
switch settings.starType {
case .regular:
path = UIBezierPath()
case .boxed:
path = UIBezierPath(roundedRect: CGRect(origin: CGPoint(), size: CGSize(width: size, height: size)), cornerRadius: size / 4)
}
path.move(to: points.first!)
points[1 ..< points.count].forEach { path.addLine(to: $0) }
path.close()
return path
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
updateImpl()
}
private func touchLocationFromBeginningOfRating(_ touches: Set<UITouch>) -> CGFloat? {
guard let touch = touches.first else { return nil }
var location = touch.location(in: self).x
let starLayers = layer.sublayers?.filter { !($0 is CATextLayer) }
var minX = bounds.width
var maxX: CGFloat = 0
starLayers?.forEach {
maxX = max(maxX, $0.position.x + $0.bounds.width)
minX = min(minX, $0.position.x)
}
assert(minX <= maxX)
if isRightToLeft {
location = maxX - location
} else {
location = location - minX
}
return location
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
guard let location = touchLocationFromBeginningOfRating(touches) else { return }
onDidTouch(location)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesMoved(touches, with: event)
guard let location = touchLocationFromBeginningOfRating(touches) else { return }
onDidTouch(location)
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
delegate?.didFinishTouchingRatingView(self)
}
private func onDidTouch(_ location: CGFloat) {
guard let delegate = delegate else { return }
let prevRating = value
let starsCount = CGFloat(settings.starsCount)
let startsLength = settings.starSize * starsCount + (settings.starMargin * (starsCount - 1))
let percent = location / startsLength
let preciseRating = percent * starsCount
let fullStarts = floor(preciseRating)
let fractionRating = starFillLevel(ratingRemainder: preciseRating - fullStarts)
value = max(minTouchRating, fullStarts + fractionRating)
if prevRating != value {
delegate.didTouchRatingView(self)
}
}
}
| apache-2.0 | c1d4dbb468ee066c614c506ff3f55f1c | 27.440191 | 137 | 0.660722 | 4.412769 | false | false | false | false |
jamy0801/LGWeChatKit | LGWeChatKit/LGChatKit/conversion/video/LGRecordVideoView.swift | 1 | 6489 | //
// LGRecordView.swift
// record
//
// Created by jamy on 11/6/15.
// Copyright © 2015 jamy. All rights reserved.
// 该模块未使用autolayout
import UIKit
import AVFoundation
private let buttonW: CGFloat = 60
class LGRecordVideoView: UIView {
var videoView: UIView!
var indicatorView: UILabel!
var recordButton: UIButton!
var progressView: UIProgressView!
var progressView2: UIProgressView!
var recordVideoModel: LGRecordVideoModel!
var preViewLayer: AVCaptureVideoPreviewLayer!
var recordTimer: NSTimer!
override init(frame: CGRect) {
super.init(frame: frame)
customInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
customInit()
}
func customInit() {
backgroundColor = UIColor.blackColor()
if TARGET_IPHONE_SIMULATOR == 1 {
NSLog("simulator can't do this!!!")
} else {
recordVideoModel = LGRecordVideoModel()
videoView = UIView(frame: CGRectMake(0, 0, bounds.width, bounds.height * 0.7))
videoView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
addSubview(videoView)
preViewLayer = AVCaptureVideoPreviewLayer(session: recordVideoModel.captureSession)
preViewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
preViewLayer.frame = videoView.bounds
videoView.layer.insertSublayer(preViewLayer, atIndex: 0)
recordButton = UIButton(type: .Custom)
recordButton.setTitleColor(UIColor.orangeColor(), forState: .Normal)
recordButton.layer.cornerRadius = buttonW / 2
recordButton.layer.borderWidth = 1.5
recordButton.layer.borderColor = UIColor.orangeColor().CGColor
recordButton.setTitle("按住拍", forState: .Normal)
recordButton.addTarget(self, action: "buttonTouchDown", forControlEvents: .TouchDown)
recordButton.addTarget(self, action: "buttonDragOutside", forControlEvents: .TouchDragOutside)
recordButton.addTarget(self, action: "buttonCancel", forControlEvents: .TouchUpOutside)
recordButton.addTarget(self, action: "buttonTouchUp", forControlEvents: .TouchUpInside)
addSubview(recordButton)
progressView = UIProgressView(frame: CGRectZero)
progressView.progressTintColor = UIColor.blackColor()
progressView.trackTintColor = UIColor.orangeColor()
progressView.hidden = true
addSubview(progressView)
progressView2 = UIProgressView(frame: CGRectZero)
progressView2.progressTintColor = UIColor.blackColor()
progressView2.trackTintColor = UIColor.orangeColor()
progressView2.hidden = true
addSubview(progressView2)
progressView2.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
indicatorView = UILabel()
indicatorView.textColor = UIColor.whiteColor()
indicatorView.font = UIFont.systemFontOfSize(12.0)
indicatorView.backgroundColor = UIColor.redColor()
indicatorView.hidden = true
addSubview(indicatorView)
recordButton.bounds = CGRectMake(0, 0, buttonW, buttonW)
recordButton.center = CGPointMake(center.x, videoView.frame.height + buttonW)
progressView.frame = CGRectMake(0, videoView.frame.height, bounds.width / 2, 2)
progressView2.frame = CGRectMake(bounds.width / 2 - 1, videoView.frame.height, bounds.width / 2 + 1, 2)
indicatorView.center = CGPointMake(center.x, videoView.frame.height - 20)
indicatorView.bounds = CGRectMake(0, 0, 50, 20)
}
}
override func willMoveToSuperview(newSuperview: UIView?) {
super.willMoveToSuperview(newSuperview)
if TARGET_IPHONE_SIMULATOR == 0 {
recordVideoModel.start()
}
}
func buttonTouchDown() {
UIView.animateWithDuration(0.2, animations: { () -> Void in
self.recordButton.transform = CGAffineTransformMakeScale(1.5, 1.5)
}) { (finish) -> Void in
self.recordButton.hidden = true
}
recordVideoModel.beginRecord()
stopTimer()
self.progressView.hidden = false
self.progressView2.hidden = false
indicatorView.hidden = false
indicatorView.text = "上移取消"
recordTimer = NSTimer(timeInterval: 1.0, target: self, selector: "recordTimerUpdate", userInfo: nil, repeats: true)
NSRunLoop.mainRunLoop().addTimer(recordTimer, forMode: NSRunLoopCommonModes)
}
func buttonDragOutside() {
indicatorView.hidden = false
indicatorView.text = "松手取消"
}
func buttonCancel() {
UIView.animateWithDuration(0.2, animations: { () -> Void in
self.recordButton.hidden = false
self.recordButton.transform = CGAffineTransformIdentity
}) { (finish) -> Void in
self.indicatorView.hidden = true
self.progressView.hidden = true
self.progressView.progress = 0
self.progressView2.hidden = true
self.progressView2.progress = 0
self.stopTimer()
}
recordVideoModel.cancelRecord()
}
func buttonTouchUp() {
UIView.animateWithDuration(0.2, animations: { () -> Void in
self.recordButton.hidden = false
self.recordButton.transform = CGAffineTransformIdentity
}) { (finish) -> Void in
self.indicatorView.hidden = true
self.progressView.hidden = true
self.progressView.progress = 0
self.progressView2.hidden = true
self.progressView2.progress = 0
self.stopTimer()
}
recordVideoModel.complectionRecord()
}
func stopTimer() {
if recordTimer != nil {
recordTimer.invalidate()
recordTimer = nil
}
}
func recordTimerUpdate() {
if progressView.progress == 1 {
buttonTouchUp()
} else {
progressView.progress += 0.1
progressView2.progress += 0.1
}
}
}
| mit | b612a3af2e62cd259209c30aed299261 | 36.74269 | 123 | 0.612333 | 5.264274 | false | false | false | false |
ahayman/RxStream | RxStream/Stream Operations/ColdOperations.swift | 1 | 33689 | //
// ColdOperations.swift
// RxStream
//
// Created by Aaron Hayman on 3/16/17.
// Copyright © 2017 Aaron Hayman. All rights reserved.
//
import Foundation
extension Cold {
/**
## Branching
This will map an upstream Request to a new Request type so that down stream client can use a different Request.
Because Requests travel upstream, the mapper must map the from the new Type to the original Request type.
- parameter mapper: Maps the new Type to the upstreamd Request type.
- returns: A new Cold stream
*/
public func mapRequest<U>(_ mapper: @escaping (U) -> Request) -> Cold<U, Response> {
return appendNewStream(stream: newMappedRequestStream(mapper: mapper))
}
/**
## Branching
This will call the handler when the stream receives a _non-terminating_ error.
- parameter handler: Handler will be called when an error is received.
- parameter error: The error thrown by the stream
- returns: a new Cold stream
*/
@discardableResult public func onError(_ handler: @escaping (_ error: Error) -> Void) -> Cold<Request, Response> {
return appendOnError(stream: newSubStream("onError"), handler: handler)
}
/**
## Branching
This will call the handler when the stream receives a _non-terminating_ error.
The handler can optionally return a Termination, which will cause the stream to terminate.
- parameter handler: Receives an error and can optionally return a Termination. If `nil` is returned, the stream will continue to be active.
- parameter error: The error thrown by the stream
- returns: a new Cold stream
*/
@discardableResult public func mapError(_ handler: @escaping (_ error: Error) -> Termination?) -> Cold<Request, Response> {
return appendMapError(stream: newSubStream("mapError"), handler: handler)
}
/**
## Branching
Attach a simple observation handler to the stream to observe new values.
- parameter handler: The handler used to observe new values.
- parameter value: The next value in the stream
- returns: A new Cold stream
*/
@discardableResult public func on(_ handler: @escaping (_ value: Response) -> Void) -> Cold<Request, Response> {
return appendOn(stream: newSubStream("on"), handler: handler)
}
/**
## Branching
Attach an observation handler to the stream to observe transitions to new values. The handler includes the old value (if any) along with the new one.
- parameter handler: The handler used to observe transitions between values.
- parameter prior: The last value emitted from the stream
- parameter next: The next value in the stream
- returns: A new Cold Stream
*/
@discardableResult public func onTransition(_ handler: @escaping (_ prior: Response?, _ next: Response) -> Void) -> Cold<Request, Response> {
return appendTransition(stream: newSubStream("onTransition"), handler: handler)
}
/**
## Branching
Attach an observation handler to observe termination events for the stream.
- parameter handler: The handler used to observe the stream's termination.
- returns: A new Cold Stream
*/
@discardableResult public func onTerminate(_ handler: @escaping (Termination) -> Void) -> Cold<Request, Response> {
return appendOnTerminate(stream: newSubStream("onTerminate"), handler: handler)
}
/**
## Branching
Map values in the current stream to new values returned in a new stream.
- note: The mapper returns an optional type. If the mapper returns `nil`, nothing will be passed down the stream, but the stream will continue to remain active.
- parameter mapper: The handler to map the current type to a new type.
- parameter value: The current value in the stream
- returns: A new Cold Stream
*/
@discardableResult public func map<U>(_ mapper: @escaping (_ value: Response) -> U?) -> Cold<Request, U> {
let stream: Cold<Request, U> = newSubStream("map<\(String(describing: Response.self))>")
return appendMap(stream: stream, withMapper: mapper)
}
/**
## Branching
Map values in the current stream to new values returned in a new stream.
The mapper returns a result type that can return an error or a mapped value.
- parameter mapper: The handler to map the current value either to a new value or an error.
- parameter value: The current value in the stream
- returns: A new Cold Stream
*/
@discardableResult public func resultMap<U>(_ mapper: @escaping (_ value: Response) -> Result<U>) -> Cold<Request, U> {
let stream: Cold<Request, U> = newSubStream("resultMap<\(String(describing: Response.self))>")
return appendMap(stream: stream, withMapper: mapper)
}
/**
## Branching
Map values _asynchronously_ to either a new value, or else an error.
The handler should take the current value along with a completion handler.
Once ready, the completion handler should be called with:
- New Value: New values will be passed down stream
- Error: An error will be passed down stream. If you wish the error to terminate, add `onError` down stream and return a termination for it.
- `nil`: Passing `nil` into will complete the handler but pass nothing down stream.
- warning: The completion handler must _always_ be called, even if it's called with `nil`. Failing to call the completion handler will block the stream, prevent it from being terminated, and will result in memory leakage.
- parameter mapper: The mapper takes a value and a comletion handler.
- parameter value: The current value in the stream
- parameter completion: The completion handler; takes an optional Result type passed in. _Must always be called only once_.
- returns: A new Cold Stream
*/
@discardableResult public func asyncMap<U>(_ mapper: @escaping (_ value: Response, _ completion: @escaping (Result<U>?) -> Void) -> Void) -> Cold<Request, U> {
let stream: Cold<Request, U> = newSubStream("asyncMap<\(String(describing: Response.self))>")
return appendMap(stream: stream, withMapper: mapper)
}
/**
## Branching
Map values to an array of values that are emitted sequentially in a new stream.
- parameter mapper: The mapper should take a value and map it to an array of new values. The array of values will be emitted sequentially in the returned stream.
- parameter value: The next value in the stream.
- returns: A new Cold Stream
*/
@discardableResult public func flatMap<U>(_ mapper: @escaping (_ value: Response) -> [U]) -> Cold<Request, U> {
let stream: Cold<Request, U> = newSubStream("flatMap<\(String(describing: Response.self))>")
return appendFlatMap(stream: stream, withFlatMapper: mapper)
}
/**
## Branching
Take an initial current value and pass it into the handler, which should return a new value.
This value is passed down stream and used as the new current value that will be passed into the handler when the next value is received.
This is similar to the functional type `reduce` except each calculation is passed down stream.
As an example, you could use this function to create a running balance of the values passed down (by adding `current` to `next`).
- parameter initial: The initial value. Will be passed into the handler as `current` for the first new value that arrives from the current stream.
- parameter scanner: Take the current reduction (either initial or last value returned from the handler), the next value from the stream and returns a new value.
- parameter current: The current reduction.
- parameter next: The next value in the stream.
- returns: A new Cold Stream
*/
@discardableResult public func scan<U>(initial: U, scanner: @escaping (_ current: U, _ next: Response) -> U) -> Cold<Request, U> {
let stream: Cold<Request, U> = newSubStream("scan(initial: \(initial))")
return appendScan(stream: stream, initial: initial, withScanner: scanner)
}
/**
## Branching
Returns the first "n" values emitted and then terminate the stream.
By default the stream is `.cancelled`, but this can be overriden by specifying the termination.
- parameter count: The number of values to emit before terminating the stream.
- parameter then: **Default:** `.cancelled`. After the values have been emitted, the stream will terminate with this reason.
- returns: A new Cold Stream
*/
@discardableResult public func first(_ count: UInt = 1, then: Termination = .cancelled) -> Cold<Request, Response> {
return appendNext(stream: newSubStream("first(\(count), then: \(then))"), count: count, then: then)
}
/**
## Branching
Emits the last "n" values of the stream when it terminates.
The values are emitted sequentialy in the order they were received.
- parameter count: The number of values to emit.
- parameter partial: **Default:** `true`. If the stream terminates before the full count has been received, partial determines whether the partial set should be emitted.
- returns: A new Cold Stream
*/
@discardableResult public func last(_ count: Int = 1, partial: Bool = true) -> Cold<Request, Response> {
if count < 2 {
return appendLast(stream: newSubStream("last"))
}
return appendLast(stream: newSubStream("last(\(count), partial: \(partial))"), count: count, partial: partial)
}
/**
## Branching
This will reduce all values in the stream using the `reducer` passed in. The reduction is emitted when the stream terminates.
This has the same format as `scan` and, in fact, does the same thing except intermediate values are not emitted.
- parameter initial: The initial value. Will be passed into the handler as `current` for the first new value that arrives from the current stream.
- parameter reducer: Take the current reduction (either initial or last value returned from the handler), the next value from the stream and returns a new value.
- parameter current: The current reduction
- parameter reducer: The next value in the stream
- returns: A new Cold Stream
*/
@discardableResult public func reduce<U>(initial: U, reducer: @escaping (_ current: U, _ next: Response) -> U) -> Cold<Request, U> {
let stream: Cold<Request, U> = newSubStream("reduce(initial: \(initial))")
return appendReduce(stream: stream, initial: initial, withReducer: reducer)
}
/**
## Branching
Buffer values received from the stream until it's full and emit the values in a group as an array.
- parameter size: The size of the buffer.
- parameter partial: **Default:** `true`. If the stream is terminated before the buffer is full, emit the partial buffer.
- returns: A new Cold Stream
*/
@discardableResult public func buffer(size: Int, partial: Bool = true) -> Cold<Request, [Response]> {
return appendBuffer(stream: newSubStream("buffer(\(size), partial: \(partial))"), bufferSize: size, partial: partial)
}
/**
## Branching
Create a moving window of the last "n" values.
For each new value received, emit the last "n" values as a group.
- parameter size: The size of the window. Minimum: 1
- parameter partial: **Default:** `true`. If the stream completes and the window buffer isn't full, emit all the partial buffer.
- returns: A new Cold Stream
*/
@discardableResult public func window(size: Int, partial: Bool = false) -> Cold<Request, [Response]> {
return appendWindow(stream: newSubStream("sizedWindow(\(size), partial: \(partial))"), windowSize: size, partial: partial)
}
/**
## Branching
Create a moving window of the last values within the provided time array.
For each new value received, emit all the values within the time frame as a group.
- parameter size: The window size in seconds
- parameter limit: _(Optional)_ limit the number of values that are buffered and emitted.
- returns: A new Cold Stream
*/
@discardableResult public func window(size: TimeInterval, limit: Int? = nil) -> Cold<Request, [Response]> {
return appendWindow(stream: newSubStream("timedWindow(\(size), limit: \(limit ?? -1))"), windowSize: size, limit: limit)
}
/**
## Branching
Filter out values if the handler returns `false`.
- parameter include: Handler to determine whether the value should filtered out (`false`) or included in the stream (`true`)
- parameter value: The next value to be emitted by the stream.
- returns: A new Cold Stream
*/
@discardableResult public func filter(include: @escaping (_ value: Response) -> Bool) -> Cold<Request, Response> {
return appendFilter(stream: newSubStream("filter"), include: include)
}
/**
## Branching
Emit only each nth value, determined by the "stride" provided. All other values are ignored.
- parameter stride: _Minimum:_ 1. The distance between each value emitted.
For example: `1` will emit all values, `2` will emit every other value, `3` will emit every third value, etc.
- returns: A new Cold Stream
*/
@discardableResult public func stride(_ stride: Int) -> Cold<Request, Response> {
return appendStride(stream: newSubStream("stride(\(stride))"), stride: stride)
}
/**
## Branching
Append a stamp to each item emitted from the stream. The Stamp and the value will be emitted as a tuple.
- parameter stamper: Takes a value emitted from the stream and returns a stamp for that value.
- parameter value: The next value for the stream.
- returns: A new Cold Stream
*/
@discardableResult public func stamp<U>(_ stamper: @escaping (_ value: Response) -> U) -> Cold<Request, (value: Response, stamp: U)> {
let stream: Cold<Request, (value: Response, stamp: U)> = newSubStream("stamp")
return appendStamp(stream: stream, stamper: stamper)
}
/**
## Branching
Append a timestamp to each value and return both as a tuple.
- returns: A new Cold Stream
*/
@discardableResult public func timeStamp() -> Cold<Request, (value: Response, stamp: Date)> {
return stamp{ _ in return Date() }
}
/**
## Branching
Emits a value only if the distinct handler returns that the new item is distinct from the previous item.
- warning: The first value is _always_ distinct and will be emitted without passing through the handler.
- parameters:
- isDistinct: Takes the prior, and next values and should return whether the next value is distinct from the prior value.
If `true`, the next value will be emitted, otherwise it will be ignored.
- prior: The prior value last emitted from the stream.
- next: The next value to be emitted from the stream.
- returns: A new Cold Stream
*/
@discardableResult public func distinct(_ isDistinct: @escaping (_ prior: Response, _ next: Response) -> Bool) -> Cold<Request, Response> {
return appendDistinct(stream: newSubStream("distinct"), isDistinct: isDistinct)
}
/**
## Branching
Only emits items that are less than all previous items, as determined by the handler.
- warning: The first value is always mininum and will be emitted without passing through the handler.
- parameters:
- lessThan: Handler should take the first item, and return whether it is less than the second item.
- isValue: The next value to be compared.
- lessThan: The current "min" value.
- returns: A new Cold Stream
*/
@discardableResult public func min(lessThan: @escaping (_ isValue: Response, _ lessThan: Response) -> Bool) -> Cold<Request, Response> {
return appendMin(stream: newSubStream("min"), lessThan: lessThan)
}
/**
## Branching
Only emits items that are greater than all previous items, as determined by the handler.
- warning: The first value is always maximum and will be emitted without passing through the handler.
- parameters:
- greaterThan: Handler should take the first item, and return whether it is less than the second item.
- isValue: The next value to be compared.
- greaterThan: The current "max" value.
- returns: A new Cold Stream
*/
@discardableResult public func max(greaterThan: @escaping (_ isValue: Response, _ greaterThan: Response) -> Bool) -> Cold<Request, Response> {
return appendMax(stream: newSubStream("max"), greaterThan: greaterThan)
}
/**
## Branching
Emits the current count of values emitted from the stream. It does not emit the values themselves.
- returns: A new Cold Stream
*/
@discardableResult public func count() -> Cold<Request, UInt> {
return appendCount(stream: newSubStream("count"))
}
/**
## Branching
This will stamp the values in the stream with the current count and emit them as a tuple.
- returns: A new Cold Stream
*/
@discardableResult public func countStamp() -> Cold<Request, (value: Response, stamp: UInt)> {
var count: UInt = 0
return stamp{ _ in
count += 1
return count
}
}
/**
## Branching
This will delay the values emitted from the stream by the time specified.
- warning: The stream cannot terminate until all events are terminated.
- parameter delay: The time, in seconds, to delay emitting events from the stream.
- returns: A new Cold Stream
*/
@discardableResult public func delay(_ delay: TimeInterval) -> Cold<Request, Response> {
return appendDelay(stream: newSubStream("delay(\(delay))"), delay: delay)
}
/**
## Branching
Skip the first "n" values emitted from the stream. All values afterwards will be emitted normally.
- parameter count: The number of values to skip.
- returns: A new Cold Stream
*/
@discardableResult public func skip(_ count: Int) -> Cold<Request, Response> {
return appendSkip(stream: newSubStream("skip(\(count))"), count: count)
}
/**
## Branching
Emit provided values immediately before the first value received by the stream.
- note: These values are only emitted when the stream receives its first value. If the stream receives no values, these values won't be emitted.
- parameter with: The values to emit before the first value
- returns: A new Cold Stream
*/
@discardableResult public func start(with: [Response]) -> Cold<Request, Response> {
return appendStart(stream: newSubStream("start(with: \(with.count) values)"), startWith: with)
}
/**
## Branching
Emit provided values after the last item, right before the stream terminates.
These values will be the last values emitted by the stream.
- parameter conat: The values to emit before the stream terminates.
- returns: A new Cold Stream
*/
@discardableResult public func concat(_ concat: [Response]) -> Cold<Request, Response> {
return appendConcat(stream: newSubStream("concat(\(concat.count) values)"), concat: concat)
}
/**
## Branching
Define a default value to emit if the stream terminates without emitting anything.
- parameter value: The default value to emit.
- returns: A new Cold Stream
*/
@discardableResult public func defaultValue(_ value: Response) -> Cold<Request, Response> {
return appendDefault(stream: newSubStream("defaultValue(\(value))"), value: value)
}
}
// MARK: Combining operators
extension Cold {
/**
## Branching
Merge a separate stream into this one, returning a new stream that emits values from both streams sequentially as an Either
- parameter stream: The stream to merge into this one.
- returns: A new Cold Stream
*/
@discardableResult public func merge<U>(_ stream: Stream<U>) -> Cold<Request, Either<Response, U>> {
return appendMerge(stream: stream, intoStream: newSubStream("merge(\(stream))"))
}
/**
## Branching
Merge into this stream a separate stream with the same type, returning a new stream that emits values from both streams sequentially.
- parameter stream: The stream to merge into this one.
- returns: A new Cold Stream
*/
@discardableResult public func merge(_ stream: Stream<Response>) -> Cold<Request, Response> {
return appendMerge(stream: stream, intoStream: newSubStream("merge(\(stream))"))
}
/**
## Branching
Merge another stream into this one, _zipping_ the values from each stream into a tuple that's emitted from a new stream.
- note: Zipping combines a stream of two values by their _index_.
In order to do this, the new stream keeps a buffer of values emitted by either stream if one stream emits more values than the other.
In order to prevent unconstrained memory growth, you can specify the maximum size of the buffer.
If you do not specify a buffer, the buffer will continue to grow if one stream continues to emit values more than another.
- parameter stream: The stream to zip into this one
- parameter buffer: _(Optional)_, **Default:** `nil`. The maximum size of the buffer. If `nil`, then no maximum is set (the buffer can grow indefinitely).
- returns: A new Cold Stream
*/
@discardableResult public func zip<U>(_ stream: Stream<U>, buffer: Int? = nil) -> Cold<Request, (Response, U)> {
return appendZip(stream: stream, intoStream: newSubStream("zip(stream: \(stream), buffer: \(buffer ?? -1))"), buffer: buffer)
}
/**
## Branching
Merge another stream into this one, emitting the values as a tuple.
- warning: The behavior of this function changes significantly on the `latest` parameter.
Specifying `latest = true` (the default) will cause the stream to enumerate _all_ changes in both streams.
If one stream emits more values than another, the lastest value in that other stream will be emitted multiple times, thus enumerating each combinmation.
If `latest = false`, then a value can only be emitted _once_, even if the other stream emits multiple values.
This means if one stream emits a single value while the other emits multiple values, all but one of those multiple values will be dropped.
- parameter latest: **Default:** `true`. Whether to emit all values, using the latest value from the other stream as necessary. If false, values may be dropped.
- parameter stream: The stream to combine into this one.
- returns: A new Cold Stream
*/
@discardableResult public func combine<U>(latest: Bool = true, stream: Stream<U>) -> Cold<Request, (Response, U)> {
return appendCombine(stream: stream, intoStream: newSubStream("combine(latest: \(latest), stream: \(stream))"), latest: latest)
}
}
// MARK: Lifetime operators
extension Cold {
/**
## Branching
Emit values from stream until the handler returns `false`, and then terminate the stream with the provided termination.
- parameter then: **Default:** `.cancelled`. When the handler returns `false`, then terminate the stream with this termination.
- parameter handler: Takes the next value and returns `false` to terminate the stream or `true` to remain active.
- parameter value: The current value being passed down the stream.
- warning: Be aware that terminations propogate _upstream_ until the termination hits a stream that has multiple active branches (attached down streams) _or_ it hits a stream that is marked `persist`.
- returns: A new Cold Stream
*/
@discardableResult public func doWhile(then: Termination = .cancelled, handler: @escaping (_ value: Response) -> Bool) -> Cold<Request, Response> {
return appendWhile(stream: newSubStream("doWhile(then: \(then))"), handler: handler, then: then)
}
/**
## Branching
Emit values from stream until the handler returns `true`, and then terminate the stream with the provided termination.
- note: This is the inverse of `doWhile`, in that the stream remains active _until_ it returns `true` whereas `doWhile` remains active until the handler return `false`.
- parameter then: **Default:** `.cancelled`. When the handler returns `true`, then terminate the stream with this termination.
- parameter handler: Takes the next value and returns `true` to terminate the stream or `false` to remain active.
- parameter value: The current value being passed down the stream.
- warning: Be aware that terminations propogate _upstream_ until the termination hits a stream that has multiple active branches (attached down streams) _or_ it hits a stream that is marked `persist`.
- returns: A new Cold Stream
*/
@discardableResult public func until(then: Termination = .cancelled, handler: @escaping (Response) -> Bool) -> Cold<Request, Response> {
return appendUntil(stream: newSubStream("until(then: \(then))"), handler: handler, then: then)
}
/**
## Branching
Emit values from stream until the handler returns a `Termination`, at which the point the stream will Terminate.
- parameter handler: Takes the next value and returns a `Termination` to terminate the stream or `nil` to continue as normal.
- parameter value: The current value being passed down the stream.
- warning: Be aware that terminations propogate _upstream_ until the termination hits a stream that has multiple active branches (attached down streams) _or_ it hits a stream that is marked `persist`.
- returns: A new Cold Stream
*/
@discardableResult public func until(_ handler: @escaping (_ value: Response) -> Termination?) -> Cold<Request, Response> {
return appendUntil(stream: newSubStream("until"), handler: handler)
}
/**
## Branching
Emit values from stream until the handler returns `false`, and then terminate the stream with the provided termination.
- parameter then: **Default:** `.cancelled`. When the handler returns `false`, then terminate the stream with this termination.
- parameter handler: Takes the next value and returns `false` to terminate the stream or `true` to remain active.
- parameter prior: The prior value, if any.
- parameter next: The current value being passed down the stream.
- warning: Be aware that terminations propogate _upstream_ until the termination hits a stream that has multiple active branches (attached down streams) _or_ it hits a stream that is marked `persist`.
- returns: A new Cold Stream
*/
@discardableResult public func doWhile(then: Termination = .cancelled, handler: @escaping (_ prior: Response?, _ next: Response) -> Bool) -> Cold<Request, Response> {
return appendWhile(stream: newSubStream("doWhile(then: \(then))"), handler: handler, then: then)
}
/**
## Branching
Emit values from stream until the handler returns `true`, and then terminate the stream with the provided termination.
- note: This is the inverse of `doWhile`, in that the stream remains active _until_ it returns `true` whereas `doWhile` remains active until the handler return `false`.
- parameter then: **Default:** `.cancelled`. When the handler returns `true`, then terminate the stream with this termination.
- parameter handler: Takes the next value and returns `true` to terminate the stream or `false` to remain active.
- parameter prior: The prior value, if any.
- parameter next: The current value being passed down the stream.
- warning: Be aware that terminations propogate _upstream_ until the termination hits a stream that has multiple active branches (attached down streams) _or_ it hits a stream that is marked `persist`.
- returns: A new Cold Stream
*/
@discardableResult public func until(then: Termination = .cancelled, handler: @escaping (_ prior: Response?, _ next: Response) -> Bool) -> Cold<Request, Response> {
return appendUntil(stream: newSubStream("untilTransition(then: \(then))"), handler: handler, then: then)
}
/**
## Branching
Emit values from stream until the handler returns a `Termination`, and then terminate the stream with the provided termination.
- parameter handler: Takes the next value and returns `true` to terminate the stream or `false` to remain active.
- parameter prior: The prior value, if any.
- parameter next: The current value being passed down the stream.
- warning: Be aware that terminations propogate _upstream_ until the termination hits a stream that has multiple active branches (attached down streams) _or_ it hits a stream that is marked `persist`.
- returns: A new Cold Stream
*/
@discardableResult public func until(handler: @escaping (_ prior: Response?, _ next: Response) -> Termination?) -> Cold<Request, Response> {
return appendUntil(stream: newSubStream("untilTransition"), handler: handler)
}
/**
## Branching
Keep a weak reference to an object, emitting both the object and the current value as a tuple.
Terminate the stream on the next event that finds object `nil`.
- parameter object: The object to keep a week reference. The stream will terminate on the next even where the object is `nil`.
- parameter then: The termination to apply after the reference has been found `nil`.
- warning: Be aware that terminations propogate _upstream_ until the termination hits a stream that has multiple active branches (attached down streams) _or_ it hits a stream that is marked `persist`.
- warning: This stream will return a stream that _cannot_ be replayed. This prevents the stream of retaining the object and extending its lifetime.
- returns: A new Cold Stream
*/
@discardableResult public func using<U: AnyObject>(_ object: U, then: Termination = .cancelled) -> Cold<Request, (U, Response)> {
return appendUsing(stream: newSubStream("using(\(object), then: \(then))"), object: object, then: then).canReplay(false)
}
/**
## Branching
Tie the lifetime of the stream to that of the object.
Terminate the stream on the next event that finds object `nil`.
- parameter object: The object to keep a week reference. The stream will terminate on the next even where the object is `nil`.
- parameter then: The termination to apply after the reference has been found `nil`.
- warning: Be aware that terminations propogate _upstream_ until the termination hits a stream that has multiple active branches (attached down streams) _or_ it hits a stream that is marked `persist`.
- returns: A new Cold Stream
*/
@discardableResult public func lifeOf<U: AnyObject>(_ object: U, then: Termination = .cancelled) -> Cold<Request, Response> {
return appendLifeOf(stream: newSubStream("lifeOf(\(object), then: \(then))"), object: object, then: then)
}
/**
## Branching
Emit the next "n" values and then terminate the stream.
- parameter count: The number of values to emit before terminating the stream.
- parameter then: **Default:** `.cancelled`. How the stream is terminated after the events are emitted.
- warning: Be aware that terminations propogate _upstream_ until the termination hits a stream that has multiple active branches (attached down streams) _or_ it hits a stream that is marked `persist`.
- returns: A new Cold Stream
*/
@discardableResult public func next(_ count: UInt = 1, then: Termination = .cancelled) -> Cold<Request, Response> {
return appendNext(stream: newSubStream("next(\(count), then: \(then))"), count: count, then: then)
}
}
extension Cold where Response : Sequence {
/**
## Branching
Convenience function that takes an array of values and flattens them into sequential values emitted from the stream.
This is the same as (and uses) `flatMap`, without the need to specify the handler.
- returns: A new Cold Stream
*/
@discardableResult public func flatten() -> Cold<Request, Response.Iterator.Element> {
return flatMap{ $0.map{ $0 } }
}
}
extension Cold where Response : Arithmetic {
/**
## Branching
Takes values emitted, averages them, and returns the average in the new stream.
- returns: A new Cold Stream
*/
@discardableResult public func average() -> Cold<Request, Response> {
return appendAverage(stream: newSubStream("average"))
}
/**
## Branching
Sums values emitted and emit them in the new stream.
- returns: A new Cold Stream
*/
@discardableResult public func sum() -> Cold<Request, Response> {
return appendSum(stream: newSubStream("sum"))
}
}
extension Cold where Response : Equatable {
/**
## Branching
Convenience function to only emit distinct equatable values.
This has the same effect as using `distinct { $0 != $1 }` function.
- returns: A new Cold Stream
*/
@discardableResult public func distinct() -> Cold<Request, Response> {
return appendDistinct(stream: newSubStream("distinct"), isDistinct: { $0 != $1 })
}
}
extension Cold where Response : Comparable {
/**
## Branching
Convenience function that only emits the minimum values.
- returns: A new Cold Stream
*/
@discardableResult public func min() -> Cold<Request, Response> {
return appendMin(stream: newSubStream("min")) { $0 < $1 }
}
/**
## Branching
Convenience function that only emits the maximum values.
- returns: A new Cold Stream
*/
@discardableResult public func max() -> Cold<Request, Response> {
return appendMax(stream: newSubStream("max")) { $0 > $1 }
}
}
| mit | b7b38dea05b80f602388de131d6853ed | 40.848447 | 225 | 0.696628 | 4.453728 | false | false | false | false |
akucaj/Hello-SpriteKit | Hello-SpriteKit/GameViewController.swift | 1 | 1414 | //
// GameViewController.swift
// Hello-SpriteKit
//
// Created by Artur Kucaj on 02/10/15.
// Copyright (c) 2015 Artur Kucaj. All rights reserved.
//
import UIKit
import SpriteKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let scene = GameScene(fileNamed:"GameScene") {
// Configure the view.
let skView = self.view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .AspectFill
skView.presentScene(scene)
}
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return .AllButUpsideDown
} else {
return .All
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
| mit | dcdf41e3c2b21985658fce6a3a2da0ad | 25.679245 | 94 | 0.60396 | 5.545098 | false | false | false | false |
willlarche/material-components-ios | components/AppBar/examples/AppBarTypicalUseExample.swift | 2 | 3845 | /*
Copyright 2016-present the Material Components for iOS authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
import MaterialComponents
class AppBarTypicalUseSwiftExample: UITableViewController {
// Step 1: Create and initialize an App Bar.
let appBar = MDCAppBar()
init() {
super.init(nibName: nil, bundle: nil)
self.title = "App Bar (Swift)"
// Step 2: Add the headerViewController as a child.
self.addChildViewController(appBar.headerViewController)
let color = UIColor(white: 0.2, alpha:1)
appBar.headerViewController.headerView.backgroundColor = color
appBar.navigationBar.tintColor = UIColor.white
appBar.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName : UIColor.white]
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
// Recommended step: Set the tracking scroll view.
appBar.headerViewController.headerView.trackingScrollView = self.tableView
// Choice: If you do not need to implement any delegate methods and you are not using a
// collection view, you can use the headerViewController as the delegate.
// Alternative: See AppBarDelegateForwardingExample.
self.tableView.delegate = appBar.headerViewController
// Step 3: Register the App Bar views.
appBar.addSubviewsToParent()
self.tableView.layoutMargins = UIEdgeInsets.zero
self.tableView.separatorInset = UIEdgeInsets.zero
self.navigationItem.rightBarButtonItem =
UIBarButtonItem(title: "Right", style: .done, target: nil, action: nil)
}
// Optional step: If you allow the header view to hide the status bar you must implement this
// method and return the headerViewController.
override var childViewControllerForStatusBarHidden: UIViewController? {
return appBar.headerViewController
}
// Optional step: The Header View Controller does basic inspection of the header view's background
// color to identify whether the status bar should be light or dark-themed.
override var childViewControllerForStatusBarStyle: UIViewController? {
return appBar.headerViewController
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setNavigationBarHidden(true, animated: animated)
}
}
// MARK: Catalog by convention
extension AppBarTypicalUseSwiftExample {
@objc class func catalogBreadcrumbs() -> [String] {
return ["App Bar", "App Bar (Swift)"]
}
@objc class func catalogIsPrimaryDemo() -> Bool {
return false
}
func catalogShouldHideNavigation() -> Bool {
return true
}
}
// MARK: - Typical application code (not Material-specific)
// MARK: UITableViewDataSource
extension AppBarTypicalUseSwiftExample {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 50
}
override func tableView(
_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = self.tableView.dequeueReusableCell(withIdentifier: "cell")
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
}
cell!.layoutMargins = UIEdgeInsets.zero
return cell!
}
}
| apache-2.0 | d5c94ae1e225dd351703dfe295096f7d | 31.584746 | 100 | 0.738622 | 4.91688 | false | false | false | false |
tlax/looper | looper/View/Camera/Scale/VCameraScaleSliderTrack.swift | 1 | 780 | import UIKit
class VCameraScaleSliderTrack:UIView
{
weak var selectedView:VBorder!
init()
{
super.init(frame:CGRect.zero)
clipsToBounds = true
isUserInteractionEnabled = false
translatesAutoresizingMaskIntoConstraints = false
backgroundColor = UIColor(white:0, alpha:0.1)
let selectedView:VBorder = VBorder(color:UIColor.genericLight)
self.selectedView = selectedView
addSubview(selectedView)
NSLayoutConstraint.equalsHorizontal(
view:selectedView,
toView:self)
NSLayoutConstraint.bottomToBottom(
view:selectedView,
toView:self)
}
required init?(coder:NSCoder)
{
return nil
}
}
| mit | 290ea688ed179f31d081036cf5b50380 | 23.375 | 70 | 0.615385 | 5.492958 | false | false | false | false |
IvoPaunov/selfie-apocalypse | Selfie apocalypse/Selfie apocalypse/SelfieSlayingSchoolController.swift | 1 | 4982 | //
// SelfieSlayingSchoolController.swift
// Selfie apocalypse
//
// Created by Ivko on 2/7/16.
// Copyright © 2016 Ivo Paounov. All rights reserved.
//
import UIKit
class SelfieSlayingSchoolController: UIViewController, UITableViewDataSource {
let transitionManager = TransitionManager()
var weapons = [SelfieSalyingWeaponDescription]()
let weaponCellIdentifier = "WeaponCell"
@IBOutlet weak var weaponsTable: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.setupWeaponsTable()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setWeaponDescriptions()
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.setWeaponDescriptions()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.weapons.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.getWeaponCell(indexPath)
return cell
}
func getWeaponCell(indexPath: NSIndexPath) -> HowToSlayCell{
let weapon = self.weapons[indexPath.row]
let cell = NSBundle.mainBundle().loadNibNamed("HowToSlayCell", owner: nil, options: nil)[0] as! HowToSlayCell
cell.weaponImageViwe.image = weapon.image
cell.weaponImageViwe.layer.borderColor = weapon.borderColor
cell.weaponImageViwe.layer.borderWidth = 4
cell.weaponTitleLabel.text = weapon.title
cell.weaponDescriptionLabel.text = weapon.description
return cell
}
func setWeaponDescriptions(){
let granadeWeapon = SelfieSalyingWeaponDescription()
granadeWeapon.image = UIImage(named: "Granade")
granadeWeapon.borderColor = UIColor.clearColor().CGColor
granadeWeapon.title = "Granade"
granadeWeapon.description = "This is very powerfull weapon that can slay all selfies in the field.\n" +
"The problem is that you have only 3 of them.\n " +
"* To use one just shake tour device.\n(That also will change the music.)"
let pikeWeapon = SelfieSalyingWeaponDescription()
pikeWeapon.image = UIImage(named: "Pike")
pikeWeapon.borderColor = UIColor.yellowColor().CGColor
pikeWeapon.title = "Pike"
pikeWeapon.description = "The pike can slay only selfies with yellow tint.\n" +
"* To the pike some selfie you should double tap on it"
let axeWeapon = SelfieSalyingWeaponDescription()
axeWeapon.image = UIImage(named: "Axe")
axeWeapon.borderColor = UIColor.blackColor().CGColor
axeWeapon.title = "Axe"
axeWeapon.description = "The axe can slay only selfies with black tint.\n" +
"* The axe is very heavy so to use it you have to long press the selfie you want to slay"
let batWeapon = SelfieSalyingWeaponDescription()
batWeapon.image = UIImage(named: "Bat")
batWeapon.borderColor = UIColor.brownColor().CGColor
batWeapon.title = "The baseball bat"
batWeapon.description = "This classic selfie slaying weapon is very powerfull but can only slay selfies with brown tint.\n" +
"* This is very easy to use weapon - just swipe lefto or right over the selfie and it will be slayed"
let nunchakuWeapon = SelfieSalyingWeaponDescription()
nunchakuWeapon.image = UIImage(named: "Nunchaku")
nunchakuWeapon.borderColor = UIColor.grayColor().CGColor
nunchakuWeapon.title = "Nunchaku"
nunchakuWeapon.description = "In every selfie apocalypse situation thera are some hard moments.\n" +
"This is the weapon for the most powerfull gray tint selfies.\n" +
"* You have to pinch out with 2 fingers over the selfie"
self.weapons.append(granadeWeapon)
self.weapons.append(pikeWeapon)
self.weapons.append(axeWeapon)
self.weapons.append(batWeapon)
self.weapons.append(nunchakuWeapon)
}
func setupWeaponsTable(){
weaponsTable.registerClass(UITableViewCell.self, forCellReuseIdentifier: weaponCellIdentifier)
weaponsTable.rowHeight = UITableViewAutomaticDimension
weaponsTable.estimatedRowHeight = 220
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let toViewController = segue.destinationViewController as UIViewController
self.transitionManager.toLeft = false
toViewController.transitioningDelegate = self.transitionManager
}
}
| mit | bc131227bd170e7e9bfa37291d770d80 | 39.495935 | 133 | 0.676972 | 4.612037 | false | false | false | false |
Erez-Panda/LiveBankSDK | Pod/Classes/LiveSign.swift | 1 | 4905 | //
// LiveSign.swift
// Pods
//
// Created by Erez Haim on 1/4/16.
//
//
import Foundation
public class LiveSign: NSObject {
public static let sharedInstance = LiveSign()
public func setRemoteUrl(strUrl: String) -> Bool {
// TODO: check if url is valid
RemoteAPI.sharedInstance.setUrl(strUrl)
return true
}
public func startSession(id: String, superView: UIView, user: String? = nil, completion: ((view: UIView) -> Void)? = nil) -> Void{
Session.sharedInstance.connect(id) { (result) -> Void in
let documentView = NSBundle(forClass: LiveSign.self).loadNibNamed("DocumentView", owner: self, options: nil)[0] as! DocumentView
documentView.fadeOut(duration: 0.0)
documentView.attachToView(superView)
documentView.fadeIn()
documentView.user = user
completion?(view: documentView)
}
}
public func openTrainingPanel(user: String , superView: UIView, completion: ((view: UIView) -> Void)? = nil) -> Void{
let trainingView = NSBundle(forClass: LiveSign.self).loadNibNamed("SignatureTrainingView", owner: self, options: nil)[0] as! SignatureTrainingView
trainingView.fadeOut(duration: 0.0)
trainingView.attachToView(superView)
trainingView.fadeIn()
trainingView.user = user
completion?(view: trainingView)
}
}
extension UIView{
func addConstraintsToSuperview(superView: UIView, top: CGFloat?, left: CGFloat?, bottom: CGFloat?, right: CGFloat?) -> Dictionary<String, NSLayoutConstraint> {
var result : Dictionary<String, NSLayoutConstraint> = [:]
self.translatesAutoresizingMaskIntoConstraints = false
if let t = top {
let topConstraint = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: superView, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: t)
superView.addConstraint(topConstraint)
result["top"] = topConstraint
}
if let l = left {
let leftConstraint = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: superView, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: l)
superView.addConstraint(leftConstraint)
result["left"] = leftConstraint
}
if let b = bottom {
let bottomConstraint = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: superView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: b)
superView.addConstraint(bottomConstraint)
result["bottom"] = bottomConstraint
}
if let r = right {
let rightConstraint = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: superView, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: r)
superView.addConstraint(rightConstraint)
result["right"] = rightConstraint
}
return result
}
func addSizeConstraints (width: CGFloat?, height: CGFloat?) -> Dictionary<String, NSLayoutConstraint>{
self.translatesAutoresizingMaskIntoConstraints = false
var widthConstraint:NSLayoutConstraint = NSLayoutConstraint()
var hightConstraint:NSLayoutConstraint = NSLayoutConstraint()
if let w = width {
widthConstraint = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: w)
self.addConstraint(widthConstraint)
}
if let h = height {
hightConstraint = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: h)
self.addConstraint(hightConstraint)
}
return ["width":widthConstraint, "height":hightConstraint]
}
/**
Fade in a view with a duration
- parameter duration: custom animation duration
*/
func fadeIn(duration duration: NSTimeInterval = 0.325) {
UIView.animateWithDuration(duration, animations: {
self.alpha = 1.0
})
}
/**
Fade out a view with a duration
- parameter duration: custom animation duration
*/
func fadeOut(duration duration: NSTimeInterval = 0.325, remove: Bool = false) {
UIView.animateWithDuration(duration, animations: { () -> Void in
self.alpha = 0.0
}) { (result) -> Void in
if (remove){
self.removeFromSuperview()
}
}
}
} | mit | 9a6741bfb7faa27555bf3345b5e09faf | 43.198198 | 221 | 0.658919 | 5.082902 | false | false | false | false |
elpassion/el-space-ios | ELSpace/Screens/Selection/SelectionScreenPresenter.swift | 1 | 1216 | import UIKit
protocol SelectionScreenPresenting {
func presentHub()
}
class SelectionScreenPresenter: SelectionScreenPresenting {
init(activitiesCoordinatorFactory: ActivitiesCoordinatorCreation,
viewControllerPresenter: ViewControllerPresenting,
presenterViewController: UIViewController) {
self.activitiesCoordinatorFactory = activitiesCoordinatorFactory
self.viewControllerPresenter = viewControllerPresenter
self.presenterViewController = presenterViewController
}
func presentHub() {
let coordinator = activitiesCoordinatorFactory.activitiesCoordinator()
self.coordinator = coordinator
let navigationController = presenterViewController.navigationController
viewControllerPresenter.push(viewController: coordinator.initialViewController, on: presenterViewController)
navigationController?.setNavigationBarHidden(false, animated: true)
}
// MARK: Private
private let activitiesCoordinatorFactory: ActivitiesCoordinatorCreation
private let viewControllerPresenter: ViewControllerPresenting
private let presenterViewController: UIViewController
private var coordinator: Coordinator?
}
| gpl-3.0 | 3fcca6c5e9a2b4bb132f010ca2690ad0 | 37 | 116 | 0.790296 | 6.948571 | false | false | false | false |
pmark/MartianRover | Playgrounds/MyPlayground6.playground/Contents.swift | 1 | 5180 | import Cocoa // (or UIKit for iOS)
import SceneKit
import QuartzCore // for the basic animation
import XCPlayground // for the live preview
////////////////
func createCoordLabels() -> SCNNode {
var labelsNode = SCNNode()
for z in -5...5 {
var l = SCNNode(geometry: SCNText(string: " z "+String(z*100), extrusionDepth: 100))
l.position = SCNVector3Make(caseSize/2, 0, (CGFloat(z)*100))
l.geometry!.firstMaterial?.diffuse.contents = NSColor.yellowColor()
l.rotation = SCNVector4(x: 1, y: 0, z: 0.0, w: -fM_PI_2)
labelsNode.addChildNode(l)
}
return labelsNode;
}
func createBoard() -> SCNNode {
var boardNode = SCNNode(geometry: SCNBox(width: caseSize, height: 1, length: caseSize, chamferRadius: 1.0))
boardNode.geometry!.firstMaterial?.diffuse.contents = NSColor.darkGrayColor()
var colorToggle = true
for x in 0..<8 {
colorToggle = (x % 2 == 0) ? true : false
for z in 0..<8 {
let h = tileSize / 2
var cube = SCNBox(
width: tileSize,
height: h,
length: tileSize,
chamferRadius: 0.25)
let iTileSize = Int(tileSize)
let iTileSize2 = iTileSize / 2
var cubeNode = SCNNode(geometry: cube)
cubeNode.position.x = CGFloat((x-4) * iTileSize + iTileSize2);
cubeNode.position.z = CGFloat((z-4) * iTileSize + iTileSize2);
cubeNode.position.y = h
cube.firstMaterial?.diffuse.contents = (colorToggle ? NSColor.whiteColor() : NSColor.blueColor())
// cube.firstMaterial?.specular.contents = (colorToggle ? NSColor.redColor() : NSColor.whiteColor())
colorToggle = !colorToggle
cubeNode.rotation = SCNVector4(x: 1, y: 1, z: 0.0, w: 0.0)
if false {
var spin = CABasicAnimation(keyPath: "rotation.w") // only animate the angle
spin.fromValue = -M_PI*2.0
spin.toValue = M_PI*2.0
spin.duration = duration + CFTimeInterval(abs(x)+abs(z))
spin.autoreverses = false
spin.repeatCount = HUGE // for infinity
cubeNode.addAnimation(spin, forKey: "spin around")
}
boardNode.addChildNode(cubeNode)
}
}
return boardNode
}
///////////////
let fM_PI = CGFloat(M_PI)
let fM_PI_2 = CGFloat(M_PI_2)
let fM_PI_4 = CGFloat(M_PI_4)
// create a scene view with an empty scene
let sceneSize = 700
var sceneView = SCNView(frame: CGRect(x: 0, y: 0, width: sceneSize, height: sceneSize))
var scene = SCNScene()
sceneView.scene = scene
sceneView.backgroundColor = NSColor.darkGrayColor()
sceneView.autoenablesDefaultLighting = true
// start a live preview of that view
XCPShowView("C", sceneView)
let floor = SCNNode(geometry: SCNFloor())
scene.rootNode.addChildNode(floor)
floor.position.z = -1
let tileSize:CGFloat = 10.0
let boardSize = tileSize*8
let caseSize = boardSize + (tileSize*4)
let duration:CFTimeInterval = 5
var numBoards:Int = 4
let trackSize:CGFloat = caseSize
let trackLength:CGFloat = (trackSize*CGFloat(numBoards))
let coordsNode:SCNNode = createCoordLabels()
scene.rootNode.addChildNode(coordsNode)
let trackNode:SCNNode = SCNNode(geometry: SCNBox(
width: trackSize,
height: 1,
length: trackLength,
chamferRadius: 0))
trackNode.geometry!.firstMaterial?.diffuse.contents = NSColor.redColor()
scene.rootNode.addChildNode(trackNode)
trackNode.position = SCNVector3Make(0, -1, 0) //(-caseSize/2))
// a camera
var camera = SCNCamera()
var cameraNode = SCNNode()
cameraNode.camera = camera
let camZ = (CGFloat(numBoards-1) * boardSize) + 10
cameraNode.position = SCNVector3(
x: (caseSize / 2),
y: (caseSize * 1.3) * CGFloat(numBoards),
z: 0) //(caseSize + (caseSize/2)))
let c = SCNLookAtConstraint(target: trackNode)
c.gimbalLockEnabled = true
//cameraNode.constraints = [c]
camera.automaticallyAdjustsZRange = true
cameraNode.rotation = SCNVector4Make(1, 0, 0, -fM_PI_2)
scene.rootNode.addChildNode(cameraNode)
for i in 0..<numBoards {
var b = createBoard()
let caseSize2 = (caseSize / 2)
let trackLength2 = (trackLength / 2)
let zFirst = trackLength2 - caseSize2
let z = zFirst - (caseSize*CGFloat(i))
// let offset:CGFloat = (trackLength / CGFloat(numBoards))
// let z = ((boardSize*CGFloat(i)) - offset)
// b.position = SCNVector3(x: 0, y: 0, z: z)
trackNode.addChildNode(b)
b.position.z = z
}
//let move:SCNAction = SCNAction.moveByX(0, y: -1, z: 10, duration: duration)
//let rot:SCNAction = SCNAction.rotateByAngle(3.14, aroundAxis: SCNVector3(x: 0, y: -1, z: 0), duration: duration)
//let r = SCNAction.reversedAction(move)
//let g = SCNAction.group([move])
//let sequence = SCNAction.sequence([g, g.reversedAction()])
//trackNode.runAction(move)
//trackNode.runAction(SCNAction.repeatActionForever(move))
// This list of boards needs to be scrollable which means the track moves.
| mit | ae7aa3aa0d97e2f37797692b55705e31 | 30.779141 | 123 | 0.630502 | 3.689459 | false | false | false | false |
vnu/vTweetz | vTweetz/TweetCell.swift | 1 | 5387 | //
// TweetTableViewCell.swift
// vTweetz
//
// Created by Vinu Charanya on 2/20/16.
// Copyright © 2016 vnu. All rights reserved.
//
import UIKit
import ActiveLabel
@objc protocol TweetCellDelegate {
optional func tweetCell(tweetCell: TweetCell, onTweetReply value: Tweet)
optional func tweetCell(tweetCell: TweetCell, onProfileImageTap value: Tweet)
}
class TweetCell: UITableViewCell {
weak var delegate: TweetCellDelegate?
@IBOutlet weak var profileImage: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var screenNameLabel: UILabel!
@IBOutlet weak var tweetedAtLabel: UILabel!
@IBOutlet weak var tweetActionImage: UIImageView!
@IBOutlet weak var tweetActionLabel: UILabel!
@IBOutlet weak var tweetTextLabel: ActiveLabel!
@IBOutlet weak var retweetButton: UIButton!
@IBOutlet weak var retweetLabel: UILabel!
@IBOutlet weak var likeButton: UIButton!
@IBOutlet weak var likeLabel: UILabel!
@IBOutlet weak var replyButton: UIButton!
@IBOutlet weak var tweetActionView: UIStackView!
@IBOutlet weak var mediaImage: UIImageView!
@IBOutlet weak var imageMediaHeightConstraint: NSLayoutConstraint!
let retweetImage = UIImage(named: "retweet-action-on")
let unretweetImage = UIImage(named: "retweet-action")
let likeImage = UIImage(named: "like-action-on")
let unlikeImage = UIImage(named: "like-action")
let replyImage = UIImage(named: "reply-action_0")
var tweet: Tweet!{
didSet{
nameLabel.text = tweet.user!.name!
screenNameLabel.text = "@\(tweet.user!.screenName!)"
tweetedAtLabel.text = tweet.tweetedAt!
retweetLabel.text = "\(tweet.retweetCount!)"
likeLabel.text = "\(tweet.likeCount!)"
profileImage.setImageWithURL(NSURL(string: (tweet.user?.profileImageUrl)!)!)
setLikeImage(!tweet.liked!)
setRetweetImage(!tweet.retweeted!)
setTweetText()
setTweetAction()
addMediaImage()
}
}
func addMediaImage(){
if let mediaUrl = tweet.mediaUrl{
mediaImage.setImageWithURL(NSURL(string: mediaUrl)!)
mediaImage.hidden = false
mediaImage.clipsToBounds = true
imageMediaHeightConstraint.constant = 240
}else{
mediaImage.hidden = true
imageMediaHeightConstraint.constant = 0
}
}
func setTweetAction(){
if let retweetBy = tweet.retweetedBy{
tweetActionView.hidden = false
tweetActionImage.image = unretweetImage
tweetActionLabel.text = "\(retweetBy) Retweeted"
}else if let inReplyto = tweet.inReplyto{
tweetActionView.hidden = false
tweetActionImage.image = replyImage
tweetActionLabel.text = "In reply to @\(inReplyto)"
}
else{
tweetActionView.hidden = true
}
}
func setTweetText(){
tweetTextLabel.URLColor = twitterDarkBlue
tweetTextLabel.hashtagColor = UIColor.blackColor()
tweetTextLabel.mentionColor = UIColor.blackColor()
tweetTextLabel.text = tweet.text!
tweetTextLabel.handleURLTap { (url: NSURL) -> () in
UIApplication.sharedApplication().openURL(url)
}
}
func setRetweetImage(retweeted: Bool){
if retweeted{
self.retweetButton.setImage(unretweetImage, forState: .Normal)
}else{
self.retweetButton.setImage(retweetImage, forState: .Normal)
}
}
func setLikeImage(liked: Bool){
if liked{
self.likeButton.setImage(unlikeImage, forState: .Normal)
}else{
self.likeButton.setImage(likeImage, forState: .Normal)
}
}
@IBAction func onRetweet(sender: AnyObject) {
if let retweeted = tweet.retweeted{
if retweeted{
self.retweetLabel.text = "\(Int(self.retweetLabel.text!)! - 1)"
}else{
self.retweetLabel.text = "\(Int(self.retweetLabel.text!)! + 1)"
}
setRetweetImage(retweeted)
}
tweet.retweet()
}
func imageTapped(sender: UITapGestureRecognizer){
print("User Tapped Imaged")
delegate?.tweetCell?(self, onProfileImageTap: self.tweet)
}
@IBAction func onLike(sender: AnyObject) {
if let liked = tweet.liked{
if liked{
self.likeLabel.text = "\(Int(self.likeLabel.text!)! - 1)"
}else{
self.likeLabel.text = "\(Int(self.likeLabel.text!)! + 1)"
}
setLikeImage(liked)
}
tweet.like()
}
@IBAction func onReply(sender: UIButton) {
print("onReplyClicked")
delegate?.tweetCell?(self, onTweetReply: self.tweet)
}
override func awakeFromNib() {
super.awakeFromNib()
let tapRecognizer = UITapGestureRecognizer(target: self, action: Selector("imageTapped:"))
//Add the recognizer to your view.
self.profileImage.addGestureRecognizer(tapRecognizer)
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
| apache-2.0 | 8c495e6a6fb639bed850f4e8990f22c3 | 31.059524 | 98 | 0.617713 | 4.708042 | false | false | false | false |
zhangdadi/HDNetworkKit-swift | HDNetworkKit/HDNetworkKit/Network/HDNetRequestQueue.swift | 1 | 6116 | //
// HDNetRequestQueue.swift
// HDNetFramework
//
// Created by 张达棣 on 14-7-23.
// Copyright (c) 2014年 HD. All rights reserved.
//
// 若发现bug请致电:[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
/**
* 带队列的网络请求
*/
public class HDNetQueuedRequest: HDNetRequest
{
public var queue: HDNetRequestQueue? //队列
var _fProcessingQueue: HDNetRequestQueue? // 正在排队中的队列
final override var isInProgress: Bool
{
get {
if let v = _fProcessingQueue {
if v.isInQueue(request: self) { //判断请求是否在队列中
return true
}
}
return queuedInProgress() //判断请求是否在进行中
}
set {
super.isInProgress = newValue
}
}
//+__________________________________________
// 开始请求,子类应重写此方法
func queuedStart() -> Bool
{
return false;
}
// 停止请求,子类应重写此方法
func queuedStop()
{
}
// 判断请求本身是否在进行中,子类重写此方法
func queuedInProgress() -> Bool
{
return false
}
//-__________________________________________
final override func start() -> Bool
{
if queue == nil {
return queuedStart()
}
queue?.enqueueRequest(self)
return true
}
final override func cancel()
{
if _fProcessingQueue != nil {
if _fProcessingQueue!.removeRequest(self) {
return
}
}
if isInProgress == false {
return
}
queuedStop()
}
override func requestCompleted(error: NSError?)
{
if _fProcessingQueue != nil {
_fProcessingQueue!.notifyRequestCompleted(self)
_fProcessingQueue = nil
}
super.requestCompleted(error)
}
//新加入队列
func onRequestQueueEnter(sender: HDNetRequestQueue)
{
_fProcessingQueue = sender
}
//退出队列
func onRequestQueueLeave(sender: HDNetRequestQueue)
{
if _fProcessingQueue == sender {
_fProcessingQueue = nil
}
}
}
//_______________________________________________________________________
/**
* 队列
*/
public class HDNetRequestQueue: NSObject
{
var _requestQueue = [HDNetQueuedRequest]()
var _requestCount: UInt = 0
var _maxParrielRequestCount: UInt = 1 //最大的同时下载数
//+___________________________________________________
// 将请求加入队尾
func enqueueRequest(request: HDNetQueuedRequest!)
{
assert(request.isInProgress == false, "请求正在进行中")
//从队列中删除
var exists = _internalRemoveRequest(request)
//重新加入队列
_requestQueue.append(request)
if exists == false {
// 通知请求对象:新加入队列
request.onRequestQueueEnter(self)
}
// 继续请求
_continueProcessRequest()
}
// 移除请求
func removeRequest(request: HDNetQueuedRequest!) -> Bool
{
if _internalRemoveRequest(request) {
// 通知请求对象:退出队列
request.onRequestQueueLeave(self)
return true
}
return false
}
// 判断请求是否在队列中
func isInQueue(#request: HDNetQueuedRequest!) -> Bool
{
for item in _requestQueue {
if item == request {
return true
}
}
return false
}
// 由HDNetQueuedRequest调用,通知HDNetRequestQueue下载已完成
func notifyRequestCompleted(request: HDNetQueuedRequest!)
{
assert(_requestCount != 0, "请求队列已为0")
_requestCount--
request.onRequestQueueLeave(self)
_continueProcessRequest()
}
//-___________________________________________________
func _continueProcessRequest()
{
_doProcessRequest()
}
func _doProcessRequest()
{
while _requestCount < _maxParrielRequestCount {
if _requestQueue.count == 0 {
//没有等待中的请求
return
}
//提取请求
var request = _requestQueue[0]
_requestQueue.removeAtIndex(0)
//开始
if request.queuedStart() {
_requestCount++
} else {
//请求失败
}
}
}
func _internalRemoveRequest(request: HDNetQueuedRequest!) -> Bool
{
var i = 0
for item in _requestQueue {
if item == request {
debugPrintln("删除")
_requestQueue.removeAtIndex(i)
return true
}
++i
}
return false
}
}
| mit | 4f417555baa359b69c7de807dabf0b2b | 25.344186 | 81 | 0.542196 | 4.495238 | false | false | false | false |
ryanspillsbury90/HaleMeditates | ios/Hale Meditates/HttpUtil.swift | 1 | 4760 | //
// HTTPUtil.swift
// Hale Meditates
//
// Created by Ryan Pillsbury on 9/4/15.
// Copyright (c) 2015 koait. All rights reserved.
//
import Foundation
import Foundation
class HttpUtil {
enum Method: String {
case OPTIONS = "OPTIONS"
case GET = "GET"
case HEAD = "HEAD"
case POST = "POST"
case PUT = "PUT"
case PATCH = "PATCH"
case DELETE = "DELETE"
case TRACE = "TRACE"
case CONNECT = "CONNECT"
}
static func PUT(urlString: String, body: String? = nil, headers: Dictionary<String, String>?, isAsync: Bool, callback: ((data: NSData?) -> Void)?) -> NSData? {
return request(.PUT, urlString: urlString, body: body, headers: headers, isAsync: isAsync, callback: callback);
}
static func POST(urlString: String, body: String? = nil, headers: Dictionary<String, String>?, isAsync: Bool, callback: ((data: NSData?) -> Void)?) -> NSData? {
return request(.POST, urlString: urlString, body: body, headers: headers, isAsync: isAsync, callback: callback)
}
static func GET(urlString: String, body: String? = nil, headers: Dictionary<String, String>?, isAsync: Bool, callback: ((data: NSData?) -> Void)?) -> NSData? {
return request(.GET, urlString: urlString, body: body, headers: headers, isAsync: isAsync, callback: callback);
}
static func request(method: Method, urlString: String, body: String? = nil, headers: Dictionary<String, String>?, isAsync: Bool, callback: ((data: NSData?) -> Void)?) -> NSData? {
if (isAsync) {
requestAsync(method, urlString: urlString, body: body, headers: headers, callback: callback);
return nil;
} else {
return requestSync(method, urlString: urlString, body: body, headers: headers);
}
}
static func requestAsync(method: Method, urlString: String, body: String? = nil, headers: Dictionary<String, String>?, callback: ((data: NSData?) -> Void)?) {
let qos = Int(QOS_CLASS_USER_INITIATED.rawValue);
dispatch_async(dispatch_get_global_queue(qos, 0)) {
let data = HttpUtil.requestSync(method, urlString: urlString, body: body, headers: headers);
if callback != nil {
callback!(data: data);
}
}
}
static func requestSync(method: Method, urlString: String, body: String? = nil, headers: Dictionary<String, String>?) -> NSData? {
let url = NSURL(string: urlString)
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = method.rawValue;
if headers != nil {
for (header, value) in headers! {
request.setValue(value, forHTTPHeaderField: header)
}
}
let response = AutoreleasingUnsafeMutablePointer<NSURLResponse?>()
do {
return try NSURLConnection.sendSynchronousRequest(request, returningResponse: response)
} catch _ {
return nil
};
}
class Request {
var headers = Dictionary<String, String>();
var url: String!
var body: String?
var method: Method!
var isAsync: Bool!;
var callback: ((data: NSData?) -> Void)?
func sendRequest() -> NSData? {
return HttpUtil.request(method, urlString: url, body: body, headers: headers, isAsync: isAsync, callback: callback)
}
}
class RequestBuilder {
private var request = Request();
func PUT(url: String, body: String? = nil) -> RequestBuilder {
request.method = .PUT;
request.body = body;
return self;
}
func POST(url: String, body: String? = nil) -> RequestBuilder {
request.method = .POST;
request.body = body;
return self;
}
func GET(url: String, body: String? = nil) -> RequestBuilder {
request.method = .GET;
request.body = body;
return self;
}
func addHeaderField(header: String, value: String) -> RequestBuilder {
request.headers[header] = value;
return self;
}
func Sync() -> Request {
request.isAsync = false;
return request;
}
func Callback(callback: ((data: NSData?) -> Void)?) {
request.callback = callback;
}
func Build() -> Request {
return request;
}
func Async() -> Request {
request.isAsync = true;
return request;
}
}
} | mit | 3c8fdd3804edfe2241b0325db0bce600 | 33.007143 | 183 | 0.558193 | 4.537655 | false | false | false | false |
vector-im/vector-ios | Config/BuildSettings.swift | 1 | 17662 | //
// Copyright 2020 Vector Creations Ltd
//
// 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
/// BuildSettings provides settings computed at build time.
/// In future, it may be automatically generated from xcconfig files
@objcMembers
final class BuildSettings: NSObject {
// MARK: - Bundle Settings
static var applicationGroupIdentifier: String {
guard let applicationGroupIdentifier = Bundle.app.object(forInfoDictionaryKey: "applicationGroupIdentifier") as? String else {
fatalError("applicationGroupIdentifier should be defined")
}
return applicationGroupIdentifier
}
static var baseBundleIdentifier: String {
guard let baseBundleIdentifier = Bundle.app.object(forInfoDictionaryKey: "baseBundleIdentifier") as? String else {
fatalError("baseBundleIdentifier should be defined")
}
return baseBundleIdentifier
}
static var keychainAccessGroup: String {
guard let keychainAccessGroup = Bundle.app.object(forInfoDictionaryKey: "keychainAccessGroup") as? String else {
fatalError("keychainAccessGroup should be defined")
}
return keychainAccessGroup
}
static var applicationURLScheme: String? {
guard let urlTypes = Bundle.app.object(forInfoDictionaryKey: "CFBundleURLTypes") as? [AnyObject],
let urlTypeDictionary = urlTypes.first as? [String: AnyObject],
let urlSchemes = urlTypeDictionary["CFBundleURLSchemes"] as? [AnyObject],
let externalURLScheme = urlSchemes.first as? String else {
return nil
}
return externalURLScheme
}
static var pushKitAppIdProd: String {
return baseBundleIdentifier + ".ios.voip.prod"
}
static var pushKitAppIdDev: String {
return baseBundleIdentifier + ".ios.voip.dev"
}
static var pusherAppIdProd: String {
return baseBundleIdentifier + ".ios.prod"
}
static var pusherAppIdDev: String {
return baseBundleIdentifier + ".ios.dev"
}
static var pushKitAppId: String {
#if DEBUG
return pushKitAppIdDev
#else
return pushKitAppIdProd
#endif
}
static var pusherAppId: String {
#if DEBUG
return pusherAppIdDev
#else
return pusherAppIdProd
#endif
}
// Element-Web instance for the app
static let applicationWebAppUrlString = "https://app.element.io"
// MARK: - Localization
/// Whether to allow the app to use a right to left layout or force left to right for all languages
static let disableRightToLeftLayout = true
// MARK: - Server configuration
// Default servers proposed on the authentication screen
static let serverConfigDefaultHomeserverUrlString = "https://matrix.org"
static let serverConfigDefaultIdentityServerUrlString = "https://vector.im"
static let serverConfigSygnalAPIUrlString = "https://matrix.org/_matrix/push/v1/notify"
// MARK: - Legal URLs
// Note: Set empty strings to hide the related entry in application settings
static let applicationCopyrightUrlString = "https://element.io/copyright"
static let applicationPrivacyPolicyUrlString = "https://element.io/privacy"
static let applicationTermsConditionsUrlString = "https://element.io/terms-of-service"
static let applicationHelpUrlString =
"https://element.io/help"
// MARK: - Permalinks
// Hosts/Paths for URLs that will considered as valid permalinks. Those permalinks are opened within the app.
static let permalinkSupportedHosts: [String: [String]] = [
"app.element.io": [],
"staging.element.io": [],
"develop.element.io": [],
"mobile.element.io": [""],
// Historical ones
"riot.im": ["/app", "/staging", "/develop"],
"www.riot.im": ["/app", "/staging", "/develop"],
"vector.im": ["/app", "/staging", "/develop"],
"www.vector.im": ["/app", "/staging", "/develop"],
// Official Matrix ones
"matrix.to": ["/"],
"www.matrix.to": ["/"],
// Client Permalinks (for use with `BuildSettings.clientPermalinkBaseUrl`)
// "example.com": ["/"],
// "www.example.com": ["/"],
]
// For use in clients that use a custom base url for permalinks rather than matrix.to.
// This baseURL is used to generate permalinks within the app (E.g. timeline message permalinks).
// Optional String that when set is used as permalink base, when nil matrix.to format is used.
// Example value would be "https://www.example.com", note there is no trailing '/'.
static let clientPermalinkBaseUrl: String? = nil
// MARK: - VoIP
static var allowVoIPUsage: Bool {
#if canImport(JitsiMeetSDK)
return true
#else
return false
#endif
}
static let stunServerFallbackUrlString: String? = "stun:turn.matrix.org"
// MARK: - Public rooms Directory
// List of homeservers for the public rooms directory
static let publicRoomsDirectoryServers = [
"matrix.org",
"gitter.im"
]
// MARK: - Rooms Screen
static let roomsAllowToJoinPublicRooms: Bool = true
// MARK: - Analytics
/// A type that represents how to set up the analytics module in the app.
///
/// **Note:** Analytics are disabled by default for forks.
/// If you are maintaining a fork, set custom configurations.
struct AnalyticsConfiguration {
/// Whether or not analytics should be enabled.
let isEnabled: Bool
/// The host to use for PostHog analytics.
let host: String
/// The public key for submitting analytics.
let apiKey: String
/// The URL to open with more information about analytics terms.
let termsURL: URL
}
#if DEBUG
/// The configuration to use for analytics during development. Set `isEnabled` to false to disable analytics in debug builds.
static let analyticsConfiguration = AnalyticsConfiguration(isEnabled: BuildSettings.baseBundleIdentifier.starts(with: "im.vector.app"),
host: "https://posthog-poc.lab.element.dev",
apiKey: "rs-pJjsYJTuAkXJfhaMmPUNBhWliDyTKLOOxike6ck8",
termsURL: URL(string: "https://element.io/cookie-policy")!)
#else
/// The configuration to use for analytics. Set `isEnabled` to false to disable analytics.
static let analyticsConfiguration = AnalyticsConfiguration(isEnabled: BuildSettings.baseBundleIdentifier.starts(with: "im.vector.app"),
host: "https://posthog.hss.element.io",
apiKey: "phc_Jzsm6DTm6V2705zeU5dcNvQDlonOR68XvX2sh1sEOHO",
termsURL: URL(string: "https://element.io/cookie-policy")!)
#endif
// MARK: - Bug report
static let bugReportEndpointUrlString = "https://riot.im/bugreports"
// Use the name allocated by the bug report server
static let bugReportApplicationId = "riot-ios"
static let bugReportUISIId = "element-auto-uisi"
// MARK: - Integrations
static let integrationsUiUrlString = "https://scalar.vector.im/"
static let integrationsRestApiUrlString = "https://scalar.vector.im/api"
// Widgets in those paths require a scalar token
static let integrationsScalarWidgetsPaths = [
"https://scalar.vector.im/_matrix/integrations/v1",
"https://scalar.vector.im/api",
"https://scalar-staging.vector.im/_matrix/integrations/v1",
"https://scalar-staging.vector.im/api",
"https://scalar-staging.riot.im/scalar/api",
]
// Jitsi server used outside integrations to create conference calls from the call button in the timeline.
// Setting this to nil effectively disables Jitsi conference calls (given that there is no wellknown override).
// Note: this will not remove the conference call button, use roomScreenAllowVoIPForNonDirectRoom setting.
static let jitsiServerUrl: URL? = URL(string: "https://jitsi.riot.im")
// MARK: - Features
/// Setting to force protection by pin code
static let forcePinProtection: Bool = false
/// Max allowed time to continue using the app without prompting PIN
static let pinCodeGraceTimeInSeconds: TimeInterval = 0
/// Force non-jailbroken app usage
static let forceNonJailbrokenUsage: Bool = true
static let allowSendingStickers: Bool = true
static let allowLocalContactsAccess: Bool = true
static let allowInviteExernalUsers: Bool = true
// MARK: - Side Menu
static let enableSideMenu: Bool = true
static let sideMenuShowInviteFriends: Bool = true
/// Whether to read the `io.element.functional_members` state event and exclude any service members when computing a room's name and avatar.
static let supportFunctionalMembers: Bool = true
// MARK: - Feature Specifics
/// Not allowed pin codes. User won't be able to select one of the pin in the list.
static let notAllowedPINs: [String] = []
/// Maximum number of allowed pin failures when unlocking, before force logging out the user. Defaults to `3`
static let maxAllowedNumberOfPinFailures: Int = 3
/// Maximum number of allowed biometrics failures when unlocking, before fallbacking the user to the pin if set or logging out the user. Defaults to `5`
static let maxAllowedNumberOfBiometricsFailures: Int = 5
/// Indicates should the app log out the user when number of PIN failures reaches `maxAllowedNumberOfPinFailures`. Defaults to `false`
static let logOutUserWhenPINFailuresExceeded: Bool = false
/// Indicates should the app log out the user when number of biometrics failures reaches `maxAllowedNumberOfBiometricsFailures`. Defaults to `false`
static let logOutUserWhenBiometricsFailuresExceeded: Bool = false
static let showNotificationsV2: Bool = true
// MARK: - Main Tabs
static let homeScreenShowFavouritesTab: Bool = true
static let homeScreenShowPeopleTab: Bool = true
static let homeScreenShowRoomsTab: Bool = true
static let homeScreenShowCommunitiesTab: Bool = true
// MARK: - General Settings Screen
static let settingsScreenShowUserFirstName: Bool = false
static let settingsScreenShowUserSurname: Bool = false
static let settingsScreenAllowAddingEmailThreepids: Bool = true
static let settingsScreenAllowAddingPhoneThreepids: Bool = true
static let settingsScreenShowThreepidExplanatory: Bool = true
static let settingsScreenShowDiscoverySettings: Bool = true
static let settingsScreenAllowIdentityServerConfig: Bool = true
static let settingsScreenShowConfirmMediaSize: Bool = true
static let settingsScreenShowAdvancedSettings: Bool = true
static let settingsScreenShowLabSettings: Bool = true
static let settingsScreenAllowChangingRageshakeSettings: Bool = true
static let settingsScreenAllowChangingCrashUsageDataSettings: Bool = true
static let settingsScreenAllowBugReportingManually: Bool = true
static let settingsScreenAllowDeactivatingAccount: Bool = true
static let settingsScreenShowChangePassword:Bool = true
static let settingsScreenShowEnableStunServerFallback: Bool = true
static let settingsScreenShowNotificationDecodedContentOption: Bool = true
static let settingsScreenShowNsfwRoomsOption: Bool = true
static let settingsSecurityScreenShowSessions:Bool = true
static let settingsSecurityScreenShowSetupBackup:Bool = true
static let settingsSecurityScreenShowRestoreBackup:Bool = true
static let settingsSecurityScreenShowDeleteBackup:Bool = true
static let settingsSecurityScreenShowCryptographyInfo:Bool = true
static let settingsSecurityScreenShowCryptographyExport:Bool = true
static let settingsSecurityScreenShowAdvancedUnverifiedDevices:Bool = true
// MARK: - Timeline settings
static let roomInputToolbarCompressionMode: MediaCompressionMode = .prompt
enum MediaCompressionMode {
case prompt, small, medium, large, none
}
// MARK: - Room Creation Screen
static let roomCreationScreenAllowEncryptionConfiguration: Bool = true
static let roomCreationScreenRoomIsEncrypted: Bool = true
static let roomCreationScreenAllowRoomTypeConfiguration: Bool = true
static let roomCreationScreenRoomIsPublic: Bool = false
// MARK: - Room Screen
static let roomScreenAllowVoIPForDirectRoom: Bool = true
static let roomScreenAllowVoIPForNonDirectRoom: Bool = true
static let roomScreenAllowCameraAction: Bool = true
static let roomScreenAllowMediaLibraryAction: Bool = true
static let roomScreenAllowStickerAction: Bool = true
static let roomScreenAllowFilesAction: Bool = true
// Timeline style
static let roomScreenAllowTimelineStyleConfiguration: Bool = true
static let roomScreenTimelineDefaultStyleIdentifier: RoomTimelineStyleIdentifier = .plain
static var isRoomScreenEnableMessageBubblesByDefault: Bool {
return self.roomScreenTimelineDefaultStyleIdentifier == .bubble
}
static let roomScreenUseOnlyLatestUserAvatarAndName: Bool = false
/// Allow split view detail view stacking
static let allowSplitViewDetailsScreenStacking: Bool = true
// MARK: - Room Contextual Menu
static let roomContextualMenuShowMoreOptionForMessages: Bool = true
static let roomContextualMenuShowMoreOptionForStates: Bool = true
static let roomContextualMenuShowReportContentOption: Bool = true
// MARK: - Room Info Screen
static let roomInfoScreenShowIntegrations: Bool = true
// MARK: - Room Settings Screen
static let roomSettingsScreenShowLowPriorityOption: Bool = true
static let roomSettingsScreenShowDirectChatOption: Bool = true
static let roomSettingsScreenAllowChangingAccessSettings: Bool = true
static let roomSettingsScreenAllowChangingHistorySettings: Bool = true
static let roomSettingsScreenShowAddressSettings: Bool = true
static let roomSettingsScreenShowFlairSettings: Bool = true
static let roomSettingsScreenShowAdvancedSettings: Bool = true
static let roomSettingsScreenAdvancedShowEncryptToVerifiedOption: Bool = true
// MARK: - Room Member Screen
static let roomMemberScreenShowIgnore: Bool = true
// MARK: - Message
static let messageDetailsAllowShare: Bool = true
static let messageDetailsAllowPermalink: Bool = true
static let messageDetailsAllowViewSource: Bool = true
static let messageDetailsAllowSave: Bool = true
static let messageDetailsAllowCopyMedia: Bool = true
static let messageDetailsAllowPasteMedia: Bool = true
// MARK: - Notifications
static let decryptNotificationsByDefault: Bool = true
// MARK: - HTTP
/// Additional HTTP headers will be sent by all requests. Not recommended to use request-specific headers, like `Authorization`.
/// Empty dictionary by default.
static let httpAdditionalHeaders: [String: String] = [:]
// MARK: - Authentication Screen
static let authScreenShowRegister = true
static let authScreenShowPhoneNumber = true
static let authScreenShowForgotPassword = true
static let authScreenShowCustomServerOptions = true
static let authScreenShowSocialLoginSection = true
// MARK: - Authentication Options
static let authEnableRefreshTokens = false
// MARK: - Onboarding
static let onboardingShowAccountPersonalization = false
// MARK: - Unified Search
static let unifiedSearchScreenShowPublicDirectory = true
// MARK: - Secrets Recovery
static let secretsRecoveryAllowReset = true
// MARK: - UISI Autoreporting
static let cryptoUISIAutoReportingEnabled = false
// MARK: - Polls
static var pollsEnabled: Bool {
guard #available(iOS 14, *) else {
return false
}
return true
}
// MARK: - Location Sharing
static let tileServerMapStyleURL = URL(string: "https://api.maptiler.com/maps/streets/style.json?key=fU3vlMsMn4Jb6dnEIFsx")!
static var locationSharingEnabled: Bool {
guard #available(iOS 14, *) else {
return false
}
return true
}
static var liveLocationSharingEnabled: Bool {
guard #available(iOS 14, *) else {
return false
}
guard self.locationSharingEnabled else {
return false
}
// Do not enable live location sharing atm
return false
}
}
| apache-2.0 | fb7eb6d0d55d046841bf8c067deaf9d3 | 40.074419 | 156 | 0.688484 | 4.891166 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.