repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
FitGenerator/ImageResizer | refs/heads/master | ImageResizer/CGRectHelpers.swift | mit | 1 | //
// CGRectHelpers.swift
// ImageResizer
//
// Created by Jakub on 13/05/16.
// Copyright © 2016 FitGenerator. All rights reserved.
//
import Foundation
public enum Aspect {
case ScaleToFill
case AspectFit
case AspectFill
}
public func rectForAspect(aspect: Aspect, inputSize: CGSize, maxSize: CGSize) -> CGRect {
switch aspect {
case .ScaleToFill:
return CGRect(origin: CGPointMake(0, 0), size: maxSize)
case .AspectFit, .AspectFill:
let aspectWidth: CGFloat = maxSize.width / inputSize.width
let aspectHeight: CGFloat = maxSize.height / inputSize.height
let aspectRatio: CGFloat
if case .AspectFit = aspect {
aspectRatio = min(aspectWidth, aspectHeight)
} else {
aspectRatio = max(aspectWidth, aspectHeight)
}
var outputRect = CGRect()
outputRect.size.width = inputSize.width * aspectRatio
outputRect.size.height = inputSize.height * aspectRatio
outputRect.origin.x = (maxSize.width - outputRect.size.width) / 2.0
outputRect.origin.y = (maxSize.height - outputRect.size.height) / 2.0
return outputRect
}
}
| 02646990b9535d0fd16f395ca8e979dd | 27.682927 | 89 | 0.657313 | false | false | false | false |
firebase/firebase-ios-sdk | refs/heads/master | FirebaseSessions/Tests/Unit/Mocks/MockIdentifierProvider.swift | apache-2.0 | 1 | //
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
@testable import FirebaseSessions
class MockIdentifierProvider: IdentifierProvider {
var sessionID: String = ""
var previousSessionID: String?
var installationID: String = ""
static let testSessionID = "testSessionID"
static let testPreviousSessionID = "testPreviousSessionID"
static let testInstallationID = "testInstallationID"
func mockAllValidIDs() {
sessionID = MockIdentifierProvider.testSessionID
previousSessionID = MockIdentifierProvider.testPreviousSessionID
installationID = MockIdentifierProvider.testInstallationID
}
}
| 095e835e805f914a3f930d538626aa23 | 31.666667 | 75 | 0.768707 | false | true | false | false |
RayTao/CoreAnimation_Collection | refs/heads/master | CoreAnimation_Collection/Animations/Gooey/TabbarMenu.swift | mit | 1 | //
// TabbarMenu.swift
// GooeyTabbar
//
// Created by KittenYang on 11/16/15.
// Copyright © 2015 KittenYang. All rights reserved.
//
import UIKit
class TabbarMenu: UIView{
/// 是否打开
var opened : Bool = false
fileprivate var normalRect : UIView!
fileprivate var springRect : UIView!
fileprivate var keyWindow : UIWindow!
fileprivate var blurView : UIVisualEffectView!
fileprivate var displayLink : CADisplayLink!
fileprivate var animationCount : Int = 0
fileprivate var diff : CGFloat = 0
fileprivate var terminalFrame : CGRect?
fileprivate var initialFrame : CGRect?
fileprivate var animateButton : AnimatedButton?
let TOPSPACE : CGFloat = 64.0 //留白
fileprivate var tabbarheight : CGFloat? //tabbar高度
init(tabbarHeight : CGFloat)
{
tabbarheight = tabbarHeight
terminalFrame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height)
initialFrame = CGRect(x: 0, y: UIScreen.main.bounds.height - tabbarHeight - TOPSPACE, width: terminalFrame!.width, height: terminalFrame!.height)
super.init(frame: initialFrame!)
setUpViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: CGRect)
{
let path = UIBezierPath()
path.move(to: CGPoint(x: 0, y: self.frame.height))
path.addLine(to: CGPoint(x: self.frame.width, y: self.frame.height))
path.addLine(to: CGPoint(x: self.frame.width, y: TOPSPACE))
path.addQuadCurve(to: CGPoint(x: 0, y: TOPSPACE), controlPoint: CGPoint(x: self.frame.width/2, y: TOPSPACE-diff))
path.close()
let context = UIGraphicsGetCurrentContext()
context?.addPath(path.cgPath)
UIColor(colorLiteralRed: 50/255.0, green: 58/255.0, blue: 68/255.0, alpha: 1.0).set()
context?.fillPath()
}
fileprivate func setUpViews()
{
keyWindow = UIApplication.shared.keyWindow
blurView = UIVisualEffectView(effect: UIBlurEffect(style: .dark))
blurView.frame = self.bounds
blurView.alpha = 0.0
keyWindow.addSubview(blurView)
self.backgroundColor = UIColor.clear
keyWindow.addSubview(self)
normalRect = UIView(frame: CGRect(x: 0, y: UIScreen.main.bounds.size.height - 30 - 50, width: 30, height: 30))
normalRect.backgroundColor = UIColor.blue
normalRect.isHidden = true
keyWindow.addSubview(normalRect)
springRect = UIView(frame: CGRect(x: UIScreen.main.bounds.size.width/2 - 30/2, y: normalRect.frame.origin.y, width: 30, height: 30))
springRect.backgroundColor = UIColor.yellow
springRect.isHidden = true
keyWindow.addSubview(springRect)
animateButton = AnimatedButton(frame: CGRect(x: 0, y: TOPSPACE + (tabbarheight! - 30)/2, width: 50, height: 30))
self.addSubview(animateButton!)
animateButton!.didTapped = { (button) -> () in
self.triggerAction()
}
}
func triggerAction()
{
if animateButton!.animating {
return
}
/**
* 展开
*/
if !opened {
opened = true
startAnimation()
UIView.animate(withDuration: 0.3, delay: 0.0, options: .curveEaseOut, animations: { () -> Void in
self.springRect.center = CGPoint(x: self.springRect.center.x, y: self.springRect.center.y - 40)
}) { (finish) -> Void in
UIView.animate(withDuration: 0.3, delay: 0.0, options: .curveEaseOut, animations: { () -> Void in
self.frame = self.terminalFrame!
}, completion: nil)
UIView.animate(withDuration: 0.3, delay: 0.2, options: .curveEaseOut, animations: { () -> Void in
self.normalRect.center = CGPoint(x: self.normalRect.center.x, y: 100)
self.blurView.alpha = 1.0
}, completion: nil)
UIView.animate(withDuration: 1.0, delay: 0.2, usingSpringWithDamping: 0.6, initialSpringVelocity: 0.0, options: .curveEaseOut, animations: { () -> Void in
self.springRect.center = CGPoint(x: self.springRect.center.x, y: 100)
}, completion: { (finish) -> Void in
self.finishAnimation()
})
}
}else{
/**
* 收缩
*/
opened = false
startAnimation()
UIView.animate(withDuration: 0.3, delay: 0.0, options: .curveEaseOut, animations: { () -> Void in
self.frame = self.initialFrame!
}, completion: nil)
UIView.animate(withDuration: 0.3, delay: 0.0, options: .curveEaseOut, animations: { () -> Void in
self.normalRect.center = CGPoint(x: self.normalRect.center.x, y: UIScreen.main.bounds.size.height - 30 - 50)
self.blurView.alpha = 0.0
}, completion: nil)
UIView.animate(withDuration: 0.2, delay:0.0, options: .curveEaseOut, animations: { () -> Void in
self.springRect.center = CGPoint(x: self.springRect.center.x, y: UIScreen.main.bounds.size.height - 30 - 50 + 10)
}, completion: { (finish) -> Void in
UIView.animate(withDuration: 0.2, delay: 0.0, options: .curveEaseOut, animations: { () -> Void in
self.springRect.center = CGPoint(x: self.springRect.center.x, y: UIScreen.main.bounds.size.height - 30 - 50 - 40)
}, completion: { (finish) -> Void in
UIView.animate(withDuration: 0.2, delay: 0.0, options: .curveEaseOut, animations: { () -> Void in
self.springRect.center = CGPoint(x: self.springRect.center.x, y: UIScreen.main.bounds.size.height - 30 - 50)
}, completion: { (finish) -> Void in
self.finishAnimation()
})
})
})
}
}
@objc fileprivate func update(_ displayLink: CADisplayLink)
{
let normalRectLayer = normalRect.layer.presentation()
let springRectLayer = springRect.layer.presentation()
let normalRectFrame = (normalRectLayer!.value(forKey: "frame")! as AnyObject).cgRectValue
let springRectFrame = (springRectLayer!.value(forKey: "frame")! as AnyObject).cgRectValue
diff = (normalRectFrame?.origin.y)! - (springRectFrame?.origin.y)!
print("=====\(diff)")
self.setNeedsDisplay()
}
fileprivate func startAnimation()
{
if displayLink == nil
{
self.displayLink = CADisplayLink(target: self, selector: #selector(TabbarMenu.update(_:)))
self.displayLink.add(to: RunLoop.main, forMode: RunLoopMode.defaultRunLoopMode)
}
animationCount += 1
}
fileprivate func finishAnimation()
{
animationCount -= 1
if animationCount == 0
{
displayLink.invalidate()
displayLink = nil
}
}
}
| 6adc0a68b47703c1513a5771ce500dfd | 34.356383 | 164 | 0.641192 | false | false | false | false |
Superkazuya/zimcher2015 | refs/heads/master | Zimcher/Utils/NetworkingHelper/TaskCreator.swift | apache-2.0 | 2 | //
// NetworkingUpload.swift
// SwiftPort
//
// Created by Weiyu Huang on 10/30/15.
// Copyright © 2015 Kappa. All rights reserved.
//
import Foundation
extension Networking {
//upload
@warn_unused_result(message="Did you forget to call `resume` on the task?")
static func task(endPoint: APIEndPoint, payload: Any?, header: [String: String]? = nil, session: NSURLSession? = nil, completionHandler:Networking.responseHandler = Networking.defaultResopnseHandler) -> NSURLSessionTask
{
let request = NSMutableURLRequest(URL: endPoint.url)
request.HTTPMethod = endPoint.method.rawValue
let payloadData: Payload?
if let p = payload {
if let explictType = endPoint.payloadType {
payloadData = Payload(type: explictType, data: p)
} else {
payloadData = Payload(data: p)
}
if let d = payloadData?.dataOrStream as? NSData {
request.HTTPBody = d
} else {
request.HTTPBodyStream = payloadData?.dataOrStream as? NSInputStream
}
} else {
payloadData = nil
}
for (k, v) in header ?? [:] {
request.setValue(v, forHTTPHeaderField: k)
}
for (k, v) in payloadData?.headers ?? [:] {
request.setValue(v, forHTTPHeaderField: k)
}
return (session ?? NSURLSession.sharedSession())
.dataTaskWithRequest(request, completionHandler: completionHandler)
}
//decorator
//create task specific functions
static func createTargetFunction(endPoint: APIEndPoint, session: NSURLSession? = nil) -> (payload: Any?, completionHandler: Networking.responseHandler?) -> NSURLSessionTask?
{
return { data, handler in
if let h = handler {
return task(endPoint, payload: data, session: session, completionHandler: h)
}
return task(endPoint, payload: data, session: session)
}
}
// MARK: User related
//@warn_unused_result(message="Did you forget to call `resume` on the task?")
static let userRegisterWithUserJSON = Networking.createTargetFunction(ENDPOINT.USER.REGISTER)
//@warn_unused_result(message="Did you forget to call `resume` on the task?")
static let userLoginWithUserJSON = Networking.createTargetFunction(ENDPOINT.USER.FIND_BY_EMAIL)
// MARK: Media upload
static let mediaUploadWithMultipartFormData = Networking.createTargetFunction(ENDPOINT.MEDIA.UPLOAD)
static let getAllMediaInfo = Networking.createTargetFunction(ENDPOINT.MEDIA.ALL_VIDEOS)
}
| b3066fb6fa42c51d14339af975b2d75a | 33.772152 | 223 | 0.621041 | false | false | false | false |
Plopix/Dose | refs/heads/master | DoseTests/Service/SimpleLogger.swift | mit | 1 | //
// SimpleLogger.swift
// Dose
//
// Created by Sebastien Morel on 6/24/15.
// Copyright (c) 2015 Plopix. All rights reserved.
//
import Foundation
/// Simple Logger Implementation
public class SimpleLogger : LoggerProtocol {
/// Debug enable?
private let debug_enabled: Bool;
/**
Constructor
- parameter debug: Enable or not the debugOutput
- returns: The SimpleLogger
*/
public init(_ debug: Bool) {
debug_enabled = debug
}
/**
isDebugOutputEnabled
*/
public func isDebugOutputEnabled() -> Bool {
return debug_enabled
}
/**
Print a verbose message
- parameter message: The message
- parameter function: Function
- parameter file: File
- parameter line: Line
*/
public func verbose(message: String, function: String = #function, file: String = #file, line: Int = #line) {
if (debug_enabled) {
print("V: \"\(message)\" (File: \(file), Function: \(function), Line: \(line))")
}
}
/**
Print a debug message
- parameter message: The message
- parameter function: Function
- parameter file: File
- parameter line: Line
*/
public func debug(message: String, function: String = #function, file: String = #file, line: Int = #line) {
if (debug_enabled) {
print("D: \"\(message)\" (File: \(file), Function: \(function), Line: \(line))")
}
}
/**
Print an info message
- parameter message: The message
- parameter function: Function
- parameter file: File
- parameter line: Line
*/
public func info(message: String, function: String = #function, file: String = #file, line: Int = #line) {
if (debug_enabled) {
print("I: \"\(message)\" (File: \(file), Function: \(function), Line: \(line))")
}
}
/**
Print a warning message
- parameter message: The message
- parameter function: Function
- parameter file: File
- parameter line: Line
*/
public func warning(message: String, function: String = #function, file: String = #file, line: Int = #line) {
if (debug_enabled) {
print("W: \"\(message)\" (File: \(file), Function: \(function), Line: \(line))")
}
}
/**
Print an error message
- parameter message: The message
- parameter function: Function
- parameter file: File
- parameter line: Line
*/
public func error(message: String, function: String = #function, file: String = #file, line: Int = #line) {
if (debug_enabled) {
print("E: \"\(message)\" (File: \(file), Function: \(function), Line: \(line))")
}
}
/**
Print a severe message
- parameter message: The message
- parameter function: Function
- parameter file: File
- parameter line: Line
*/
public func severe(message: String, function: String = #function, file: String = #file, line: Int = #line) {
if (debug_enabled) {
print("S: \"\(message)\" (File: \(file), Function: \(function), Line: \(line))")
}
}
} | cef6850420c52032dce2ca96b5517fab | 25.422764 | 113 | 0.558941 | false | false | false | false |
vmanot/swift-package-manager | refs/heads/master | Sources/Utility/Diagnostics.swift | apache-2.0 | 1 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import Basic
/// Represents an object which can be converted into a diagnostic data.
public protocol DiagnosticDataConvertible {
/// Diagnostic data representation of this instance.
var diagnosticData: DiagnosticData { get }
}
/// DiagnosticData wrapper for Swift errors.
public struct AnyDiagnostic: DiagnosticData {
public static let id = DiagnosticID(
type: AnyDiagnostic.self,
name: "org.swift.diags.anyerror",
description: {
$0 <<< { "\($0.anyError)" }
}
)
public let anyError: Swift.Error
public init(_ error: Swift.Error) {
self.anyError = error
}
}
/// Represents unknown diagnosic location.
public final class UnknownLocation: DiagnosticLocation {
/// The singleton instance.
public static let location = UnknownLocation()
private init() {}
public var localizedDescription: String {
return "<unknown>"
}
}
extension DiagnosticsEngine {
/// Emit a diagnostic with an unknown location.
public func emit(data: DiagnosticData) {
emit(data: data, location: UnknownLocation.location)
}
/// Emit a Swift error.
///
/// Errors will be converted into diagnostic data if possible.
/// Otherwise, they will be emitted as AnyDiagnostic.
public func emit(
_ error: Swift.Error,
location: DiagnosticLocation = UnknownLocation.location
) {
if let diagnosticData = error as? DiagnosticData {
emit(data: diagnosticData, location: location)
} else if case let convertible as DiagnosticDataConvertible = error {
emit(convertible, location: location)
} else {
emit(data: AnyDiagnostic(error), location: location)
}
}
/// Emit a diagnostic data convertible instance.
public func emit(
_ convertible: DiagnosticDataConvertible,
location: DiagnosticLocation = UnknownLocation.location
) {
emit(data: convertible.diagnosticData, location: location)
}
/// Wrap a throwing closure, returning an optional value and
/// emitting any thrown errors.
///
/// - Parameters:
/// - closure: Closure to wrap.
/// - Returns: Returns the return value of the closure wrapped
/// into an optional. If the closure throws, nil is returned.
public func wrap<T>(
with constuctLocation: @autoclosure () -> (DiagnosticLocation) = UnknownLocation.location,
_ closure: () throws -> T
) -> T? {
do {
return try closure()
} catch {
emit(error, location: constuctLocation())
return nil
}
}
/// Wrap a throwing closure, returning a success boolean and
/// emitting any thrown errors.
///
/// - Parameters:
/// - closure: Closure to wrap.
/// - Returns: Returns true if the wrapped closure did not throw
/// and false otherwise.
@discardableResult
public func wrap(
with constuctLocation: @autoclosure () -> (DiagnosticLocation) = UnknownLocation.location,
_ closure: () throws -> Void
) -> Bool {
do {
try closure()
return true
} catch {
emit(error, location: constuctLocation())
return false
}
}
}
/// Namespace for representing diagnostic location of a package.
public enum PackageLocation {
/// Represents location of a locally available package. This could be root
/// package, edited dependency or checked out dependency.
public struct Local: DiagnosticLocation {
/// The name of the package, if known.
public let name: String?
/// The path to the package.
public let packagePath: AbsolutePath
public init(name: String? = nil, packagePath: AbsolutePath) {
self.name = name
self.packagePath = packagePath
}
public var localizedDescription: String {
let stream = BufferedOutputByteStream()
if let name = name {
stream <<< "Package: \(name) "
}
stream <<< packagePath.asString
return stream.bytes.asString!
}
}
/// Represents location a remote package with no checkout on disk.
public struct Remote: DiagnosticLocation {
/// The URL of the package.
public let url: String
/// The source control reference of the package. It could be version, branch, revision etc.
public let reference: String
public init(url: String, reference: String) {
self.url = url
self.reference = reference
}
public var localizedDescription: String {
return url + " @ " + reference
}
}
}
| 44ee58a2f572d360383f0d311a520d02 | 29.266272 | 99 | 0.624242 | false | false | false | false |
24/ios-o2o-c | refs/heads/master | gxc/Order/CommonOrderViewController.swift | mit | 1 | //
// CommonOrderViewController.swift
// gxc
//
// Created by gx on 14/12/8.
// Copyright (c) 2014年 zheng. All rights reserved.
//
import Foundation
class CommonOrderViewController: UIViewController ,RSTapRateViewDelegate {
var txtView = UITextView()
var tapRateView = RSTapRateView()
var orderDetail = GXViewState.OrderDetail
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "bar_back.png"), style: UIBarButtonItemStyle.Done, target: self, action: Selector("NavigationControllerBack"))
/*navigation 不遮住View*/
self.automaticallyAdjustsScrollViewInsets = false
self.edgesForExtendedLayout = UIRectEdge()
/*self view*/
self.view.backgroundColor = UIColor.whiteColor()
//superview
let superview: UIView = self.view
/* navigation titleView */
self.navigationController?.navigationBar.barTintColor = UIColor(fromHexString: "#008FD7")
var navigationBar = self.navigationController?.navigationBar
navigationBar?.tintColor = UIColor.whiteColor()
self.navigationItem.title = "预约送衣"
tapRateView.delegate = self
tapRateView.backgroundColor = UIColor.whiteColor()
self.view.addSubview(tapRateView)
tapRateView.textLabel.text = ""
tapRateView.rating = 4
tapRateView.snp_makeConstraints { make in
make.left.equalTo(CGPointZero)
make.top.equalTo(superview)
make.width.equalTo(superview)
make.height.equalTo(45)
}
self.view.addSubview(txtView)
txtView.snp_makeConstraints { make in
make.top.equalTo(self.tapRateView.snp_bottom).offset(20)
make.left.equalTo(CGPointZero).offset(5)
make.right.equalTo(superview.snp_right).offset(-5)
make.height.equalTo(150)
}
// txtView.backgroundColor = UIColor.grayColor()
txtView.autoresizingMask = UIViewAutoresizing.FlexibleHeight
txtView.autoresizingMask = UIViewAutoresizing.FlexibleHeight
txtView.layer.borderColor = UIColor(fromHexString: "#008FD7").CGColor
txtView.layer.borderWidth = 1.0;
txtView.layer.cornerRadius = 5.0;
var commentBtn = UIButton()
commentBtn.layer.cornerRadius = 4
commentBtn.addTarget(self, action: Selector("commentOrder"), forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(commentBtn)
commentBtn.setTitle("提交评论", forState: UIControlState.Normal)
commentBtn.backgroundColor = UIColor(fromHexString: "#E61D4C")
commentBtn.snp_makeConstraints { make in
make.top.equalTo(self.txtView.snp_bottom).offset(50)
make.left.equalTo(CGPointZero).offset(5)
make.right.equalTo(superview).offset(-5)
make.width.equalTo(superview)
make.height.equalTo(40)
}
// Do any additional setup after loading the view, typically from a nib.
}
func commentOrder()
{
MBProgressHUD.showHUDAddedTo(self.view, animated: true)
var rating = String(self.tapRateView.rating)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("AddCommentSuccess:"), name: GXNotifaction_User_Orders_AddCommon, object: nil)
var orderId = orderDetail.shopDetail!.OrderId!
var content = txtView.text!
var token = GXViewState.userInfo.Token!
GxApiCall().AddOrderComment(NSString(format: "%.0f", orderId), content: content, token: token, score: rating)
}
func AddCommentSuccess(notif :NSNotification)
{
MBProgressHUD.hideHUDForView(self.view, animated: true)
SweetAlert().showAlert("", subTitle: "评论添加成功!", style: AlertStyle.Success)
self.navigationController?.popViewControllerAnimated(true)
}
func tapDidRateView(view:RSTapRateView,rating:Int)
{
// NSLog(@"Current rating: %i", rating);
println(rating)
}
func NavigationControllerBack()
{
self.navigationController?.popViewControllerAnimated(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| b63c92c3a8f6f9f508be0170c1f3aa3c | 34.4375 | 204 | 0.645062 | false | false | false | false |
thombles/Flyweight | refs/heads/master | Flyweight/Data/DataClasses.swift | apache-2.0 | 1 | // Flyweight - iOS client for GNU social
// Copyright 2017 Thomas Karpiniec
//
// 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 CoreData
@objc(AccountMO)
public class AccountMO: NSManagedObject {
@NSManaged var id: Int64
@NSManaged var server: String
@NSManaged var type: String
@NSManaged var username: String
// Non-optionals need values
override public func awakeFromInsert() {
id = 0
server = ""
type = ""
username = ""
}
}
@objc(NoticeInGSTimelineMO)
public class NoticeInGSTimelineMO: NSManagedObject {
@NSManaged var gsTimeline: GSTimelineMO?
@NSManaged var noticeId: Int64
@NSManaged var notice: NoticeMO?
@NSManaged var previousNotice: NoticeMO?
override public func awakeFromInsert() {
noticeId = 0
}
}
| c5293c200f73c0653015f7837b55a3da | 27.659574 | 75 | 0.705271 | false | false | false | false |
msdgwzhy6/Sleipnir | refs/heads/master | Sleipnir/Sleipnir/Util/Array.swift | mit | 1 | //
// Array.swift
// Sleipnir
//
// Created by Artur Termenji on 6/19/14.
// Copyright (c) 2014 railsware. All rights reserved.
//
import Foundation
extension Array {
mutating func shuffle() {
for var i = self.count - 1; i >= 1; i-- {
let j = Int(random() % (i+1))
swap(&self[i], &self[j])
}
}
}
extension Array : Equatable { }
public func ==<T>(lhs: Array<T>, rhs: Array<T>) -> Bool {
return lhs._bridgeToObjectiveC() == rhs._bridgeToObjectiveC()
}
| d5307a5af6ce7fd3d7854ddfd1ec6782 | 19 | 65 | 0.555769 | false | false | false | false |
material-components/material-components-ios-codelabs | refs/heads/master | MDC-102/Swift/Complete/Shrine/Shrine/CustomLayout.swift | apache-2.0 | 4 | /*
Copyright 2018-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 UIKit
private let HORIZONTAL_PADDING: CGFloat = 0.10
class CustomLayout: UICollectionViewLayout {
var itemASize: CGSize = .zero
var itemBSize: CGSize = .zero
var itemCSize: CGSize = .zero
var itemAOffset: CGPoint = .zero
var itemBOffset: CGPoint = .zero
var itemCOffset: CGPoint = .zero
var tripleSize: CGSize = .zero
var frameCache = [NSValue]()
override init() {
super.init()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func prepare() {
super.prepare()
var parentFrame = self.collectionView!.bounds.standardized
parentFrame = UIEdgeInsetsInsetRect(parentFrame, self.collectionView!.adjustedContentInset)
let contentHeight = parentFrame.size.height -
(self.collectionView!.contentInset.top + self.collectionView!.contentInset.bottom)
let contentWidth = parentFrame.size.width
let landscapeItemSize = CGSize(width: contentWidth * 0.46, height: contentHeight * 0.32)
let portaitItemSize = CGSize(width: contentWidth * 0.3, height: contentHeight * 0.54)
self.itemASize = landscapeItemSize
self.itemBSize = landscapeItemSize
self.itemCSize = portaitItemSize
self.itemAOffset = CGPoint(x: contentWidth * HORIZONTAL_PADDING, y: contentHeight * 0.66)
self.itemBOffset = CGPoint(x: contentWidth * 0.3, y: contentHeight * 0.16)
self.itemCOffset = CGPoint(x: self.itemBOffset.x + self.itemBSize.width + contentWidth * HORIZONTAL_PADDING, y: contentHeight * 0.2)
self.tripleSize = CGSize(width: self.itemCOffset.x + self.itemCSize.width, height: contentHeight)
self.frameCache.removeAll()
for itemIndex in 0..<self.collectionView!.numberOfItems(inSection:0) {
let tripleCount = itemIndex / 3
let internalIndex = itemIndex % 3
var itemFrame: CGRect = .zero
if (internalIndex == 2) {
itemFrame.size = self.itemCSize
} else if (internalIndex == 1) {
itemFrame.size = self.itemBSize
} else {
itemFrame.size = self.itemASize
}
itemFrame.origin.x = self.tripleSize.width * CGFloat(tripleCount)
if (internalIndex == 2) {
itemFrame.origin.x += self.itemCOffset.x
itemFrame.origin.y = self.itemCOffset.y
} else if (internalIndex == 1) {
itemFrame.origin.x += self.itemBOffset.x
itemFrame.origin.y = self.itemBOffset.y
} else {
itemFrame.origin.x += self.itemAOffset.x
itemFrame.origin.y = self.itemAOffset.y
}
let frameValue: NSValue = NSValue(cgRect: itemFrame)
self.frameCache.append(frameValue)
}
}
override var collectionViewContentSize: CGSize {
get {
var contentSize: CGSize = .zero
contentSize.height = self.tripleSize.height
let lastItemFrameValue: NSValue = self.frameCache.last!
let lastItemFrame = lastItemFrameValue.cgRectValue
contentSize.width = lastItemFrame.maxX + HORIZONTAL_PADDING * self.collectionView!.frame.width
return contentSize
}
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var visibleLayoutAttributes = [UICollectionViewLayoutAttributes]()
for itemIndex in 0..<self.frameCache.count {
let itemFrame = self.frameCache[itemIndex].cgRectValue
if rect.intersects(itemFrame) {
let indexPath = IndexPath(row: itemIndex, section: 0)
let attributes = self.collectionView!.layoutAttributesForItem(at: indexPath)!
attributes.frame = itemFrame
visibleLayoutAttributes.append(attributes)
}
}
return visibleLayoutAttributes
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
let tripleCount = indexPath.row / 3
let internalIndex = indexPath.row % 3
var itemFrame: CGRect = .zero
if (internalIndex == 2) {
itemFrame.size = self.itemCSize
} else if (internalIndex == 1) {
itemFrame.size = self.itemBSize
} else {
itemFrame.size = self.itemASize
}
itemFrame.origin.x = self.tripleSize.width * CGFloat(tripleCount)
if (internalIndex == 2) {
itemFrame.origin.x += self.itemCOffset.x
itemFrame.origin.y = self.itemCOffset.y
} else if (internalIndex == 1) {
itemFrame.origin.x += self.itemBOffset.x
itemFrame.origin.y = self.itemBOffset.y
} else {
itemFrame.origin.x += self.itemAOffset.x
itemFrame.origin.y = self.itemAOffset.y
}
let attributes = UICollectionViewLayoutAttributes.init(forCellWith: indexPath)
attributes.frame = itemFrame
return attributes
}
override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return true
}
}
| 7a6169a623174b203c2fd90702c3e440 | 33.165605 | 136 | 0.704139 | false | false | false | false |
jacobjiggler/FoodMate | refs/heads/master | src/iOS/FoodMate/ManualItemViewController.swift | mit | 1 | //
// ManualItemViewController.swift
// FoodMate
//
// Created by Jordan Horwich on 9/13/14.
// Copyright (c) 2014 FoodMate. All rights reserved.
//
import UIKit
class ManualItemViewController: UIViewController {
@IBOutlet weak var itemNameTextField: UITextField!
@IBOutlet weak var itemPriceTextField: UITextField!
@IBOutlet weak var barCodeTextField: UITextField!
@IBOutlet weak var daysToExpireTextField: UITextField!
var itemBarcode: String = ""
var itemName: String = ""
var parentView:UIViewController!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewDidAppear(animated: Bool) {
barCodeTextField.text = itemBarcode
var query : PFQuery = PFQuery(className: "Food_item")
query.whereKey("barcode", equalTo: itemBarcode)
query.findObjectsInBackgroundWithBlock({(objects:[AnyObject]!, NSError error) in
if (error != nil) {
NSLog("error " + error.localizedDescription)
}
else {
print(objects)
if objects.count > 0 {
var objQuery : PFQuery = PFQuery(className: "Food_item")
objQuery.getObjectInBackgroundWithId(objects[0].objectId) {
(item: PFObject!, error: NSError!) -> Void in
self.itemNameTextField.text = item["name"] as String
self.itemPriceTextField.text = String(format: "%.2f", item["price"].floatValue)
if item["expiration"] != nil {
self.daysToExpireTextField.text = String(item["expiration"] as Int)
}
}
}
// self.foodData = objects
// self.tableView.reloadData()
}
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func initwithBarcode(barcode: String) {
itemBarcode = barcode
}
override func viewDidDisappear(animated: Bool) {
//parentView.dismissViewControllerAnimated(false, completion: nil)
}
/*
// 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.
}
*/
/////////////////////
// Button Bar Actions
/////////////////////
@IBAction func cancelButtonClicked(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func doneButtonClicked(sender: AnyObject) {
// send Parse requests here and then reload the table
}
@IBAction func removeButtonClicked(sender: AnyObject) {
var query = PFQuery(className: "Food_item")
query.whereKey("name", equalTo: itemNameTextField.text)
var item = query.getFirstObject()
if item == nil {
var newItem = PFObject(className: "Food_item")
newItem["name"] = self.itemNameTextField.text
newItem["price"] = (self.itemPriceTextField.text as NSString).floatValue
if (self.barCodeTextField.text != "") {
newItem["barcode"] = self.barCodeTextField.text
}
if (self.daysToExpireTextField.text != "") {
newItem["expiration"] = self.daysToExpireTextField.text.toInt()
}
newItem["inStock"] = false
newItem.saveInBackground()
} else {
item["price"] = (self.itemPriceTextField.text as NSString).floatValue
if (self.barCodeTextField.text != "") {
item["barcode"] = self.barCodeTextField.text
}
if (self.daysToExpireTextField.text != "") {
item["expiration"] = self.daysToExpireTextField.text.toInt()
}
item["inStock"] = false
item.saveInBackground()
}
self.dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func addButtonClicked(sender: AnyObject) {
// var foobar = PFQuery(className: "_User")
// foobar.whereKey("username", equalTo: "jordan")
// foobar.findObjectsInBackgroundWithBlock({(objects:[AnyObject]!, NSError error) in
// if (error != nil) {
// NSLog("error " + error.localizedDescription)
// }
// else {
// print("################")
// print(objects)
// }
// })
//
//
//
var codedObjId = PFQuery(className: "Group").getFirstObject()
var query = PFQuery(className: "Food_item")
query.whereKey("name", equalTo: itemNameTextField.text)
var item = query.getFirstObject()
if item == nil {
var newItem = PFObject(className: "Food_item")
newItem["name"] = self.itemNameTextField.text
newItem["price"] = (self.itemPriceTextField.text as NSString).floatValue
if !self.barCodeTextField.text.isEmpty {
newItem["barcode"] = self.barCodeTextField.text
}
if !self.daysToExpireTextField.text.isEmpty {
newItem["expiration"] = self.daysToExpireTextField.text.toInt()
}
newItem["inStock"] = true
newItem["groupId"] = codedObjId
newItem.saveInBackground()
} else {
item["price"] = (self.itemPriceTextField.text as NSString).floatValue
if (self.barCodeTextField.text != "") {
item["barcode"] = self.barCodeTextField.text
}
if (self.daysToExpireTextField.text != "") {
item["expiration"] = self.daysToExpireTextField.text.toInt()
}
item["inStock"] = true
item["groupId"] = codedObjId
item.saveInBackground()
}
self.dismissViewControllerAnimated(true, completion: nil)
}
}
| 7ae96c3e11f29808c5610e20a4789218 | 36.011561 | 106 | 0.567859 | false | false | false | false |
rowungiles/SwiftTech | refs/heads/master | SwiftTech/SwiftTech/Utilities/Search/CollectionTrie.swift | gpl-3.0 | 1 | //
// CollectionTrie.swift
// SwiftTech
//
// Created by Rowun Giles on 20/01/2016.
// Copyright © 2016 Rowun Giles. All rights reserved.
//
import Foundation
protocol CollectionTrie {}
extension CollectionTrie {
static internal func findRecursively<T: RangeReplaceableCollectionType, U: Equatable where T.Generator.Element == U>(findCollection: T, node: TrieNode<U>) -> TrieNode<U>? {
var collection = findCollection
guard !collection.isEmpty else {
return node
}
let key = collection.removeFirst()
if let childNode = node.children[key] {
return findRecursively(collection, node: childNode)
}
return nil
}
static internal func addRecursively<T: RangeReplaceableCollectionType, U: Equatable where T.Generator.Element == U>(addCollection: T, addNode: TrieNode<U>) -> TrieNode<U> {
var collection = addCollection
var node = addNode
guard !collection.isEmpty else {
node.isFinal = true
return node
}
let key = collection.removeFirst()
let childNode = node.children[key] ?? TrieNode()
node.children[key] = addRecursively(collection, addNode: childNode)
return node
}
}
| f696651f7942185f4c179d397c546fb8 | 26.38 | 176 | 0.596786 | false | false | false | false |
ben-ng/swift | refs/heads/master | validation-test/compiler_crashers_fixed/01385-swift-typedecl-getdeclaredtype.swift | apache-2.0 | 1 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
func d<b.g == A: A : $0) {
enum A {
func c: A {
S.C(v: c: [T) -> e(AnyObject, T)
}
}
t: a {
i<C
}
class A where Optional<Int
print() {
}
}
typealias R
}
var d = .e {
func a(.Type) -> (g<h.init(A, AnyObject> {
return g(self.b
class a())
}
convenience init()
}
import Foundation
}
for (bytes: e(()
}
return {
class func b<T>(self.B
return d: B<l : Any) -> T, self.C(object1, range: ()(Any, object2: 1]], f: A, (h.Element == [T {
typealias b {
return "
}
extension A {
}
return { _, x }
}
let n1: A {
var b = B<T) -> S) { _, T -> V, e: (a)
}
func d.join(c {
self.c = a<I : 1)
switch x = a<T? {
protocol d = [c: T? {
}
class a {
struct c : ()
return b(T, length: S<d: b = nil
func a<c() {
case c>()))
return nil
}
var d, A {
struct c {
func c() -> {
typealias h>(.count](a<3))
}
return true
class d
b, x = 1)
}
private let n1: d : a<d(n: Any) as [self.B == "".advance(mx : NSObject {
init())
}
func d: T
}
typealias e = [unowned self.init()
enum S) {
}
self] in
class a<Q<T) -> V {
}
}
}
class a {
case s()
class A.Iterator.count]
}
enum A : String {
func d<h : [unowned self.E == compose<T] = [c()
}
typealias A {
}
let c in return S.join() {
protocol a {
}
b
return d.B
struct e {
func g(range: H) -> ()
}
var d>(c = { }
}
assert() -> : A? {
return b: String {
typealias e == Swift.init(a: Hashable> String {
class A {
print(s(self.startIndex)"foobar"")
}
let start = b<T
| 854058d69ec2b8df8768235855495dc0 | 15.523364 | 96 | 0.602376 | false | false | false | false |
gtranchedone/AlgorithmsSwift | refs/heads/master | Algorithms.playground/Pages/Problem - Search First Occurrence.xcplaygroundpage/Contents.swift | mit | 1 | /*: [Previous](@previous)
# Search a sorted array for first occurrence of k
### Write a method that takes a sorted array and a key and returns the index of the first occurrence of that key in the array. For example, in the array [-14, -10, 2, 108, 108, 243, 285, 285, 285, 401], when searching for 108, the algorithm should return the index 3 and when searching for 285 it should return index 6.
*/
// use binary search but don’t stop when the first element is found
func indexOfFirstOccurrenceOf<T where T: Comparable>(element: T, inArray array: [T]) -> Int? {
guard !array.isEmpty else { return nil }
var low = 0, high = array.count - 1, result: Int? = nil
while (low <= high) {
let mid = low + ((high - low) / 2)
if array[mid] <= element {
high = mid - 1
if array[mid] == element {
result = mid // this is always the lowest match found
}
}
else {
low = mid + 1
}
}
return result
}
let array = [-14, -10, 2, 108, 108, 243, 285, 285, 285, 401]
array.indexOf(99)
array.indexOf(108)
array.indexOf(285)
let emptyArray: [Int] = []
emptyArray.indexOf(123)
//: [Next](@next) | 0cced909a8bb1ed82cdd979ae72e4c89 | 35.333333 | 319 | 0.611853 | false | false | false | false |
tqtifnypmb/Framenderer | refs/heads/master | Framenderer/Sources/GLObjects/FrameBuffer/SMSampleInputFrameBuffer.swift | mit | 2 | //
// SMSampleInputFrameBuffer.swift
// Framenderer
//
// Created by tqtifnypmb on 17/01/2017.
// Copyright © 2017 tqitfnypmb. All rights reserved.
//
import Foundation
import GLKit
import OpenGLES.ES3.gl
import OpenGLES.ES3.glext
import CoreMedia
class SMSampleInputFrameBuffer: InputFrameBuffer {
private var _texture: GLuint = 0
private let _textureWidth: GLsizei
private let _textureHeight: GLsizei
private var _flipVertically = false
private let _isFont: Bool
private let _guessRotation: Bool
/// Create a input framebuffer object using samplebuffer as content
convenience init(sampleBuffer: CMSampleBuffer, isFrontCamera: Bool) throws {
try self.init(sampleBuffer: sampleBuffer, isFront: isFrontCamera, guessRotation: true)
}
convenience init(sampleBuffer: CMSampleBuffer) throws {
try self.init(sampleBuffer: sampleBuffer, isFront: false, guessRotation: false)
}
init(sampleBuffer: CMSampleBuffer, isFront: Bool, guessRotation: Bool) throws {
_isFont = isFront
_guessRotation = guessRotation
if let cv = CMSampleBufferGetImageBuffer(sampleBuffer) {
CVPixelBufferLockBaseAddress(cv, .readOnly)
let texture = try TextureCacher.shared.createTexture(fromPixelBufer: cv, target: GLenum(GL_TEXTURE_2D), format: GLenum(GL_BGRA))
_texture = CVOpenGLESTextureGetName(texture)
let bpr = CVPixelBufferGetBytesPerRow(cv)
let width = bpr / 4
let height = CVPixelBufferGetHeight(cv)
CVPixelBufferUnlockBaseAddress(cv, .readOnly)
_textureWidth = GLsizei(width)
_textureHeight = GLsizei(height)
glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_MAG_FILTER), GL_LINEAR)
glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_MIN_FILTER), GL_LINEAR)
glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_WRAP_S), GL_CLAMP_TO_EDGE)
glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_WRAP_T), GL_CLAMP_TO_EDGE)
glBindTexture(GLenum(GL_TEXTURE_2D), 0)
} else {
throw DataError.sample(errorDesc: "CMSampleBuffer doesn't contain image data")
}
}
func useAsInput() {
glBindTexture(GLenum(GL_TEXTURE_2D), _texture)
}
func textCoorFlipVertically(flip: Bool) {
_flipVertically = flip
}
func retrieveRawData() -> [GLubyte] {
return readTextureRawData(texture: _texture, width: _textureWidth, height: _textureHeight)
}
var bitmapInfo: CGBitmapInfo {
return [CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedFirst.rawValue), .byteOrder32Little]
}
var width: GLsizei {
return _textureWidth
}
var height: GLsizei {
return _textureHeight
}
var textCoor: [GLfloat] {
if !_guessRotation {
return [
0.0, 0.0,
0.0, 1.0,
1.0, 0.0,
1.0, 1.0
]
}
var rotation: Rotation = .none
var flipHorzontally = false
switch UIDevice.current.orientation {
case .landscapeRight:
rotation = _isFont ? .none : .ccw180
case .portrait:
rotation = .ccw90
case .landscapeLeft:
rotation = _isFont ? .ccw180 : .none
case .portraitUpsideDown:
rotation = _isFont ? .ccw90 : .ccw270
flipHorzontally = true
default:
rotation = .none
}
let coor = textCoordinate(forRotation: rotation, flipHorizontally: flipHorzontally, flipVertically: false)
if _flipVertically {
return flipTextCoorVertically(textCoor: coor)
} else {
return coor
}
}
var format: GLenum {
return GLenum(GL_BGRA)
}
}
| bd64abe6b81d064bf843f5c671a5f345 | 30.620155 | 140 | 0.601863 | false | false | false | false |
xianglin123/douyuzhibo | refs/heads/master | douyuzhibo/douyuzhibo/Classes/Home/ViewModel/XLRecommendVM.swift | apache-2.0 | 1 | //
// XLRecommendVM.swift
// douyuzhibo
//
// Created by xianglin on 16/11/25.
// Copyright © 2016年 xianglin. All rights reserved.
//
import UIKit
class XLRecommendVM: XLBaseViewModel {
// 普通主播数组
fileprivate lazy var normalGroup : XLAnchorGroup = XLAnchorGroup()
// 颜值主播数组
fileprivate lazy var prettyGroup : XLAnchorGroup = XLAnchorGroup()
// 无线轮播数据
lazy var cycleModels : [XLCycleModel] = [XLCycleModel]()
}
//MARK: - 请求网络数据
extension XLRecommendVM {
//MARK: - 请求推荐页面数据
func requestData(_ finishCallback : @escaping () -> ()) {
// 0.获取请求时的秒数
let interval = Int(NSDate().timeIntervalSince1970)
// 1.定义参数
let parameters = ["limit" : "4", "offset" : "0", "time" : "\(interval)"]
// 2.创建Group
let dGroup = DispatchGroup()
dGroup.enter()
// 1. 第一部分:请求热门数据
XLNetworkManager.request(.get, url: "http://capi.douyucdn.cn/api/v1/getbigDataRoom", paramters: ["time" : "\(interval)"]) { (result) in
// 1.1 获取响应字典
guard let responseDict = result as? [String : NSObject] else { return }
// 1.2 取出数组data,内部都是字典,字典转模型
guard let dataArray = responseDict["data"] as? [[String : NSObject]] else { return }
// 1.3 设置组头
self.normalGroup.tag_name = "热门"
self.normalGroup.icon_name = "home_header_hot"
// 1.4 字典转模型 并添加至普通主播数组
for dict in dataArray {
self.normalGroup.anchors.append(XLAnchorModel.init(dict: dict))
}
dGroup.leave()
}
dGroup.enter()
// 2. 第二部分:请求颜值数据
XLNetworkManager.request(.get, url: "http://capi.douyucdn.cn/api/v1/getVerticalRoom", paramters: parameters) { (result) in
// 2.1 获取响应字典
guard let responseDict = result as? [String : NSObject] else { return }
// 2.2 取出数组data,内部都是字典,字典转模型
guard let dataArray = responseDict["data"] as? [[String : NSObject]] else { return }
// 2.3 设置组头
self.prettyGroup.tag_name = "颜值"
self.prettyGroup.icon_name = "home_header_phone"
// 2.4 字典转模型 并添加至数组
for dict in dataArray {
self.prettyGroup.anchors.append(XLAnchorModel.init(dict: dict))
}
dGroup.leave()
}
dGroup.enter()
// 3. 第三部分:请求2组-12组数据
XLNetworkManager.request(.get, url: "http://capi.douyucdn.cn/api/v1/getHotCate", paramters: parameters) { (result) in
// 1.1 获取响应字典
guard let responseDict = result as? [String : NSObject] else { return }
// 1.2 取出数组data,内部都是字典,字典转模型
guard let dataArray = responseDict["data"] as? [[String : NSObject]] else { return }
// 1.4 字典转模型 并添加至普通主播数组
for dict in dataArray {
self.anchorModels.append(XLAnchorGroup.init(dict: dict))
}
dGroup.leave()
}
dGroup.notify(queue: DispatchQueue.main) {
self.anchorModels.insert(self.prettyGroup, at: 0)
self.anchorModels.insert(self.normalGroup, at: 0)
// 5.完成回调
finishCallback()
}
}
//MARK: - 请求轮播数据
func requestCycleData(_ finishCallback : @escaping () -> ()) {
// 4.请求轮播数据
XLNetworkManager.request(.get, url: "http://www.douyutv.com/api/v1/slide/6", paramters: ["version" : "2.300"]) { (result) in
// 1.1 获取响应字典
guard let responseDict = result as? [String : NSObject] else { return }
// 1.2 取出数组data,内部都是字典,字典转模型
guard let dataArray = responseDict["data"] as? [[String : NSObject]] else { return }
// 1.3 遍历数组 字典转模型
for dict in dataArray {
self.cycleModels.append(XLCycleModel.init(dict: dict))
}
finishCallback()
}
}
}
| a9f7c9c7ff1e9fb74bdff207850f4070 | 33.375 | 143 | 0.534061 | false | false | false | false |
Jnosh/swift | refs/heads/master | test/IDE/reconstruct_type_from_mangled_name_invalid.swift | apache-2.0 | 28 | // RUN: %target-swift-ide-test -reconstruct-type -source-filename %s | %FileCheck %s -implicit-check-not="FAILURE"
// REQUIRES: rdar30680565
struct GS<T> {
// CHECK: decl: struct GS<T> for 'GS'
// FIXME: why do we get this?
// CHECK: decl: struct GS<T> for 'T' usr=s:14swift_ide_test2GSV1Txmfp
let a: T.Nope
// CHECK: decl: let a: <<error type>>
let b: T
// CHECK: decl: let b: T
}
let global1: GS
// CHECK: decl: let global1: <<error type>>
let global2 = GS().x
// CHECK: decl: let global2: <<error type>>
let global3 = GS<Int>(a: 1, b: 2).b
// CHECK: decl: let global3: <<error type>>
protocol P {
// FIXME: missing protocol entries?
// CHECK: decl: protocol P for 'P' usr=s:14swift_ide_test1PP
associatedtype T
// CHECK: decl: protocol P for 'T' usr=s:14swift_ide_test1PP1T
func foo() -> T
// CHECK: decl: func foo() -> Self.T for 'foo' usr=s:14swift_ide_test1PP3foo1TQzyF
}
struct SP: P {
// CHECK: decl: struct SP : P for 'SP'
typealias TT = Self.T
// FIXME: should be the typealias decl
// CHECK: decl: struct SP : P for 'TT' usr=s:14swift_ide_test2SPV2TT
}
| ae93165cd80b9af5e403b8e940638145 | 29.8 | 114 | 0.662338 | false | true | false | false |
JGiola/swift | refs/heads/main | tools/swift-inspect/Sources/swift-inspect/DarwinRemoteProcess.swift | apache-2.0 | 9 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 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
//
//===----------------------------------------------------------------------===//
#if os(iOS) || os(macOS) || os(tvOS) || os(watchOS)
import SwiftRemoteMirror
import SymbolicationShims
internal final class DarwinRemoteProcess: RemoteProcess {
public typealias ProcessIdentifier = pid_t
public typealias ProcessHandle = task_t
private var task: task_t
public var process: ProcessHandle { task }
public private(set) var context: SwiftReflectionContextRef!
private var symbolicator: CSSymbolicatorRef
private var swiftCore: CSTypeRef
private let swiftConcurrency: CSTypeRef
private lazy var threadInfos = getThreadInfos()
static var QueryDataLayout: QueryDataLayoutFunction {
return { (context, type, _, output) in
guard let output = output else { return 0 }
switch type {
case DLQ_GetPointerSize, DLQ_GetSizeSize:
let size = UInt8(MemoryLayout<UnsafeRawPointer>.stride)
output.storeBytes(of: size, toByteOffset: 0, as: UInt8.self)
return 1
case DLQ_GetPtrAuthMask:
let mask = GetPtrauthMask()
output.storeBytes(of: mask, toByteOffset: 0, as: UInt.self)
return 1
case DLQ_GetObjCReservedLowBits:
var size: UInt8 = 0
#if os(macOS)
// Only 64-bit macOS reserves pointer bit-packing.
if MemoryLayout<UnsafeRawPointer>.stride == 8 { size = 1 }
#endif
output.storeBytes(of: size, toByteOffset: 0, as: UInt8.self)
return 1
case DLQ_GetLeastValidPointerValue:
var value: UInt64 = 0x1000
#if os(iOS) || os(macOS) || os(tvOS) || os(watchOS)
// 64-bit Apple platforms reserve the low 4GiB.
if MemoryLayout<UnsafeRawPointer>.stride == 8 { value = 0x1_0000_0000 }
#endif
output.storeBytes(of: value, toByteOffset: 0, as: UInt64.self)
return 1
default:
return 0
}
}
}
func read(address: swift_addr_t, size: Int) -> UnsafeRawPointer? {
return task_peek(task, address, mach_vm_size_t(size))
}
func getAddr(symbolName: String) -> swift_addr_t {
// FIXME: use `__USER_LABEL_PREFIX__` instead of the hardcoded `_`.
let fullName = "_\(symbolName)"
var symbol = CSSymbolOwnerGetSymbolWithMangledName(swiftCore, fullName)
if CSIsNull(symbol) {
symbol = CSSymbolOwnerGetSymbolWithMangledName(swiftConcurrency, fullName)
}
let range = CSSymbolGetRange(symbol)
return swift_addr_t(range.location)
}
static var ReadBytes: ReadBytesFunction {
return { (context, address, size, _) in
let process: DarwinRemoteProcess = DarwinRemoteProcess.fromOpaque(context!)
return process.read(address: address, size: Int(size))
}
}
static var GetStringLength: GetStringLengthFunction {
return { (context, address) in
let process: DarwinRemoteProcess = DarwinRemoteProcess.fromOpaque(context!)
if let str = task_peek_string(process.task, address) {
return UInt64(strlen(str))
}
return 0
}
}
static var GetSymbolAddress: GetSymbolAddressFunction {
return { (context, symbol, length) in
let process: DarwinRemoteProcess = DarwinRemoteProcess.fromOpaque(context!)
guard let symbol = symbol else { return 0 }
let name: String = symbol.withMemoryRebound(to: UInt8.self, capacity: Int(length)) {
let buffer = UnsafeBufferPointer(start: $0, count: Int(length))
return String(decoding: buffer, as: UTF8.self)
}
return process.getAddr(symbolName: name)
}
}
init?(processId: ProcessIdentifier, forkCorpse: Bool) {
var task: task_t = task_t()
let taskResult = task_for_pid(mach_task_self_, processId, &task)
guard taskResult == KERN_SUCCESS else {
print("unable to get task for pid \(processId): \(String(cString: mach_error_string(taskResult))) \(hex: taskResult)")
return nil
}
if forkCorpse {
var corpse = task_t()
let corpseResult = task_generate_corpse(task, &corpse)
if corpseResult == KERN_SUCCESS {
task = corpse
} else {
print("unable to fork corpse for pid \(processId): \(String(cString: mach_error_string(corpseResult))) \(hex: corpseResult)")
}
}
self.task = task
self.symbolicator = CSSymbolicatorCreateWithTask(self.task)
self.swiftCore =
CSSymbolicatorGetSymbolOwnerWithNameAtTime(self.symbolicator,
"libswiftCore.dylib", kCSNow)
self.swiftConcurrency = CSSymbolicatorGetSymbolOwnerWithNameAtTime(
symbolicator, "libswift_Concurrency.dylib", kCSNow)
_ = task_start_peeking(self.task)
guard let context =
swift_reflection_createReflectionContextWithDataLayout(self.toOpaqueRef(),
Self.QueryDataLayout,
Self.Free,
Self.ReadBytes,
Self.GetStringLength,
Self.GetSymbolAddress) else {
return nil
}
self.context = context
_ = CSSymbolicatorForeachSymbolOwnerAtTime(self.symbolicator, kCSNow, { owner in
let address = CSSymbolOwnerGetBaseAddress(owner)
_ = swift_reflection_addImage(self.context, address)
})
}
deinit {
task_stop_peeking(self.task)
mach_port_deallocate(mach_task_self_, self.task)
}
func symbolicate(_ address: swift_addr_t) -> (module: String?, symbol: String?) {
let symbol =
CSSymbolicatorGetSymbolWithAddressAtTime(self.symbolicator, address, kCSNow)
let module = CSSymbolGetSymbolOwner(symbol)
return (CSSymbolOwnerGetName(module), CSSymbolGetName(symbol))
}
internal func iterateHeap(_ body: (swift_addr_t, UInt64) -> Void) {
withoutActuallyEscaping(body) {
withUnsafePointer(to: $0) {
task_enumerate_malloc_blocks(self.task,
UnsafeMutableRawPointer(mutating: $0),
CUnsignedInt(MALLOC_PTR_IN_USE_RANGE_TYPE),
{ (task, context, type, ranges, count) in
let callback: (swift_addr_t, UInt64) -> Void =
context!.assumingMemoryBound(to: ((swift_addr_t, UInt64) -> Void).self).pointee
for i in 0..<Int(count) {
let range = ranges[i]
callback(swift_addr_t(range.address), UInt64(range.size))
}
})
}
}
}
}
extension DarwinRemoteProcess {
private class PortList: Sequence {
let buffer: UnsafeBufferPointer<mach_port_t>
init?(task: task_t) {
var threadList: UnsafeMutablePointer<mach_port_t>?
var threadCount: mach_msg_type_number_t = 0
let result = task_threads(task, &threadList, &threadCount)
guard result == KERN_SUCCESS else {
print("unable to gather threads for process: \(String(cString: mach_error_string(result))) (0x\(String(result, radix: 16)))")
return nil
}
buffer = UnsafeBufferPointer(start: threadList, count: Int(threadCount))
}
deinit {
// Deallocate the port rights for the threads.
for thread in self {
mach_port_deallocate(mach_task_self_, thread)
}
// Deallocate the thread list.
let pointer = vm_address_t(truncatingIfNeeded: Int(bitPattern: buffer.baseAddress))
let size = vm_size_t(MemoryLayout<mach_port_t>.size) * vm_size_t(buffer.count)
vm_deallocate(mach_task_self_, pointer, size)
}
func makeIterator() -> UnsafeBufferPointer<thread_t>.Iterator {
return buffer.makeIterator()
}
}
private struct ThreadInfo {
var threadID: UInt64
var tlsStart: UInt64
var kernelObject: UInt32?
}
private func getThreadInfos() -> [ThreadInfo] {
guard let threads = PortList(task: self.task) else {
return []
}
return threads.compactMap {
guard let info = getThreadInfo(thread: $0) else {
return nil
}
guard let kernelObj = getKernelObject(task: mach_task_self_, port: $0) else {
return nil
}
return ThreadInfo(threadID: info.thread_id,
tlsStart: info.thread_handle,
kernelObject: kernelObj)
}
}
private func getKernelObject(task: task_t, port: mach_port_t) -> UInt32? {
var object: UInt32 = 0
var type: UInt32 = 0
let result = mach_port_kernel_object(task, port, &type, &object)
guard result == KERN_SUCCESS else {
return nil
}
return object
}
private func getThreadInfo(thread: thread_t) -> thread_identifier_info_data_t? {
let THREAD_IDENTIFIER_INFO_COUNT =
MemoryLayout<thread_identifier_info_data_t>.size / MemoryLayout<natural_t>.size
var info = thread_identifier_info_data_t()
var infoCount = mach_msg_type_number_t(THREAD_IDENTIFIER_INFO_COUNT)
var result: kern_return_t = 0
withUnsafeMutablePointer(to: &info) {
$0.withMemoryRebound(to: integer_t.self, capacity: THREAD_IDENTIFIER_INFO_COUNT) {
result = thread_info(thread, thread_flavor_t(THREAD_IDENTIFIER_INFO),
$0, &infoCount)
}
}
guard result == KERN_SUCCESS else {
print("unable to get info for thread port \(thread): \(String(cString: mach_error_string(result))) (0x\(String(result, radix: 16)))")
return nil
}
return info
}
}
extension DarwinRemoteProcess {
internal var currentTasks: [(threadID: UInt64, currentTask: swift_addr_t)] {
return threadInfos.compactMap {
let tlsStart = $0.tlsStart
if tlsStart == 0 { return nil }
let SWIFT_CONCURRENCY_TASK_KEY = 103
let currentTaskPointer = tlsStart + UInt64(SWIFT_CONCURRENCY_TASK_KEY * MemoryLayout<UnsafeRawPointer>.size)
guard let pointer = read(address: currentTaskPointer, size: MemoryLayout<UnsafeRawPointer>.size) else {
return nil
}
let currentTask = pointer.load(as: UInt.self)
return (threadID: $0.threadID, currentTask: swift_addr_t(currentTask))
}
}
internal func getThreadID(remotePort: thread_t) -> UInt64? {
guard let remoteThreadObj = getKernelObject(task: self.task, port: remotePort) else {
return nil
}
return threadInfos.first{ $0.kernelObject == remoteThreadObj }?.threadID
}
}
#endif
| 3a20325e6b73ff2681bc3f079b1b1e84 | 34.477124 | 139 | 0.631448 | false | false | false | false |
vector-im/riot-ios | refs/heads/develop | Riot/Modules/Secrets/Setup/RecoveryKey/SecretsSetupRecoveryKeyCoordinator.swift | apache-2.0 | 1 | // File created from ScreenTemplate
// $ createScreen.sh SecretsSetupRecoveryKey SecretsSetupRecoveryKey
/*
Copyright 2020 New Vector 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
import UIKit
final class SecretsSetupRecoveryKeyCoordinator: SecretsSetupRecoveryKeyCoordinatorType {
// MARK: - Properties
// MARK: Private
private var secretsSetupRecoveryKeyViewModel: SecretsSetupRecoveryKeyViewModelType
private let secretsSetupRecoveryKeyViewController: SecretsSetupRecoveryKeyViewController
// MARK: Public
// Must be used only internally
var childCoordinators: [Coordinator] = []
weak var delegate: SecretsSetupRecoveryKeyCoordinatorDelegate?
// MARK: - Setup
init(recoveryService: MXRecoveryService, passphrase: String?) {
let secretsSetupRecoveryKeyViewModel = SecretsSetupRecoveryKeyViewModel(recoveryService: recoveryService, passphrase: passphrase)
let secretsSetupRecoveryKeyViewController = SecretsSetupRecoveryKeyViewController.instantiate(with: secretsSetupRecoveryKeyViewModel)
self.secretsSetupRecoveryKeyViewModel = secretsSetupRecoveryKeyViewModel
self.secretsSetupRecoveryKeyViewController = secretsSetupRecoveryKeyViewController
}
// MARK: - Public methods
func start() {
self.secretsSetupRecoveryKeyViewModel.coordinatorDelegate = self
}
func toPresentable() -> UIViewController {
return self.secretsSetupRecoveryKeyViewController
}
}
// MARK: - SecretsSetupRecoveryKeyViewModelCoordinatorDelegate
extension SecretsSetupRecoveryKeyCoordinator: SecretsSetupRecoveryKeyViewModelCoordinatorDelegate {
func secretsSetupRecoveryKeyViewModelDidComplete(_ viewModel: SecretsSetupRecoveryKeyViewModelType) {
self.delegate?.secretsSetupRecoveryKeyCoordinatorDidComplete(self)
}
func secretsSetupRecoveryKeyViewModelDidFailed(_ viewModel: SecretsSetupRecoveryKeyViewModelType) {
self.delegate?.secretsSetupRecoveryKeyCoordinatorDidFailed(self)
}
func secretsSetupRecoveryKeyViewModelDidCancel(_ viewModel: SecretsSetupRecoveryKeyViewModelType) {
self.delegate?.secretsSetupRecoveryKeyCoordinatorDidCancel(self)
}
}
| 66a9fb4eacd06507db4999a980385dfb | 37.708333 | 141 | 0.775386 | false | false | false | false |
spritekitbook/flappybird-swift | refs/heads/master | Chapter 10/Finish/FloppyBird/FloppyBird/CloudController.swift | apache-2.0 | 15 | //
// CloudController.swift
// FloppyBird
//
// Created by Jeremy Novak on 9/26/16.
// Copyright © 2016 SpriteKit Book. All rights reserved.
//
import SpriteKit
class CloudController:SKNode {
// MARK: - Private class constants
private let largeCloud = Cloud(cloudSize: .large)
private let mediumCloud = Cloud(cloudSize: .medium)
private let smallCloud = Cloud(cloudSize: .small)
// MARK: - Private class variables
private var cloudArray = [Cloud]()
private var frameCount:TimeInterval = 0.0
// MARK: Init
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init() {
super.init()
setup()
}
// MARK: - Setup
private func setup() {
cloudArray = [largeCloud, mediumCloud, smallCloud]
// Spawn the first clouds
self.run(SKAction.wait(forDuration: 0.25), completion: {
[weak self] in
self?.spawnFirst()
})
}
// MARK: - Spawn
private func spawn() {
let randomIndex = RandomIntegerBetween(min: 0, max: cloudArray.count - 1)
let randomSpeed = RandomFloatBetween(min: 6.0, max: 12.0)
let cloud = cloudArray[randomIndex].copy() as! Cloud
let startX = kViewSize.width + cloud.size.width
let startY = RandomFloatBetween(min: kViewSize.height * 0.3, max: kViewSize.height * 0.8)
cloud.position = CGPoint(x: startX, y: startY)
cloud.moveSpeed = randomSpeed
self.addChild(cloud)
}
private func spawnFirst() {
let randomCloudIndex = RandomIntegerBetween(min: 0, max: 2)
let startX = RandomFloatBetween(min: kViewSize.width * 0.3, max: kViewSize.width * 0.7)
let startY = RandomFloatBetween(min: kViewSize.height * 0.3, max: kViewSize.height * 0.7)
let cloud = cloudArray[randomCloudIndex].copy() as! Cloud
let randomSpeed = RandomFloatBetween(min: 6.0, max: 12.0)
cloud.moveSpeed = randomSpeed
cloud.position = CGPoint(x: startX, y: startY)
self.addChild(cloud)
}
// MARK: - Update
func update(delta: TimeInterval) {
frameCount += delta
if self.frameCount >= 5.0 {
spawn()
frameCount = 0.0
}
for node in self.children {
if let cloud = node as? Cloud {
cloud.update(delta: delta)
}
}
}
}
| 38513963bb6e6833194ebbd0775f270b | 26.431579 | 97 | 0.563315 | false | false | false | false |
azfx/Sapporo | refs/heads/master | Example/Example/Calendar/CalendarLayout.swift | mit | 1 | //
// CalendarLayout.swift
// Example
//
// Created by Le VanNghia on 6/29/15.
// Copyright (c) 2015 Le Van Nghia. All rights reserved.
//
// http://www.objc.io/issues/3-views/collection-view-layouts
import UIKit
import Sapporo
let DaysPerWeek : CGFloat = 7
let HoursPerDay : CGFloat = 24
let HorizontalSpacing : CGFloat = 10
let HeightPerHour : CGFloat = 50
let DayHeaderHeight : CGFloat = 40
let HourHeaderWidth : CGFloat = 100
class CalendarLayout: SALayout {
override func collectionViewContentSize() -> CGSize {
let contentWidth = collectionView!.bounds.size.width
let contentHeight = CGFloat(DayHeaderHeight + (HeightPerHour * HoursPerDay))
return CGSizeMake(contentWidth, contentHeight)
}
override func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? {
var layoutAttributes = [UICollectionViewLayoutAttributes]()
// Cells
let visibleIndexPaths = indexPathsOfItemsInRect(rect)
layoutAttributes += visibleIndexPaths.map {
self.layoutAttributesForItemAtIndexPath($0)
}
// Supplementary views
let dayHeaderViewIndexPaths = indexPathsOfDayHeaderViewsInRect(rect)
layoutAttributes += dayHeaderViewIndexPaths.map {
self.layoutAttributesForSupplementaryViewOfKind(CalendarHeaderType.Day.rawValue, atIndexPath: $0)
}
let hourHeaderViewIndexPaths = indexPathsOfHourHeaderViewsInRect(rect)
layoutAttributes += hourHeaderViewIndexPaths.map {
self.layoutAttributesForSupplementaryViewOfKind(CalendarHeaderType.Hour.rawValue, atIndexPath: $0)
}
return layoutAttributes
}
override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes! {
var attributes = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath)
if let event = (getCellModel(indexPath) as? CalendarEventCellModel)?.event {
attributes.frame = frameForEvent(event)
}
return attributes
}
override func layoutAttributesForSupplementaryViewOfKind(elementKind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes! {
var attributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: elementKind, withIndexPath: indexPath)
let totalWidth = collectionViewContentSize().width
if elementKind == CalendarHeaderType.Day.rawValue {
let availableWidth = totalWidth - HourHeaderWidth
let widthPerDay = availableWidth / DaysPerWeek
attributes.frame = CGRectMake(HourHeaderWidth + (widthPerDay * CGFloat(indexPath.item)), 0, widthPerDay, DayHeaderHeight)
attributes.zIndex = -10
} else if elementKind == CalendarHeaderType.Hour.rawValue {
attributes.frame = CGRectMake(0, DayHeaderHeight + HeightPerHour * CGFloat(indexPath.item), totalWidth, HeightPerHour)
attributes.zIndex = -10
}
return attributes
}
override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool {
return true
}
}
extension CalendarLayout {
func indexPathsOfEventsBetweenMinDayIndex(minDayIndex: Int, maxDayIndex: Int, minStartHour: Int, maxStartHour: Int) -> [NSIndexPath] {
var indexPaths = [NSIndexPath]()
if let cellmodels = getCellModels(0) as? [CalendarEventCellModel] {
for i in 0..<cellmodels.count {
let event = cellmodels[i].event
if event.day >= minDayIndex && event.day <= maxDayIndex && event.startHour >= minStartHour && event.startHour <= maxStartHour {
let indexPath = NSIndexPath(forItem: i, inSection: 0)
indexPaths.append(indexPath)
}
}
}
return indexPaths
}
func indexPathsOfItemsInRect(rect: CGRect) -> [NSIndexPath] {
let minVisibleDay = dayIndexFromXCoordinate(CGRectGetMinX(rect))
let maxVisibleDay = dayIndexFromXCoordinate(CGRectGetMaxX(rect))
let minVisibleHour = hourIndexFromYCoordinate(CGRectGetMinY(rect))
let maxVisibleHour = hourIndexFromYCoordinate(CGRectGetMaxY(rect))
return indexPathsOfEventsBetweenMinDayIndex(minVisibleDay, maxDayIndex: maxVisibleDay, minStartHour: minVisibleHour, maxStartHour: maxVisibleHour)
}
func dayIndexFromXCoordinate(xPosition: CGFloat) -> Int {
let contentWidth = collectionViewContentSize().width - HourHeaderWidth
let widthPerDay = contentWidth / DaysPerWeek
let dayIndex = max(0, Int((xPosition - HourHeaderWidth) / widthPerDay))
return dayIndex
}
func hourIndexFromYCoordinate(yPosition: CGFloat) -> Int {
let hourIndex = max(0, Int((yPosition - DayHeaderHeight) / HeightPerHour))
return hourIndex
}
func indexPathsOfDayHeaderViewsInRect(rect: CGRect) -> [NSIndexPath] {
if CGRectGetMinY(rect) > DayHeaderHeight {
return []
}
let minDayIndex = dayIndexFromXCoordinate(CGRectGetMinX(rect))
let maxDayIndex = dayIndexFromXCoordinate(CGRectGetMaxX(rect))
return (minDayIndex...maxDayIndex).map { index -> NSIndexPath in
NSIndexPath(forItem: index, inSection: 0)
}
}
func indexPathsOfHourHeaderViewsInRect(rect: CGRect) -> [NSIndexPath] {
if CGRectGetMinX(rect) > HourHeaderWidth {
return []
}
let minHourIndex = hourIndexFromYCoordinate(CGRectGetMinY(rect))
let maxHourIndex = hourIndexFromYCoordinate(CGRectGetMaxY(rect))
return (minHourIndex...maxHourIndex).map { index -> NSIndexPath in
NSIndexPath(forItem: index, inSection: 0)
}
}
func frameForEvent(event: CalendarEvent) -> CGRect {
let totalWidth = collectionViewContentSize().width - HourHeaderWidth
let widthPerDay = totalWidth / DaysPerWeek
var frame = CGRectZero
frame.origin.x = HourHeaderWidth + widthPerDay * CGFloat(event.day)
frame.origin.y = DayHeaderHeight + HeightPerHour * CGFloat(event.startHour)
frame.size.width = widthPerDay
frame.size.height = CGFloat(event.durationInHours) * HeightPerHour
frame = CGRectInset(frame, HorizontalSpacing/2.0, 0)
return frame
}
} | 24b2fc2b3f57b3ea668f8caa08c590bb | 40.03125 | 156 | 0.670628 | false | false | false | false |
february29/Learning | refs/heads/master | swift/Fch_Contact/Fch_Contact/AppClasses/ViewController/ThemeViewContoller.swift | mit | 1 | //
// ThemeViewContoller.swift
// Fch_Contact
//
// Created by bai on 2018/1/30.
// Copyright © 2018年 北京仙指信息技术有限公司. All rights reserved.
//
import UIKit
import SnapKit
class ThemeViewContoller: BBaseViewController ,UITableViewDelegate,UITableViewDataSource{
// case white
// case black
// case green
// case red
// case blue
// case purple
// case pink
let dataArray =
[Theme.white,
// Theme.black,
Theme.green,
Theme.red,
Theme.blue,
Theme.purple,
Theme.pink]
lazy var tableView:UITableView = {
let table = UITableView.init(frame: CGRect.zero, style: .grouped);
table.showsVerticalScrollIndicator = false;
table.showsHorizontalScrollIndicator = false;
// table.estimatedRowHeight = 30;
table.delegate = self;
table.dataSource = self;
table.setBackgroundColor(.tableBackground);
table.setSeparatorColor(.primary);
table.register(FontTableViewCell.self, forCellReuseIdentifier: "cell")
table.rowHeight = UITableViewAutomaticDimension;
table.tableFooterView = UIView();
return table;
}();
override func viewDidLoad() {
super.viewDidLoad()
self.title = BLocalizedString(key: "Theme");
self.view.addSubview(self.tableView);
self.tableView.snp.makeConstraints { (make) in
make.left.right.top.bottom.equalToSuperview();
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArray.count;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = FontTableViewCell.init(style: .default, reuseIdentifier: "cell");
cell.coloumLable1?.text = dataArray[indexPath.row].displayName;
return cell;
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
ColorCenter.shared.theme = dataArray[indexPath.row] ;
let setting = UserDefaults.standard.getUserSettingModel()
setting.theme = dataArray[indexPath.row];
UserDefaults.standard.setUserSettingModel(model: setting);
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 1;
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 45;
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return UIView();
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| 02d1cffaeb5e183d1ca095627b63f286 | 24.53913 | 100 | 0.605039 | false | false | false | false |
angmu/SwiftPlayCode | refs/heads/master | swift练习/swift数组字典.playground/section-1.swift | mit | 1 | // Playground - noun: a place where people can play
import Foundation
//var animals:[NSObject] = [NSObject]()
var animals:[Any] = [Any]()
animals.append("monkey")
animals.append("elephen")
animals.append(18)
//var array: [Any] = ["simba", "junchen", "xiaoming", 17]
//for item in array {
// print(item)
//}
let array: [Any] = ["why", "lmj", "lnj",29]
//let array1:[Any] = ["yz", "wsz"]
//let array2 = array + array1
//let dict :Dictionary<String, Any>= ["name":"simba", "age":24, "score":98]
var dict: [String : Any] = ["name" : "why", "age" : 18]
dict["height"] = 170
//dict.removeValue(forKey: "age")
//print(dict)
//for k in dict.keys {
// print(k)
//}
| 188484cc537cad5c8295b89eb07d8e6f | 20.645161 | 75 | 0.605067 | false | false | false | false |
remobjects/ElementsSamples | refs/heads/master | Silver/Island/Command Line/Mandelbrot (Windows)/Program.swift | mit | 1 | let cols = 78
let lines = 30
var chars = [" ",".",",","`","'",":","=","|","+","i","h","I","H","E","O","Q","S","B","#","$"]
let maxIter = count(chars)
var minRe = -2.0
var maxRe = 1.0
var minIm = -1.0
var maxIm = 1.0
var im = minIm
while im <= maxIm
{
var re = minRe
while re <= maxRe
{
var zr = re
var zi = im
var n = -1
while n < maxIter-1
{
n += 1
var a = zr * zr
var b = zi * zi
if a + b > 4.0 { break }
zi = 2 * zr * zi + im
zr = a - b + re
}
print(chars[n], separator: "", terminator: "")
re += (maxRe - minRe) / Double(cols)
}
print()
im += (maxIm - minIm) / Double(lines)
}
//Press ENTER to continue
print("Press ENTER to exit");
Console.ReadLine();
| 11411780bc53f6048141dfb473222a36 | 19.6 | 93 | 0.408565 | false | false | false | false |
calebd/swift | refs/heads/master | test/APINotes/versioned-objc.swift | apache-2.0 | 2 | // RUN: %empty-directory(%t)
// RUN: not %target-swift-frontend -typecheck -F %S/Inputs/custom-frameworks -swift-version 4 %s 2>&1 | %FileCheck -check-prefix=CHECK-DIAGS -check-prefix=CHECK-DIAGS-4 %s
// RUN: not %target-swift-frontend -typecheck -F %S/Inputs/custom-frameworks -swift-version 3 %s 2>&1 | %FileCheck -check-prefix=CHECK-DIAGS -check-prefix=CHECK-DIAGS-3 %s
// REQUIRES: objc_interop
import APINotesFrameworkTest
// CHECK-DIAGS-4-NOT: versioned-objc.swift:[[@LINE-1]]:
class ProtoWithVersionedUnavailableMemberImpl: ProtoWithVersionedUnavailableMember {
// CHECK-DIAGS-3: versioned-objc.swift:[[@LINE-1]]:7: error: type 'ProtoWithVersionedUnavailableMemberImpl' cannot conform to protocol 'ProtoWithVersionedUnavailableMember' because it has requirements that cannot be satisfied
func requirement() -> Any? { return nil }
}
func testNonGeneric() {
// CHECK-DIAGS-3:[[@LINE+1]]:{{[0-9]+}}: error: cannot convert value of type 'Any' to specified type 'Int'
let _: Int = NewlyGenericSub.defaultElement()
// CHECK-DIAGS-4:[[@LINE-1]]:{{[0-9]+}}: error: generic parameter 'Element' could not be inferred
// CHECK-DIAGS-3:[[@LINE+1]]:{{[0-9]+}}: error: cannot specialize non-generic type 'NewlyGenericSub'
let _: Int = NewlyGenericSub<Base>.defaultElement()
// CHECK-DIAGS-4:[[@LINE-1]]:{{[0-9]+}}: error: cannot convert value of type 'Base' to specified type 'Int'
}
func testRenamedGeneric() {
// CHECK-DIAGS-3-NOT: 'RenamedGeneric' has been renamed to 'OldRenamedGeneric'
let _: OldRenamedGeneric<Base> = RenamedGeneric<Base>()
// CHECK-DIAGS-4:[[@LINE-1]]:{{[0-9]+}}: error: 'OldRenamedGeneric' has been renamed to 'RenamedGeneric'
// CHECK-DIAGS-3-NOT: 'RenamedGeneric' has been renamed to 'OldRenamedGeneric'
let _: RenamedGeneric<Base> = OldRenamedGeneric<Base>()
// CHECK-DIAGS-4:[[@LINE-1]]:{{[0-9]+}}: error: 'OldRenamedGeneric' has been renamed to 'RenamedGeneric'
class SwiftClass {}
// CHECK-DIAGS-3:[[@LINE+1]]:{{[0-9]+}}: error: 'RenamedGeneric' requires that 'SwiftClass' inherit from 'Base'
let _: OldRenamedGeneric<SwiftClass> = RenamedGeneric<SwiftClass>()
// CHECK-DIAGS-4:[[@LINE-1]]:{{[0-9]+}}: error: 'RenamedGeneric' requires that 'SwiftClass' inherit from 'Base'
// CHECK-DIAGS-3:[[@LINE+1]]:{{[0-9]+}}: error: 'RenamedGeneric' requires that 'SwiftClass' inherit from 'Base'
let _: RenamedGeneric<SwiftClass> = OldRenamedGeneric<SwiftClass>()
// CHECK-DIAGS-4:[[@LINE-1]]:{{[0-9]+}}: error: 'RenamedGeneric' requires that 'SwiftClass' inherit from 'Base'
}
func testRenamedClassMembers(obj: ClassWithManyRenames) {
// CHECK-DIAGS-3: [[@LINE+1]]:{{[0-9]+}}: error: 'classWithManyRenamesForInt' has been replaced by 'init(swift3Factory:)'
_ = ClassWithManyRenames.classWithManyRenamesForInt(0)
// CHECK-DIAGS-4: [[@LINE-1]]:{{[0-9]+}}: error: 'classWithManyRenamesForInt' has been replaced by 'init(for:)'
// CHECK-DIAGS-3: [[@LINE+1]]:{{[0-9]+}}: error: 'init(forInt:)' has been replaced by 'init(swift3Factory:)'
_ = ClassWithManyRenames(forInt: 0)
// CHECK-DIAGS-4: [[@LINE-1]]:{{[0-9]+}}: error: 'init(forInt:)' has been replaced by 'init(for:)'
// CHECK-DIAGS-3-NOT: :[[@LINE+1]]:{{[0-9]+}}:
_ = ClassWithManyRenames(swift3Factory: 0)
// CHECK-DIAGS-4: [[@LINE-1]]:{{[0-9]+}}: error: 'init(swift3Factory:)' has been replaced by 'init(for:)'
// CHECK-DIAGS-3: [[@LINE+1]]:{{[0-9]+}}: error: 'init(for:)' has been replaced by 'init(swift3Factory:)'
_ = ClassWithManyRenames(for: 0)
// CHECK-DIAGS-4-NOT: :[[@LINE-1]]:{{[0-9]+}}:
// CHECK-DIAGS-3: [[@LINE+1]]:{{[0-9]+}}: error: 'init(boolean:)' has been renamed to 'init(swift3Boolean:)'
_ = ClassWithManyRenames(boolean: false)
// CHECK-DIAGS-4: [[@LINE-1]]:{{[0-9]+}}: error: 'init(boolean:)' has been renamed to 'init(finalBoolean:)'
// CHECK-DIAGS-3-NOT: :[[@LINE+1]]:{{[0-9]+}}:
_ = ClassWithManyRenames(swift3Boolean: false)
// CHECK-DIAGS-4: [[@LINE-1]]:{{[0-9]+}}: error: 'init(swift3Boolean:)' has been renamed to 'init(finalBoolean:)'
// CHECK-DIAGS-3: [[@LINE+1]]:{{[0-9]+}}: error: 'init(finalBoolean:)' has been renamed to 'init(swift3Boolean:)'
_ = ClassWithManyRenames(finalBoolean: false)
// CHECK-DIAGS-4-NOT: :[[@LINE-1]]:{{[0-9]+}}:
// CHECK-DIAGS-3: [[@LINE+1]]:{{[0-9]+}}: error: 'doImportantThings()' has been renamed to 'swift3DoImportantThings()'
obj.doImportantThings()
// CHECK-DIAGS-4: [[@LINE-1]]:{{[0-9]+}}: error: 'doImportantThings()' has been renamed to 'finalDoImportantThings()'
// CHECK-DIAGS-3-NOT: :[[@LINE+1]]:{{[0-9]+}}:
obj.swift3DoImportantThings()
// CHECK-DIAGS-4: [[@LINE-1]]:{{[0-9]+}}: error: 'swift3DoImportantThings()' has been renamed to 'finalDoImportantThings()'
// CHECK-DIAGS-3: [[@LINE+1]]:{{[0-9]+}}: error: 'finalDoImportantThings()' has been renamed to 'swift3DoImportantThings()'
obj.finalDoImportantThings()
// CHECK-DIAGS-4-NOT: :[[@LINE-1]]:{{[0-9]+}}:
// CHECK-DIAGS-3: [[@LINE+1]]:{{[0-9]+}}: error: 'importantClassProperty' has been renamed to 'swift3ClassProperty'
_ = ClassWithManyRenames.importantClassProperty
// CHECK-DIAGS-4: [[@LINE-1]]:{{[0-9]+}}: error: 'importantClassProperty' has been renamed to 'finalClassProperty'
// CHECK-DIAGS-3-NOT: :[[@LINE+1]]:{{[0-9]+}}:
_ = ClassWithManyRenames.swift3ClassProperty
// CHECK-DIAGS-4: [[@LINE-1]]:{{[0-9]+}}: error: 'swift3ClassProperty' has been renamed to 'finalClassProperty'
// CHECK-DIAGS-3: [[@LINE+1]]:{{[0-9]+}}: error: 'finalClassProperty' has been renamed to 'swift3ClassProperty'
_ = ClassWithManyRenames.finalClassProperty
// CHECK-DIAGS-4-NOT: :[[@LINE-1]]:{{[0-9]+}}:
}
func testRenamedProtocolMembers(obj: ProtoWithManyRenames) {
// CHECK-DIAGS-3: [[@LINE+1]]:{{[0-9]+}}: error: 'init(boolean:)' has been renamed to 'init(swift3Boolean:)'
_ = type(of: obj).init(boolean: false)
// CHECK-DIAGS-4: [[@LINE-1]]:{{[0-9]+}}: error: 'init(boolean:)' has been renamed to 'init(finalBoolean:)'
// CHECK-DIAGS-3-NOT: :[[@LINE+1]]:{{[0-9]+}}:
_ = type(of: obj).init(swift3Boolean: false)
// CHECK-DIAGS-4: [[@LINE-1]]:{{[0-9]+}}: error: 'init(swift3Boolean:)' has been renamed to 'init(finalBoolean:)'
// CHECK-DIAGS-3: [[@LINE+1]]:{{[0-9]+}}: error: 'init(finalBoolean:)' has been renamed to 'init(swift3Boolean:)'
_ = type(of: obj).init(finalBoolean: false)
// CHECK-DIAGS-4-NOT: :[[@LINE-1]]:{{[0-9]+}}:
// CHECK-DIAGS-3: [[@LINE+1]]:{{[0-9]+}}: error: 'doImportantThings()' has been renamed to 'swift3DoImportantThings()'
obj.doImportantThings()
// CHECK-DIAGS-4: [[@LINE-1]]:{{[0-9]+}}: error: 'doImportantThings()' has been renamed to 'finalDoImportantThings()'
// CHECK-DIAGS-3-NOT: :[[@LINE+1]]:{{[0-9]+}}:
obj.swift3DoImportantThings()
// CHECK-DIAGS-4: [[@LINE-1]]:{{[0-9]+}}: error: 'swift3DoImportantThings()' has been renamed to 'finalDoImportantThings()'
// CHECK-DIAGS-3: [[@LINE+1]]:{{[0-9]+}}: error: 'finalDoImportantThings()' has been renamed to 'swift3DoImportantThings()'
obj.finalDoImportantThings()
// CHECK-DIAGS-4-NOT: :[[@LINE-1]]:{{[0-9]+}}:
// CHECK-DIAGS-3: [[@LINE+1]]:{{[0-9]+}}: error: 'importantClassProperty' has been renamed to 'swift3ClassProperty'
_ = type(of: obj).importantClassProperty
// CHECK-DIAGS-4: [[@LINE-1]]:{{[0-9]+}}: error: 'importantClassProperty' has been renamed to 'finalClassProperty'
// CHECK-DIAGS-3-NOT: :[[@LINE+1]]:{{[0-9]+}}:
_ = type(of: obj).swift3ClassProperty
// CHECK-DIAGS-4: [[@LINE-1]]:{{[0-9]+}}: error: 'swift3ClassProperty' has been renamed to 'finalClassProperty'
// CHECK-DIAGS-3: [[@LINE+1]]:{{[0-9]+}}: error: 'finalClassProperty' has been renamed to 'swift3ClassProperty'
_ = type(of: obj).finalClassProperty
// CHECK-DIAGS-4-NOT: :[[@LINE-1]]:{{[0-9]+}}:
}
let unrelatedDiagnostic: Int = nil
| aa4a5d6c530479cb10ab2cbd2caac933 | 53.48951 | 227 | 0.657854 | false | false | false | false |
akane/Akane | refs/heads/master | Akane/Akane/Collection/Delegate/CollectionViewDelegate.swift | mit | 1 | //
// This file is part of Akane
//
// Created by JC on 08/02/16.
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code
//
import Foundation
@available(*, unavailable, renamed: "CollectionViewAdapter")
typealias CollectionViewDelegate<T: DataSource> = CollectionViewAdapter<T>
/// Adapter class, making the link between `UICollectionView`, `UICollectionViewDataSource` and `DataSource`
/// Unlike TableViewAdapter (due to some API limitations) it can handles cells only. Subclass it if you want to display any supplementary views.
open class CollectionViewAdapter<DataSourceType : DataSource> : NSObject, UICollectionViewDataSource, UICollectionViewDelegate
{
open fileprivate(set) weak var observer: ViewObserver?
open fileprivate(set) var dataSource: DataSourceType
var viewModels: [IndexPath:ComponentViewModel] = [:]
/**
- parameter observer: the observer which will be used to register observations on cells
- parameter dataSource: the dataSource used to provide data to the collectionView
*/
public init(observer: ViewObserver, dataSource: DataSourceType) {
self.observer = observer
self.dataSource = dataSource
super.init()
}
/**
Makes the class both delegate and dataSource of collectionView
- parameter collectionView: a UICollectionView on which you want to be delegate and dataSource
*/
open func becomeDataSourceAndDelegate(_ collectionView: UICollectionView, reload: Bool = true) {
objc_setAssociatedObject(collectionView, &TableViewDataSourceAttr, self, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
collectionView.delegate = self
collectionView.dataSource = self
if reload {
self.viewModels.removeAll()
collectionView.reloadData()
}
}
// MARK: DataSource
open func numberOfSections(in collectionView: UICollectionView) -> Int {
return self.dataSource.numberOfSections()
}
open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.dataSource.numberOfItemsInSection(section)
}
open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let item = self.dataSource.item(at: indexPath)
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: item.reuseIdentifier, for: indexPath)
if let viewModel = self.dataSource.itemViewModel(for: item, at: indexPath),
let observer = self.observer,
let componentCell = cell as? _AnyComponentDisplayable {
componentCell._tryBindings(observer, params: viewModel)
self.viewModels[indexPath] = viewModel
}
return cell
}
// MARK: Selection
@objc
/// - returns the row index path if its viewModel is of type `ComponentItemViewModel` and it defines `select`, nil otherwise
/// - see: `ComponentItemViewModel.select()`
/// - seeAlso: `UICollectionViewDelegate.collectionView(_:, shouldSelectItemAtIndexPath:)`
open func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
guard let _ = self.viewModels[indexPath] as? Selectable else {
return false
}
return true
}
@objc
/// Call the row view model `select` `Command`
/// - see: `ComponentItemViewModel.select()`
/// - seeAlso: `UICollectionViewDelegate.collectionView(_:, didSelectItemAtIndexPath:)`
open func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard let viewModel = self.viewModels[indexPath] as? Selectable else {
return
}
viewModel.commandSelect.execute(nil)
}
@objc
/// - returns the row index path if its viewModel is of type `ComponentItemViewModel` and it defines `unselect`, nil otherwise
/// - seeAlso: `UICollectionViewDelegate.collectionView(_:, shouldDeselectItemAtIndexPath:)`
open func collectionView(_ collectionView: UICollectionView, shouldDeselectItemAt indexPath: IndexPath) -> Bool {
guard let _ = self.viewModels[indexPath] as? Unselectable else {
return false
}
return true
}
@objc
/// Call the row view model `unselect` `Command`
/// - seeAlso: `UICollectionViewDelegate.collectionView(_:, didDeselectRowAtIndexPath:)`
open func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
guard let viewModel = self.viewModels[indexPath] as? Unselectable else {
return
}
viewModel.commandUnselect.execute(nil)
}
}
| 4609883c081109f365a71861042c0ad2 | 37.951613 | 144 | 0.701449 | false | false | false | false |
NemProject/NEMiOSApp | refs/heads/develop | NEMWallet/Assets/Supporting Files/Cryptography/RIPEMD-160/RIPEMD.swift | mit | 1 | import Foundation
public struct RIPEMD {
public static func digest (_ input : NSData, bitlength:Int = 160) -> NSData {
assert(bitlength == 160, "Only RIPEMD-160 is implemented")
let paddedData = pad(input)
var block = RIPEMD.Block()
for i in 0 ..< paddedData.length / 64 {
let part = getWordsInSection(paddedData, i)
block.compress(part)
}
return encodeWords(block.hash)
}
// Pads the input to a multiple 64 bytes. First it adds 0x80 followed by zeros.
// It then needs 8 bytes at the end where it writes the length (in bits, little endian).
// If this doesn't fit it will add another block of 64 bytes.
// FIXME: Make private once tests support it
public static func pad(_ data: NSData) -> NSData {
let paddedData = data.mutableCopy() as! NSMutableData
// Put 0x80 after the last character:
let stop: [UInt8] = [UInt8(0x80)] // 2^8
paddedData.append(stop, length: 1)
// Pad with zeros until there are 64 * k - 8 bytes.
var numberOfZerosToPad: Int;
if paddedData.length % 64 == 56 {
// No padding needed
numberOfZerosToPad = 0
} else if paddedData.length % 64 < 56 {
numberOfZerosToPad = 56 - (paddedData.length % 64)
} else {
// Add an extra round
numberOfZerosToPad = 56 + (64 - paddedData.length % 64)
}
let zeroBytes = [UInt8](repeating: 0, count: numberOfZerosToPad)
paddedData.append(zeroBytes, length: numberOfZerosToPad)
// Append length of message:
let length: UInt32 = UInt32(data.length) * 8
let lengthBytes: [UInt32] = [length, UInt32(0x00_00_00_00)]
paddedData.append(lengthBytes, length: 8)
return paddedData as NSData
}
// Takes an NSData object of length k * 64 bytes and returns an array of UInt32
// representing 1 word (4 bytes) each. Each word is in little endian,
// so "abcdefgh" is now "dcbahgfe".
// FIXME: Make private once tests support it
public static func getWordsInSection(_ data: NSData, _ section: Int) -> [UInt32] {
let offset = section * 64
assert(data.length >= Int(offset + 64), "Data too short")
var words: [UInt32] = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
data.getBytes(&words, range: NSMakeRange(offset, 64))
return words
}
// FIXME: Make private once tests support it
public static func encodeWords(_ input: [UInt32]) -> NSData {
let data = NSMutableData(bytes: input, length: 20)
return data
}
// Returns a string representation of a hexadecimal number
public static func digest (_ input : NSData, bitlength:Int = 160) -> String {
return digest(input, bitlength: bitlength).toHexString()
}
// Takes a string representation of a hexadecimal number
public static func hexStringDigest (_ input : String, bitlength:Int = 160) -> NSData {
let data = NSData.fromHexString(input)
return digest(data, bitlength: bitlength)
}
// Takes a string representation of a hexadecimal number and returns a
// string represenation of the resulting 160 bit hash.
public static func hexStringDigest (_ input : String, bitlength:Int = 160) -> String {
let digest: NSData = hexStringDigest(input, bitlength: bitlength)
return digest.toHexString()
}
// Takes an ASCII string
public static func asciiDigest (_ input : String, bitlength:Int = 160) -> NSData {
// Order of bytes is preserved; if the last character is dot, the last
// byte is a dot.
if let data: NSData = input.data(using: String.Encoding.ascii) as NSData? {
return digest(data, bitlength: bitlength)
} else {
assert(false, "Invalid input")
return NSData()
}
}
// Takes an ASCII string and returns a hex string represenation of the
// resulting 160 bit hash.
public static func asciiDigest (_ input : String, bitlength:Int = 160) -> String {
return asciiDigest(input, bitlength: bitlength).toHexString()
}
}
| 7125b161a39f2555c08baf10772dd6d7 | 37.598214 | 92 | 0.608605 | false | false | false | false |
akabekobeko/examples-ios-fmdb | refs/heads/master | UsingFMDB-Swift/UsingFMDB-Swift/BooksViewController.swift | mit | 1 | //
// BooksViewController.swift
// UsingFMDB-Swift
//
// Created by akabeko on 2016/12/17.
// Copyright © 2016年 akabeko. All rights reserved.
//
import UIKit
/// List view for a books.
class BooksViewController: UITableViewController, EditBookViewControllerDelegate {
/// Segue fot the edit book.
private static let SegueEditBook = "EditBook"
/// Name for the cell.
private static let CellIdentifier = "Cell"
/// A value indicating that a new book should be created.
private var creatingBook = false
/// Called after the controller's view is loaded into memory.
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Books"
let button = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.add, target: self, action: #selector(didTouchCreateBookButton(sender:)))
self.navigationItem.leftBarButtonItem = button
self.navigationItem.rightBarButtonItem = self.editButtonItem
}
/// Notifies the view controller that its view is about to be removed from a view hierarchy.
///
/// - Parameter animated: If true, the disappearance of the view is being animated.
override func viewWillAppear(_ animated: Bool) {
self.setEditing(false, animated: animated)
super.viewWillAppear(animated)
}
/// Sent to the view controller when the app receives a memory warning.
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
/// Notifies the view controller that a segue is about to be performed.
///
/// - Parameters:
/// - segue: The segue object containing information about the view controllers involved in the segue.
/// - sender: The object that initiated the segue. You might use this parameter to perform different actions based on which control (or other object) initiated the segue.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == BooksViewController.SegueEditBook {
let vc = segue.destination as! EditBookViewController
vc.originalBook = self.creatingBook ? nil : self.bookAtIndexPath(indexPath: self.tableView.indexPathForSelectedRow!)
vc.deletate = self
}
}
/// Occurs when editing or creation of a book is completed.
///
/// - Parameters:
/// - viewController: Sender.
/// - oldBook: Old book data.
/// - newBook: New book data.
func didFinishEditBook(viewController: EditBookViewController, oldBook: Book?, newBook: Book) {
let store = self.bookStore()
var success = false;
if (newBook.bookId == Book.BookIdNone) {
success = store.add(book: newBook)
} else {
success = store.update(oldBook: oldBook!, newBook: newBook)
}
if success {
self.tableView.reloadData()
}
}
/// Occurs when the book creation button is touched.
///
/// - Parameter sender: Target of the event.
@objc func didTouchCreateBookButton(sender: Any?) {
self.creatingBook = true
self.performSegue(withIdentifier: BooksViewController.SegueEditBook, sender: self)
}
/// Asks the data source to return the number of sections in the table view.
///
/// - Parameter tableView: An object representing the table view requesting this information.
/// - Returns: The number of sections in tableView. The default value is 1.
override func numberOfSections(in tableView: UITableView) -> Int {
let store = self.bookStore()
return store.authors.count
}
/// Tells the data source to return the number of rows in a given section of a table view.
///
/// - Parameters:
/// - tableView: The table-view object requesting this information.
/// - section: An index number identifying a section in tableView.
/// - Returns: The number of rows in section.
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let store = self.bookStore()
let author = store.authors[section]
let books = store.booksByAuthor[author]
return (books?.count)!
}
/// Asks the data source for the title of the header of the specified section of the table view.
///
/// - Parameters:
/// - tableView: The table-view object asking for the title.
/// - section: An index number identifying a section of tableView.
/// - Returns: A string to use as the title of the section header. If you return nil , the section will have no title.
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let store = self.bookStore()
return store.authors[section]
}
/// Asks the data source for a cell to insert in a particular location of the table view.
///
/// - Parameters:
/// - tableView: A table-view object requesting the cell.
/// - indexPath: An index path locating a row in tableView.
/// - Returns: An object inheriting from UITableViewCell that the table view can use for the specified row. An assertion is raised if you return nil.
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: BooksViewController.CellIdentifier, for: indexPath)
let label = cell.viewWithTag(1) as! UILabel
let book = self.bookAtIndexPath(indexPath: indexPath)
label.text = book.title
return cell
}
/// Asks the data source to commit the insertion or deletion of a specified row in the receiver.
///
/// - Parameters:
/// - tableView: The table-view object requesting the insertion or deletion.
/// - editingStyle: The cell editing style corresponding to a insertion or deletion requested for the row specified by indexPath. Possible editing styles are UITableViewCellEditingStyleInsert or UITableViewCellEditingStyleDelete.
/// - indexPath: An index path locating the row in tableView.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == UITableViewCellEditingStyle.delete {
let store = self.bookStore()
let book = self.bookAtIndexPath(indexPath: indexPath)
if store.remove(book: book) {
self.tableView.reloadData()
}
}
}
/// Tells the delegate that the specified row is now selected.
///
/// - Parameters:
/// - tableView: A table-view object informing the delegate about the new row selection.
/// - indexPath: An index path locating the new selected row in tableView.
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.creatingBook = false
self.performSegue(withIdentifier: BooksViewController.SegueEditBook, sender: self)
}
/// Get the book at index path.
///
/// - Parameter indexPath: An index path locating a row in tableView.
/// - Returns: Book data.
private func bookAtIndexPath(indexPath: IndexPath) -> Book {
let store = self.bookStore()
let author = store.authors[indexPath.section]
let books = store.booksByAuthor[author]
return books![indexPath.row]
}
/// Get the book sore.
///
/// - Returns: Instance of the book store.
func bookStore() -> BookStore {
let app = UIApplication.shared.delegate as! AppDelegate
return app.appStore.bookStore
}
}
| 3773826d2beb86bc5afa31ee9e99952b | 41.147541 | 235 | 0.669389 | false | false | false | false |
AaronMT/firefox-ios | refs/heads/master | Sync/SyncTelemetryUtils.swift | mpl-2.0 | 4 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import Account
import Storage
import SwiftyJSON
import SyncTelemetry
fileprivate let log = Logger.syncLogger
public let PrefKeySyncEvents = "sync.telemetry.events"
public enum SyncReason: String {
case startup = "startup"
case scheduled = "scheduled"
case backgrounded = "backgrounded"
case user = "user"
case syncNow = "syncNow"
case didLogin = "didLogin"
case push = "push"
case engineEnabled = "engineEnabled"
case clientNameChanged = "clientNameChanged"
}
public enum SyncPingReason: String {
case shutdown = "shutdown"
case schedule = "schedule"
case idChanged = "idchanged"
}
public protocol Stats {
func hasData() -> Bool
}
private protocol DictionaryRepresentable {
func asDictionary() -> [String: Any]
}
public struct SyncUploadStats: Stats {
var sent: Int = 0
var sentFailed: Int = 0
public func hasData() -> Bool {
return sent > 0 || sentFailed > 0
}
}
extension SyncUploadStats: DictionaryRepresentable {
func asDictionary() -> [String: Any] {
return [
"sent": sent,
"failed": sentFailed
]
}
}
public struct SyncDownloadStats: Stats {
var applied: Int = 0
var succeeded: Int = 0
var failed: Int = 0
var newFailed: Int = 0
var reconciled: Int = 0
public func hasData() -> Bool {
return applied > 0 ||
succeeded > 0 ||
failed > 0 ||
newFailed > 0 ||
reconciled > 0
}
}
extension SyncDownloadStats: DictionaryRepresentable {
func asDictionary() -> [String: Any] {
return [
"applied": applied,
"succeeded": succeeded,
"failed": failed,
"newFailed": newFailed,
"reconciled": reconciled
]
}
}
public struct ValidationStats: Stats, DictionaryRepresentable {
let problems: [ValidationProblem]
let took: Int64
let checked: Int?
public func hasData() -> Bool {
return !problems.isEmpty
}
func asDictionary() -> [String: Any] {
var dict: [String: Any] = [
"problems": problems.map { $0.asDictionary() },
"took": took
]
if let checked = self.checked {
dict["checked"] = checked
}
return dict
}
}
public struct ValidationProblem: DictionaryRepresentable {
let name: String
let count: Int
func asDictionary() -> [String: Any] {
return ["name": name, "count": count]
}
}
public class StatsSession {
var took: Int64 = 0
var when: Timestamp?
private var startUptimeNanos: UInt64?
public func start(when: UInt64 = Date.now()) {
self.when = when
self.startUptimeNanos = DispatchTime.now().uptimeNanoseconds
}
public func hasStarted() -> Bool {
return startUptimeNanos != nil
}
public func end() -> Self {
guard let startUptime = startUptimeNanos else {
assertionFailure("SyncOperationStats called end without first calling start!")
return self
}
// Casting to Int64 should be safe since we're using uptime since boot in both cases.
// Convert to milliseconds as stated in the sync ping format
took = (Int64(DispatchTime.now().uptimeNanoseconds) - Int64(startUptime)) / 1000000
return self
}
}
// Stats about a single engine's sync.
public class SyncEngineStatsSession: StatsSession {
public var validationStats: ValidationStats?
private(set) var uploadStats: SyncUploadStats
private(set) var downloadStats: SyncDownloadStats
public init(collection: String) {
self.uploadStats = SyncUploadStats()
self.downloadStats = SyncDownloadStats()
}
public func recordDownload(stats: SyncDownloadStats) {
self.downloadStats.applied += stats.applied
self.downloadStats.succeeded += stats.succeeded
self.downloadStats.failed += stats.failed
self.downloadStats.newFailed += stats.newFailed
self.downloadStats.reconciled += stats.reconciled
}
public func recordUpload(stats: SyncUploadStats) {
self.uploadStats.sent += stats.sent
self.uploadStats.sentFailed += stats.sentFailed
}
}
extension SyncEngineStatsSession: DictionaryRepresentable {
func asDictionary() -> [String: Any] {
var dict: [String: Any] = [
"took": took,
]
if downloadStats.hasData() {
dict["incoming"] = downloadStats.asDictionary()
}
if uploadStats.hasData() {
dict["outgoing"] = [uploadStats.asDictionary()]
}
if let validation = self.validationStats, validation.hasData() {
dict["validation"] = validation.asDictionary()
}
return dict
}
}
// Stats and metadata for a sync operation.
public class SyncOperationStatsSession: StatsSession {
public let why: SyncReason
public var uid: String?
public var deviceID: String?
fileprivate let didLogin: Bool
public init(why: SyncReason, uid: String, deviceID: String?) {
self.why = why
self.uid = uid
self.deviceID = deviceID
self.didLogin = (why == .didLogin)
}
}
extension SyncOperationStatsSession: DictionaryRepresentable {
func asDictionary() -> [String: Any] {
let whenValue = when ?? 0
return [
"when": whenValue,
"took": took,
"didLogin": didLogin,
"why": why.rawValue
]
}
}
public enum SyncPingError: MaybeErrorType {
case failedToRestoreScratchpad
public var description: String {
switch self {
case .failedToRestoreScratchpad: return "Failed to restore Scratchpad from prefs"
}
}
}
public enum SyncPingFailureReasonName: String {
case httpError = "httperror"
case unexpectedError = "unexpectederror"
case sqlError = "sqlerror"
case otherError = "othererror"
}
public protocol SyncPingFailureFormattable {
var failureReasonName: SyncPingFailureReasonName { get }
}
public struct SyncPing: SyncTelemetryPing {
public private(set) var payload: JSON
public static func from(result: SyncOperationResult,
remoteClientsAndTabs: RemoteClientsAndTabs,
prefs: Prefs,
why: SyncPingReason) -> Deferred<Maybe<SyncPing>> {
// Grab our token so we can use the hashed_fxa_uid and clientGUID from our scratchpad for
// our ping's identifiers
return RustFirefoxAccounts.shared.syncAuthState.token(Date.now(), canBeExpired: false) >>== { (token, kSync) in
let scratchpadPrefs = prefs.branch("sync.scratchpad")
guard let scratchpad = Scratchpad.restoreFromPrefs(scratchpadPrefs, syncKeyBundle: KeyBundle.fromKSync(kSync)) else {
return deferMaybe(SyncPingError.failedToRestoreScratchpad)
}
var ping: [String: Any] = pingCommonData(
why: why,
hashedUID: token.hashedFxAUID,
hashedDeviceID: (scratchpad.clientGUID + token.hashedFxAUID).sha256.hexEncodedString
)
// TODO: We don't cache our sync pings so if it fails, it fails. Once we add
// some kind of caching we'll want to make sure we don't dump the events if
// the ping has failed.
let pickledEvents = prefs.arrayForKey(PrefKeySyncEvents) as? [Data] ?? []
let events = pickledEvents.compactMap(Event.unpickle).map { $0.toArray() }
ping["events"] = events
prefs.setObject(nil, forKey: PrefKeySyncEvents)
return dictionaryFrom(result: result, storage: remoteClientsAndTabs, token: token) >>== { syncDict in
// TODO: Split the sync ping metadata from storing a single sync.
ping["syncs"] = [syncDict]
return deferMaybe(SyncPing(payload: JSON(ping)))
}
}
}
static func pingCommonData(why: SyncPingReason, hashedUID: String, hashedDeviceID: String) -> [String: Any] {
return [
"version": 1,
"why": why.rawValue,
"uid": hashedUID,
"deviceID": hashedDeviceID,
"os": [
"name": "iOS",
"version": UIDevice.current.systemVersion,
"locale": Locale.current.identifier
]
]
}
// Generates a single sync ping payload that is stored in the 'syncs' list in the sync ping.
private static func dictionaryFrom(result: SyncOperationResult,
storage: RemoteClientsAndTabs,
token: TokenServerToken) -> Deferred<Maybe<[String: Any]>> {
return connectedDevices(fromStorage: storage, token: token) >>== { devices in
guard let stats = result.stats else {
return deferMaybe([String: Any]())
}
var dict = stats.asDictionary()
if let engineResults = result.engineResults.successValue {
dict["engines"] = SyncPing.enginePingDataFrom(engineResults: engineResults)
} else if let failure = result.engineResults.failureValue {
var errorName: SyncPingFailureReasonName
if let formattableFailure = failure as? SyncPingFailureFormattable {
errorName = formattableFailure.failureReasonName
} else {
errorName = .unexpectedError
}
dict["failureReason"] = [
"name": errorName.rawValue,
"error": "\(type(of: failure))",
]
}
dict["devices"] = devices
return deferMaybe(dict)
}
}
// Returns a list of connected devices formatted for use in the 'devices' property in the sync ping.
private static func connectedDevices(fromStorage storage: RemoteClientsAndTabs,
token: TokenServerToken) -> Deferred<Maybe<[[String: Any]]>> {
func dictionaryFrom(client: RemoteClient) -> [String: Any]? {
var device = [String: Any]()
if let os = client.os {
device["os"] = os
}
if let version = client.version {
device["version"] = version
}
if let guid = client.guid {
device["id"] = (guid + token.hashedFxAUID).sha256.hexEncodedString
}
return device
}
return storage.getClients() >>== { deferMaybe($0.compactMap(dictionaryFrom)) }
}
private static func enginePingDataFrom(engineResults: EngineResults) -> [[String: Any]] {
return engineResults.map { result in
let (name, status) = result
var engine: [String: Any] = [
"name": name
]
// For complete/partial results, extract out the collect stats
// and add it to engine information. For syncs that were not able to
// start, return why and a reason.
switch status {
case .completed(let stats):
engine.merge(with: stats.asDictionary())
case .partial(let stats):
engine.merge(with: stats.asDictionary())
case .notStarted(let reason):
engine.merge(with: [
"status": reason.telemetryId
])
}
return engine
}
}
}
| 2f2ac42c94261889570c23e00a6e3162 | 31.200542 | 129 | 0.596953 | false | false | false | false |
wuyezhiguhun/DDMusicFM | refs/heads/master | DDMusicFM/DDFound/Controller/DDFoundViewController.swift | apache-2.0 | 1 | //
// DDFoundViewController.swift
// DDMusicFM
//
// Created by 王允顶 on 17/9/6.
// Copyright © 2017年 王允顶. All rights reserved.
//
import UIKit
import SnapKit
class DDFoundViewController: DDBaseViewController, DDSubTitleViewDelegate, DDSubTitleViewDataSource, UIPageViewControllerDelegate, UIPageViewControllerDataSource {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = DDColorFloat(0.92, 0.93, 0.93)
self.view.addSubview(self.subTitleView)
addViewFrame()
configSubView()
// Do any additional setup after loading the view.
}
func configSubView() -> Void {
self.pageViewControllers.view.snp.makeConstraints { (make) in
make.top.equalTo(self.subTitleView.snp.bottom).offset(0)
make.left.equalTo(self.view).offset(0)
make.right.equalTo(self.view).offset(0)
make.bottom.equalTo(self.view).offset(0)
}
}
//MARK: == DDSubTitleViewDelegate ==
func titleViewNumber(_ titleView: DDSubTitleView) -> NSInteger {
return self.subTitleArray.count
}
func titleViewTitle(_ titleView: DDSubTitleView, _ index: Int) -> String {
return self.subTitleArray.object(at: index) as! String
}
func titleViewDidSelected(_ titleView: DDSubTitleView, _ index: NSInteger) {
self.pageViewControllers.setViewControllers([self.controllers.object(at: index) as! UIViewController], direction: UIPageViewControllerNavigationDirection.forward, animated: false, completion: nil)
}
//MARK: == UI 布局 ==
func addViewFrame() -> Void {
self.subTitleView.snp.makeConstraints { (make) in
make.top.equalTo(self.view).offset(64)
make.left.equalTo(self.view).offset(0)
make.right.equalTo(self.view).offset(0)
make.height.equalTo(40)
}
}
//MARK: == UIPageViewControllerDataSource ==
public func presentationCount(for pageViewController: UIPageViewController) -> Int {
return self.controllers.count
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
let index = indexForView(viewController)
if index == 0 || index == NSNotFound {
return nil
}
return self.controllers.object(at: Int(index) - 1) as? UIViewController
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
let index = indexForView(viewController)
if index == NSNotFound || index == self.controllers.count - 1 {
return nil
}
return self.controllers.object(at: Int(index) + 1) as? UIViewController
}
func indexForView(_ controller: UIViewController) -> Int {
return self.controllers.index(of: controller)
}
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
let viewController = self.pageViewControllers.viewControllers?[0]
let index = indexForView(viewController!)
self.subTitleView.showAtIndex(index)
}
//MARK: == get 函数 ==
var _subTitleArray: NSMutableArray?
var subTitleArray: NSMutableArray {
get {
if _subTitleArray == nil {
_subTitleArray = NSMutableArray(array: ["推荐","分类","广播","榜单","主播"])
}
return _subTitleArray!
}
set {
_subTitleArray = subTitleArray;
}
}
var _subTitleView: DDSubTitleView?
var subTitleView: DDSubTitleView {
get {
if _subTitleView == nil {
_subTitleView = DDSubTitleView()
_subTitleView?.delegate = self
_subTitleView?.dataSource = self
_subTitleView?.reloadData()
}
return _subTitleView!
}
set {
_subTitleView = subTitleView
}
}
var _controllers: NSMutableArray?
var controllers: NSMutableArray {
get {
if _controllers == nil {
_controllers = NSMutableArray()
for title in self.subTitleArray {
let con = DDSubFindFactory.subFindControllerWithIdentifier(title as! String)
_controllers?.add(con)
}
}
return _controllers!
}
set {
_controllers = controllers
}
}
var _pageViewControllers: UIPageViewController?
var pageViewControllers: UIPageViewController {
get {
if _pageViewControllers == nil {
let options = NSDictionary(object: NSNumber(integerLiteral: UIPageViewControllerSpineLocation.none.rawValue), forKey: UIPageViewControllerOptionSpineLocationKey as NSCopying)
_pageViewControllers = UIPageViewController(transitionStyle: UIPageViewControllerTransitionStyle.scroll, navigationOrientation: UIPageViewControllerNavigationOrientation.horizontal, options: options as? [String : Any])
_pageViewControllers?.delegate = self
_pageViewControllers?.dataSource = self
_pageViewControllers?.setViewControllers([self.controllers .firstObject as! UIViewController], direction: UIPageViewControllerNavigationDirection.forward, animated: false, completion: nil)
self.addChildViewController(_pageViewControllers!)
self.view.addSubview((_pageViewControllers?.view)!)
}
return _pageViewControllers!
}
set {
_pageViewControllers = pageViewControllers
}
}
var _headerView: DDFindRecomHeader?
var headerView: DDFindRecomHeader {
get {
if _headerView == nil {
_headerView = DDFindRecomHeader.findRecomHeader
}
return _headerView!
}
set {
_headerView = headerView
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 19d11e214aa0f5cd49bbc5eb0d12679f | 35.090909 | 234 | 0.633575 | false | false | false | false |
ihomway/RayWenderlichCourses | refs/heads/master | Advanced Swift 3/Advanced Swift 3.playground/Pages/Values and References Challenge.xcplaygroundpage/Contents.swift | mit | 1 | //: [Previous](@previous)
import Foundation
// Challenge
// You may already know that enums are value types in Swift. What about indirect enums?
// Create an indirect enum and show that it exhibits value semantics and not reference
// semantics.
//MARK: Value
enum Direction {
case top, left, down, right
}
var dir1: Direction = .right
var dir2: Direction = .left
var directions: [Direction] = []
directions.append(dir1)
directions.append(dir2)
dir1 = .top
directions
indirect enum Expression {
case number(Int)
case add(Expression, Expression)
func evaluate() -> Int {
switch self {
case let .number(value):
return value
case let .add(left, right):
return left.evaluate() + right.evaluate()
}
}
}
var first = Expression.number(50)
var firstCopy = first
var second = Expression.number(12)
var sum = Expression.add(first, second)
sum.evaluate()
firstCopy = .number(1000)
sum.evaluate()
//: [Next](@next)
| ffeef163184b4622ce733a32b101bebb | 18.102041 | 88 | 0.71047 | false | false | false | false |
cityos/photo-stream | refs/heads/master | Example/Example/PhotosTableViewController.swift | mit | 1 | //
// PhotosTableViewController.swift
// Example
//
// Created by Said Sikira on 5/5/15.
// Copyright (c) 2015 Said Sikira. All rights reserved.
//
import UIKit
import PhotoStream
class PhotosTableViewController: UITableViewController {
var photoURLS : Array<String> {
var photos = [String]()
photos.append("http://upload.wikimedia.org/wikipedia/commons/3/3d/Dubrovnik_crop.jpg")
photos.append("http://upload.wikimedia.org/wikipedia/en/7/71/Dubrovnik,_Croatia.jpg")
photos.append("http://upload.wikimedia.org/wikipedia/commons/7/73/Dubrovnik_Harbor_from_City_Walls_-_Old_City_-_Dubrovnik_-_Croatia.jpg")
return photos
}
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 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return photoURLS.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("imageCell", forIndexPath: indexPath) as! PhotoTableViewCell
// PhotoStream.fetch(URLString: self.photoURLS[indexPath.row]) {
// success, image in
// cell.photoImageView.image = image
// }
cell.photoImageView.setImageFromPhotoStream(URLString: photoURLS[indexPath.row], placeholderImage: UIImage(), animated: true)
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.
}
*/
}
| 1149607c229b79f72398b7ca8c216231 | 35.410714 | 157 | 0.681216 | false | false | false | false |
RocketChat/Rocket.Chat.iOS | refs/heads/develop | Rocket.Chat/Extensions/UIViewController/UIViewControllerExtension.swift | mit | 1 | //
// UIViewControllerExtension.swift
// Rocket.Chat
//
// Created by Rafael K. Streit on 14/11/16.
// Copyright © 2016 Rocket.Chat. All rights reserved.
//
import UIKit
import Photos
import MobileCoreServices
import ObjectiveC
private var viewScrollViewAssociatedKey: UInt8 = 0
protocol MediaPicker: AnyObject { }
extension MediaPicker where Self: UIViewController & UIImagePickerControllerDelegate & UINavigationControllerDelegate {
func openCamera(video: Bool = false) {
guard UIImagePickerController.isSourceTypeAvailable(.camera) else {
return assertionFailure("Device camera is not availbale")
}
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.allowsEditing = true
imagePicker.sourceType = .camera
imagePicker.cameraFlashMode = .off
imagePicker.mediaTypes = video ? [kUTTypeMovie as String] : [kUTTypeImage as String]
imagePicker.cameraCaptureMode = video ? .video : .photo
self.present(imagePicker, animated: true, completion: nil)
}
func openPhotosLibrary() {
let picker = UIImagePickerController()
picker.delegate = self
picker.allowsEditing = true
picker.sourceType = .savedPhotosAlbum
if let mediaTypes = UIImagePickerController.availableMediaTypes(for: .savedPhotosAlbum) {
picker.mediaTypes = mediaTypes
}
present(picker, animated: true, completion: nil)
}
}
extension MediaPicker where Self: UIViewController & DrawingControllerDelegate {
func openDrawing() {
let storyboard = UIStoryboard(name: "Drawing", bundle: Bundle.main)
if let controller = storyboard.instantiateInitialViewController() as? UINavigationController {
if let drawingController = controller.viewControllers.first as? DrawingViewController {
drawingController.delegate = self
}
present(controller, animated: true, completion: nil)
}
}
}
extension UIViewController {
var scrollViewInternal: UIScrollView! {
get {
return objc_getAssociatedObject(self, &viewScrollViewAssociatedKey) as? UIScrollView
}
set(newValue) {
objc_setAssociatedObject(self, &viewScrollViewAssociatedKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
// MARK: Keyboard Handling
func registerKeyboardHandlers(_ scrollView: UIScrollView) {
self.scrollViewInternal = scrollView
// Keyboard handler
NotificationCenter.default.addObserver(
self,
selector: #selector(UIViewController.keyboardWillShow(_:)),
name: UIResponder.keyboardWillShowNotification,
object: nil
)
NotificationCenter.default.addObserver(
self,
selector: #selector(UIViewController.keyboardWillHide(_:)),
name: UIResponder.keyboardWillHideNotification,
object: nil
)
}
func unregisterKeyboardNotifications() {
NotificationCenter.default.removeObserver(self)
}
@objc internal func keyboardWillShow(_ notification: Foundation.Notification) {
let userInfo = notification.userInfo
let value = userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue
let rawFrame = value?.cgRectValue ?? CGRect.zero
let duration = userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] ?? 0
let scrollView = self.scrollViewInternal
UIView.animate(
withDuration: (duration as AnyObject).doubleValue,
delay: 0,
options: UIView.AnimationOptions(),
animations: {
guard let insets = scrollView?.contentInset else { return }
var newInsets = insets
newInsets.bottom = rawFrame.height
scrollView?.contentInset = newInsets
scrollView?.scrollIndicatorInsets = newInsets
},
completion: nil
)
}
@objc internal func keyboardWillHide(_ notification: Foundation.Notification) {
let userInfo = notification.userInfo
let duration = userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] ?? 0
let scrollView = self.scrollViewInternal
UIView.animate(
withDuration: (duration as AnyObject).doubleValue,
delay: 0,
options: UIView.AnimationOptions(),
animations: {
let insets = UIEdgeInsets.zero
scrollView?.contentInset = insets
scrollView?.scrollIndicatorInsets = insets
},
completion: nil
)
}
}
extension UIViewController {
static var nib: UINib {
return UINib(nibName: "\(self)", bundle: nil)
}
static func instantiateFromNib() -> Self? {
func instanceFromNib<T: UIViewController>() -> T? {
return nib.instantiate() as? T
}
return instanceFromNib()
}
}
| 2d74dc90f27cd84ab5a42ed981ee48e9 | 31.544872 | 140 | 0.652551 | false | false | false | false |
honghaoz/CrackingTheCodingInterview | refs/heads/master | Swift/LeetCode/Binary Search/441_Arranging Coins.swift | mit | 1 | // 441_Arranging Coins
// https://leetcode.com/problems/arranging-coins/
//
// Created by Honghao Zhang on 9/16/19.
// Copyright © 2019 Honghaoz. All rights reserved.
//
// Description:
// You have a total of n coins that you want to form in a staircase shape, where every k-th row must have exactly k coins.
//
//Given n, find the total number of full staircase rows that can be formed.
//
//n is a non-negative integer and fits within the range of a 32-bit signed integer.
//
//Example 1:
//
//n = 5
//
//The coins can form the following rows:
//¤
//¤ ¤
//¤ ¤
//
//Because the 3rd row is incomplete, we return 2.
//Example 2:
//
//n = 8
//
//The coins can form the following rows:
//¤
//¤ ¤
//¤ ¤ ¤
//¤ ¤
//
//Because the 4th row is incomplete, we return 3.
//
import Foundation
class Num441 {
/// Use a binary search to find the row count
/// Sum is 上底加下底的和,乘以高,除以2
func arrangeCoins(_ n: Int) -> Int {
guard n > 0 else {
return 0
}
if n == 1 {
return 1
}
// start, mid, end is the number of rows
var start = 1
var end = n
while start + 1 < end {
let mid = start + (end - start) / 2
let sum = (mid + 1) * mid / 2
if sum < n {
start = mid
}
else if sum > n {
end = mid
}
else {
return mid
}
}
if (end + 1) * end / 2 <= n {
return end
}
else {
return start
}
}
}
| 73b560b1794822eea70563871e995034 | 18.833333 | 122 | 0.561625 | false | false | false | false |
brightify/torch | refs/heads/fix/xcode11 | Generator/Source/TorchGeneratorFramework/CodeBuilder.swift | mit | 1 | //
// CodeBuilder.swift
// TorchGenerator
//
// Created by Filip Dolnik on 21.07.16.
// Copyright © 2016 Brightify. All rights reserved.
//
public struct CodeBuilder {
fileprivate static let tab = " "
public fileprivate(set) var code = ""
fileprivate var nesting = 0
fileprivate var nest: String {
return (0 ..< nesting).reduce("") { acc, _ in acc + CodeBuilder.tab }
}
public mutating func clear() {
code = ""
}
public mutating func nest(_ closure: (_ builder: inout CodeBuilder) -> ()) {
nesting += 1
closure(&self)
nesting -= 1
}
public mutating func nest(_ line: String) {
nest { (builder: inout CodeBuilder) in
builder += line
}
}
public mutating func append(line: String, insertLineBreak: Bool = true) {
if line == "" {
code += insertLineBreak ? "\n" : ""
} else {
code += "\(nest)\(line)\(insertLineBreak ? "\n" : "")"
}
}
public mutating func append(lines: [String]) {
lines.enumerated().forEach {
if $0 > 0 {
append(line: "")
}
append(line: $1, insertLineBreak: false)
}
}
public mutating func append(builder subbuilder: CodeBuilder) {
let lines = subbuilder.code
.split(omittingEmptySubsequences: false) { $0 == "\n" || $0 == "\r\n" }
.map(String.init)
append(lines: lines)
}
}
public func +=(builder: inout CodeBuilder, string: String) {
builder.append(line: string)
}
public func +=(builder: inout CodeBuilder, lines: [String]) {
builder.append(lines: lines)
}
public func +=(builder: inout CodeBuilder, subbuilder: CodeBuilder) {
builder.append(builder: subbuilder)
}
| e1cef45f274c53bce62bb517a8b9611a | 24.591549 | 83 | 0.558613 | false | false | false | false |
DAloG/BlueCap | refs/heads/master | BlueCapKitTests/CentralManagerTests.swift | mit | 1 | //
// CentralManagerTests.swift
// BlueCapKit
//
// Created by Troy Stribling on 1/7/15.
// Copyright (c) 2015 Troy Stribling. The MIT License (MIT).
//
import UIKit
import XCTest
import CoreBluetooth
import CoreLocation
import BlueCapKit
class CentralManagerTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testPowerOnWhenPoweredOn() {
let mock = CentralManagerMock(state:.PoweredOn)
let expectation = expectationWithDescription("onSuccess fulfilled for future")
let future = mock.impl.powerOn(mock)
future.onSuccess {
expectation.fulfill()
}
future.onFailure{error in
XCTAssert(false, "onFailure called")
}
waitForExpectationsWithTimeout(2) {error in
XCTAssertNil(error, "\(error)")
}
}
func testPowerOnWhenPoweredOff() {
let mock = CentralManagerMock(state:.PoweredOff)
let expectation = expectationWithDescription("onSuccess fulfilled for future")
let future = mock.impl.powerOn(mock)
future.onSuccess {
expectation.fulfill()
}
future.onFailure{error in
XCTAssert(false, "onFailure called")
}
mock.state = .PoweredOn
mock.impl.didUpdateState(mock)
waitForExpectationsWithTimeout(2) {error in
XCTAssertNil(error, "\(error)")
}
}
func testPowerOffWhenPoweredOn() {
let mock = CentralManagerMock(state:.PoweredOn)
let expectation = expectationWithDescription("onSuccess fulfilled for future")
let future = mock.impl.powerOff(mock)
future.onSuccess {
expectation.fulfill()
}
future.onFailure{error in
XCTAssert(false, "onFailure called")
}
mock.state = .PoweredOff
mock.impl.didUpdateState(mock)
waitForExpectationsWithTimeout(2) {error in
XCTAssertNil(error, "\(error)")
}
}
func testPowerOffWhenPoweredOff() {
let mock = CentralManagerMock(state:.PoweredOff)
let expectation = expectationWithDescription("onSuccess fulfilled for future")
let future = mock.impl.powerOff(mock)
future.onSuccess {
expectation.fulfill()
}
future.onFailure{error in
XCTAssert(false, "onFailure called")
}
waitForExpectationsWithTimeout(2) {error in
XCTAssertNil(error, "\(error)")
}
}
func testServiceScanning() {
let mock = CentralManagerMock(state:.PoweredOff)
let expectation = expectationWithDescription("onSuccess fulfilled for future")
let future = mock.impl.startScanning(mock)
future.onSuccess {_ in
expectation.fulfill()
}
future.onFailure{error in
XCTAssert(false, "onFailure called")
}
mock.impl.didDiscoverPeripheral(PeripheralMock(name:"Mock"))
waitForExpectationsWithTimeout(2) {error in
XCTAssertNil(error, "\(error)")
}
}
}
| a41e4539c49862cd6b59bf4a1a4ea0c9 | 29.104762 | 86 | 0.619108 | false | true | false | false |
frootloops/swift | refs/heads/master | test/SILGen/reabstract_lvalue.swift | apache-2.0 | 1 | // RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
struct MyMetatypeIsThin {}
// CHECK-LABEL: sil hidden @_T017reabstract_lvalue19consumeGenericInOut{{[_0-9a-zA-Z]*}}F : $@convention(thin) <T> (@inout T) -> ()
func consumeGenericInOut<T>(_ x: inout T) {}
// CHECK-LABEL: sil hidden @_T017reabstract_lvalue9transformSdSiF : $@convention(thin) (Int) -> Double
func transform(_ i: Int) -> Double {
return Double(i)
}
// CHECK-LABEL: sil hidden @_T017reabstract_lvalue0A13FunctionInOutyyF : $@convention(thin) () -> ()
func reabstractFunctionInOut() {
// CHECK: [[BOX:%.*]] = alloc_box ${ var @callee_guaranteed (Int) -> Double }
// CHECK: [[PB:%.*]] = project_box [[BOX]]
// CHECK: [[ARG:%.*]] = function_ref @_T017reabstract_lvalue9transformSdSiF
// CHECK: [[THICK_ARG:%.*]] = thin_to_thick_function [[ARG]]
// CHECK: store [[THICK_ARG:%.*]] to [init] [[PB]]
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB]] : $*@callee_guaranteed (Int) -> Double
// CHECK: [[ABSTRACTED_BOX:%.*]] = alloc_stack $@callee_guaranteed (@in Int) -> @out Double
// CHECK: [[THICK_ARG:%.*]] = load [copy] [[WRITE]]
// CHECK: [[THUNK1:%.*]] = function_ref @_T0SiSdIegyd_SiSdIegir_TR
// CHECK: [[ABSTRACTED_ARG:%.*]] = partial_apply [callee_guaranteed] [[THUNK1]]([[THICK_ARG]])
// CHECK: store [[ABSTRACTED_ARG]] to [init] [[ABSTRACTED_BOX]]
// CHECK: [[FUNC:%.*]] = function_ref @_T017reabstract_lvalue19consumeGenericInOut{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[FUNC]]<(Int) -> Double>([[ABSTRACTED_BOX]])
// CHECK: [[NEW_ABSTRACTED_ARG:%.*]] = load [take] [[ABSTRACTED_BOX]]
// CHECK: [[THUNK2:%.*]] = function_ref @_T0SiSdIegir_SiSdIegyd_TR
// CHECK: [[NEW_ARG:%.*]] = partial_apply [callee_guaranteed] [[THUNK2]]([[NEW_ABSTRACTED_ARG]])
var minimallyAbstracted = transform
consumeGenericInOut(&minimallyAbstracted)
}
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0SiSdIegyd_SiSdIegir_TR : $@convention(thin) (@in Int, @guaranteed @callee_guaranteed (Int) -> Double) -> @out Double
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0SiSdIegir_SiSdIegyd_TR : $@convention(thin) (Int, @guaranteed @callee_guaranteed (@in Int) -> @out Double) -> Double
// CHECK-LABEL: sil hidden @_T017reabstract_lvalue0A13MetatypeInOutyyF : $@convention(thin) () -> ()
func reabstractMetatypeInOut() {
var thinMetatype = MyMetatypeIsThin.self
// CHECK: [[BOX:%.*]] = alloc_stack $@thick MyMetatypeIsThin.Type
// CHECK: [[THICK:%.*]] = metatype $@thick MyMetatypeIsThin.Type
// CHECK: store [[THICK]] to [trivial] [[BOX]]
// CHECK: [[FUNC:%.*]] = function_ref @_T017reabstract_lvalue19consumeGenericInOut{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[FUNC]]<MyMetatypeIsThin.Type>([[BOX]])
consumeGenericInOut(&thinMetatype)
}
| 9b7e7740caf81ce28d3e038b097c02ba | 59.574468 | 198 | 0.659993 | false | false | false | false |
Elm-Tree-Island/Shower | refs/heads/master | Carthage/Checkouts/ReactiveCocoa/ReactiveCocoaTests/UIKit/UISearchBarSpec.swift | gpl-3.0 | 2 | import ReactiveSwift
import ReactiveCocoa
import UIKit
import Quick
import Nimble
import enum Result.NoError
class UISearchBarSpec: QuickSpec {
override func spec() {
var searchBar: UISearchBar!
weak var _searchBar: UISearchBar?
var receiver: SearchBarDelegateReceiver!
beforeEach {
autoreleasepool {
receiver = SearchBarDelegateReceiver()
searchBar = UISearchBar(frame: .zero)
_searchBar = searchBar
_ = searchBar.reactive.textValues
searchBar.delegate = receiver
expect(searchBar.delegate).toNot(beIdenticalTo(receiver))
}
}
afterEach {
autoreleasepool {
searchBar = nil
}
expect(_searchBar).toEventually(beNil())
}
it("should accept changes from bindings to its text value") {
let firstChange = "first"
let secondChange = "second"
searchBar.text = ""
let (pipeSignal, observer) = Signal<String?, NoError>.pipe()
searchBar.reactive.text <~ SignalProducer(pipeSignal)
observer.send(value: firstChange)
expect(searchBar.text) == firstChange
observer.send(value: secondChange)
expect(searchBar.text) == secondChange
}
it("should emit user initiated changes to its text value when the editing ends") {
searchBar.text = "Test"
var latestValue: String?
searchBar.reactive.textValues.observeValues { text in
latestValue = text
}
expect(latestValue).to(beNil())
expect(receiver.endEditingTexts.isEmpty) == true
searchBar.delegate!.searchBarTextDidEndEditing!(searchBar)
expect(latestValue) == searchBar.text
expect(receiver.endEditingTexts.last) == searchBar.text
}
it("should emit user initiated changes to its text value continuously") {
searchBar.text = "newValue"
var latestValue: String?
searchBar.reactive.continuousTextValues.observeValues { text in
latestValue = text
}
expect(latestValue).to(beNil())
expect(receiver.texts.isEmpty) == true
searchBar.delegate!.searchBar!(searchBar, textDidChange: "newValue")
expect(latestValue) == "newValue"
expect(receiver.texts.last) == "newValue"
}
it("should accept changes from bindings to its scope button index") {
let firstChange = 1
let secondChange = 2
searchBar.scopeButtonTitles = ["First", "Second", "Third"]
let (pipeSignal, observer) = Signal<Int, NoError>.pipe()
searchBar.reactive.selectedScopeButtonIndex <~ SignalProducer(pipeSignal)
observer.send(value: firstChange)
expect(searchBar.selectedScopeButtonIndex) == firstChange
observer.send(value: secondChange)
expect(searchBar.selectedScopeButtonIndex) == secondChange
}
it("should emit user initiated changes to its text value when the editing ends") {
searchBar.scopeButtonTitles = ["First", "Second", "Third"]
var latestValue: Int?
searchBar.reactive.selectedScopeButtonIndices.observeValues { text in
latestValue = text
}
expect(latestValue).to(beNil())
expect(receiver.selectedScopeButtonIndices.isEmpty) == true
searchBar.delegate!.searchBar!(searchBar, selectedScopeButtonIndexDidChange: 1)
expect(latestValue) == 1
expect(receiver.selectedScopeButtonIndices.last) == 1
searchBar.delegate!.searchBar!(searchBar, selectedScopeButtonIndexDidChange: 2)
expect(latestValue) == 2
expect(receiver.selectedScopeButtonIndices.last) == 2
}
it("should notify when the cancel button is clicked") {
var isClicked: Bool?
searchBar.reactive.cancelButtonClicked
.observeValues { isClicked = true }
expect(isClicked).to(beNil())
expect(receiver.cancelButtonClickedCounter) == 0
searchBar.delegate!.searchBarCancelButtonClicked!(searchBar)
expect(isClicked) == true
expect(receiver.cancelButtonClickedCounter) == 1
}
it("should notify when the search button is clicked") {
var isClicked: Bool?
searchBar.reactive.searchButtonClicked
.observeValues { isClicked = true }
expect(isClicked).to(beNil())
expect(receiver.searchButtonClickedCounter) == 0
searchBar.delegate!.searchBarSearchButtonClicked!(searchBar)
expect(isClicked) == true
expect(receiver.searchButtonClickedCounter) == 1
}
it("should notify when the bookmark button is clicked") {
var isClicked: Bool?
searchBar.reactive.bookmarkButtonClicked
.observeValues { isClicked = true }
expect(isClicked).to(beNil())
expect(receiver.bookmarkButtonClickedCounter) == 0
searchBar.delegate!.searchBarBookmarkButtonClicked!(searchBar)
expect(isClicked) == true
expect(receiver.bookmarkButtonClickedCounter) == 1
}
it("should notify when the results list button is clicked") {
var isClicked: Bool?
searchBar.reactive.resultsListButtonClicked
.observeValues { isClicked = true }
expect(isClicked).to(beNil())
expect(receiver.resultsListButtonClickedCounter) == 0
searchBar.delegate!.searchBarResultsListButtonClicked!(searchBar)
expect(isClicked) == true
expect(receiver.resultsListButtonClickedCounter) == 1
}
}
}
class SearchBarDelegateReceiver: NSObject, UISearchBarDelegate {
var texts: [String] = []
var endEditingTexts: [String] = []
var searchButtonClickedCounter = 0
var cancelButtonClickedCounter = 0
var bookmarkButtonClickedCounter = 0
var resultsListButtonClickedCounter = 0
var selectedScopeButtonIndices: [Int] = []
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchButtonClickedCounter += 1
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
texts.append(searchText)
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
endEditingTexts.append(searchBar.text ?? "")
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
cancelButtonClickedCounter += 1
}
func searchBarResultsListButtonClicked(_ searchBar: UISearchBar) {
resultsListButtonClickedCounter += 1
}
func searchBarBookmarkButtonClicked(_ searchBar: UISearchBar) {
bookmarkButtonClickedCounter += 1
}
func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
selectedScopeButtonIndices.append(selectedScope)
}
}
| 668d0dc21c18087408fd5ff96da45e0b | 27.525822 | 97 | 0.745227 | false | true | false | false |
IBM-Swift/BluePic | refs/heads/master | BluePic-iOS/Pods/BMSPush/Source/BMSPushClient.swift | apache-2.0 | 1 | /*
* Copyright 2016 IBM Corp.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import UIKit
import BMSCore
public protocol BMSPushObserver{
func onChangePermission(status:Bool);
}
// MARK: - Swift 3
#if swift(>=3.0)
import UserNotifications
import UserNotificationsUI
public enum IMFPushErrorvalues: Int {
/// - IMFPushErrorInternalError: Denotes the Internal Server Error occured.
case IMFPushErrorInternalError = 1
/// - IMFPushErrorEmptyTagArray: Denotes the Empty Tag Array Error.
case IMFPushErrorEmptyTagArray = 2
/// - IMFPushRegistrationVerificationError: Denotes the Previous Push registration Error.
case IMFPushRegistrationVerificationError = 3
/// - IMFPushRegistrationError: Denotes the First Time Push registration Error.
case IMFPushRegistrationError = 4
/// - IMFPushRegistrationUpdateError: Denotes the Device updation Error.
case IMFPushRegistrationUpdateError = 5
/// - IMFPushRetrieveSubscriptionError: Denotes the Subscribed tags retrieval error.
case IMFPushRetrieveSubscriptionError = 6
/// - IMFPushRetrieveSubscriptionError: Denotes the Available tags retrieval error.
case IMFPushRetrieveTagsError = 7
/// - IMFPushTagSubscriptionError: Denotes the Tag Subscription error.
case IMFPushTagSubscriptionError = 8
/// - IMFPushTagUnsubscriptionError: Denotes the tag Unsubscription error.
case IMFPushTagUnsubscriptionError = 9
/// - BMSPushUnregitrationError: Denotes the Push Unregistration error.
case BMSPushUnregitrationError = 10
}
/**
A singleton that serves as an entry point to Bluemix client-Push service communication.
*/
public class BMSPushClient: NSObject {
// MARK: Properties (Public)
/// This singleton should be used for all `BMSPushClient` activity.
public static let sharedInstance = BMSPushClient()
// Specifies the bluemix push clientSecret value
public private(set) var clientSecret: String?
public private(set) var applicationId: String?
public private(set) var bluemixDeviceId: String?
// used to test in test zone and dev zone
public static var overrideServerHost = "";
private var _notificationOptions : BMSPushClientOptions?
public var notificationOptions:BMSPushClientOptions? {
get{
return _notificationOptions
}
set(value){
_notificationOptions = value
}
}
// MARK: Properties (private)
/// `BMSClient` object.
private var bmsClient = BMSClient.sharedInstance
// Notification Count
private var notificationcount:Int = 0
private var isInitialized = false;
public var delegate:BMSPushObserver?
// MARK: Initializers
/**
The required intializer for the `BMSPushClient` class.
This method will intialize the BMSPushClient with clientSecret based registration.
- parameter clientSecret: The clientSecret of the Push Service
- parameter appGUID: The pushAppGUID of the Push Service
*/
public func initializeWithAppGUID (appGUID: String, clientSecret: String) {
if validateString(object: clientSecret) {
self.clientSecret = clientSecret
self.applicationId = appGUID
BMSPushUtils.saveValueToNSUserDefaults(value: appGUID, key: BMSPUSH_APP_GUID)
BMSPushUtils.saveValueToNSUserDefaults(value: clientSecret, key: BMSPUSH_CLIENT_SECRET)
isInitialized = true;
self.bluemixDeviceId = ""
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound], completionHandler: { (granted, error) in
if(granted) {
UIApplication.shared.registerForRemoteNotifications()
self.delegate?.onChangePermission(status: true)
} else {
print("Error while registering with APNS server : \(String(describing: error))")
self.delegate?.onChangePermission(status: false)
}
})
} else {
// Fallback on earlier versions
let settings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
UIApplication.shared.registerUserNotificationSettings(settings)
self.checkStatusChange()
}
}
else{
self.sendAnalyticsData(logType: LogLevel.error, logStringData: "Error while registration - Client secret is not valid")
print("Error while registration - Client secret is not valid")
self.delegate?.onChangePermission(status: false)
}
}
/**
The required intializer for the `BMSPushClient` class.
This method will intialize the BMSPushClient with clientSecret based registration and take in notificationOptions.
- parameter clientSecret: The clientSecret of the Push Service
- parameter appGUID: The pushAppGUID of the Push Service
- parameter options: The push notification options
*/
public func initializeWithAppGUID (appGUID: String, clientSecret: String, options: BMSPushClientOptions) {
if validateString(object: clientSecret) {
self.clientSecret = clientSecret
self.applicationId = appGUID
BMSPushUtils.saveValueToNSUserDefaults(value: appGUID, key: BMSPUSH_APP_GUID)
BMSPushUtils.saveValueToNSUserDefaults(value: clientSecret, key: BMSPUSH_CLIENT_SECRET)
isInitialized = true;
let category : [BMSPushNotificationActionCategory] = options.category
self.bluemixDeviceId = options.deviceId
if #available(iOS 10.0, *) {
let center = UNUserNotificationCenter.current()
var notifCategory = Set<UNNotificationCategory>();
for singleCategory in category {
let categoryFirst : BMSPushNotificationActionCategory = singleCategory
let pushCategoryIdentifier : String = categoryFirst.identifier
let pushNotificationAction : [BMSPushNotificationAction] = categoryFirst.actions
var pushActionsArray = [UNNotificationAction]()
for actionButton in pushNotificationAction {
let newActionButton : BMSPushNotificationAction = actionButton
var options:UNNotificationActionOptions = .foreground
switch actionButton.activationMode {
case UIUserNotificationActivationMode.background:
options = .destructive
case UIUserNotificationActivationMode.foreground:
options = .foreground
}
let addButton = UNNotificationAction(identifier: newActionButton.identifier, title: newActionButton.title, options: [options])
pushActionsArray.append(addButton)
}
let responseCategory = UNNotificationCategory(identifier: pushCategoryIdentifier, actions: pushActionsArray, intentIdentifiers: [])
notifCategory.insert(responseCategory)
}
if !notifCategory.isEmpty {
center.setNotificationCategories(notifCategory)
}
center.requestAuthorization(options: [.alert, .badge, .sound], completionHandler: { (granted, error) in
if(granted) {
UIApplication.shared.registerForRemoteNotifications()
self.delegate?.onChangePermission(status: true)
} else {
print("Error while registering with APNS server : \(String(describing: error))")
self.delegate?.onChangePermission(status: false)
}
})
} else {
// Fallback on earlier versions
var notifCategory = Set<UIUserNotificationCategory>();
for singleCategory in category {
let categoryFirst : BMSPushNotificationActionCategory = singleCategory
let pushNotificationAction : [BMSPushNotificationAction] = categoryFirst.actions
let pushCategoryIdentifier : String = categoryFirst.identifier
var pushActionsArray = [UIUserNotificationAction]()
for actionButton in pushNotificationAction {
let newActionButton : BMSPushNotificationAction = actionButton
let addButton : UIMutableUserNotificationAction = UIMutableUserNotificationAction()
addButton.identifier = newActionButton.identifier
addButton.title = newActionButton.title
addButton.activationMode = newActionButton.activationMode
addButton.isAuthenticationRequired = newActionButton.authenticationRequired!
pushActionsArray.append(addButton)
}
let responseCategory : UIMutableUserNotificationCategory = UIMutableUserNotificationCategory()
responseCategory.identifier = pushCategoryIdentifier
responseCategory.setActions(pushActionsArray, for:UIUserNotificationActionContext.default)
responseCategory.setActions(pushActionsArray, for:UIUserNotificationActionContext.minimal)
notifCategory.insert(responseCategory)
}
if notifCategory.isEmpty {
let settings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories:nil)
UIApplication.shared.registerUserNotificationSettings(settings)
}else{
let settings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: notifCategory)
UIApplication.shared.registerUserNotificationSettings(settings)
}
self.checkStatusChange()
}
}
else{
self.sendAnalyticsData(logType: LogLevel.error, logStringData: "Error while registration - Client secret is not valid")
print("Error while registration - Client secret is not valid")
self.delegate?.onChangePermission(status: false)
}
}
// MARK: Methods (Public)
/**
This Methode used to register the client device to the Bluemix Push service. This is the normal registration, without userId.
Call this methode after successfully registering for remote push notification in the Apple Push
Notification Service .
- Parameter deviceToken: This is the response we get from the push registartion in APNS.
- Parameter WithUserId: This is the userId value.
- Parameter completionHandler: The closure that will be called when this request finishes. The response will contain response (String), StatusCode (Int) and error (string).
*/
public func registerWithDeviceToken(deviceToken:Data , WithUserId:String?, completionHandler: @escaping(_ response:String?, _ statusCode:Int?, _ error:String) -> Void) {
if (isInitialized){
if (validateString(object: WithUserId!)){
let devId = self.getDeviceID()
BMSPushUtils.saveValueToNSUserDefaults(value: devId, key: "deviceId")
var token = ""
for i in 0..<deviceToken.count {
token = token + String(format: "%02.2hhx", arguments: [deviceToken[i]])
}
self.applicationId = BMSPushUtils.getValueToNSUserDefaults(key: BMSPUSH_APP_GUID)
self.clientSecret = BMSPushUtils.getValueToNSUserDefaults(key: BMSPUSH_CLIENT_SECRET)
if(self.applicationId == "" || self.clientSecret == ""){
self.sendAnalyticsData(logType: LogLevel.error, logStringData: "Error while registration - Error is: push is not initialized")
completionHandler("", IMFPushErrorvalues.IMFPushRegistrationError.rawValue , "Error while registration - Error is: push is not initialized")
return
}
let urlBuilder = BMSPushUrlBuilder(applicationID: self.applicationId!,clientSecret:self.clientSecret!)
let resourceURL:String = urlBuilder.getSubscribedDevicesUrl(devID: devId)
let headers = urlBuilder.addHeader()
let method = HttpMethod.GET
self.sendAnalyticsData(logType: LogLevel.debug, logStringData: "Verifying previous device registration.")
let getRequest = Request(url: resourceURL, method: method, headers: headers, queryParameters: nil, timeout: 60)
// MARK: FIrst Action, checking for previuos registration
getRequest.send(completionHandler: { (response, error) -> Void in
if response?.statusCode != nil {
let status = response?.statusCode ?? 0
let responseText = response?.responseText ?? ""
if (status == 404) {
self.sendAnalyticsData(logType: LogLevel.debug, logStringData: "Device is not registered before. Registering for the first time.")
let resourceURL:String = urlBuilder.getDevicesUrl()
let headers = urlBuilder.addHeader()
let method = HttpMethod.POST
let getRequest = Request(url: resourceURL, method: method, headers: headers, queryParameters: nil, timeout: 60, cachePolicy: .useProtocolCachePolicy)
let data = "{\"\(IMFPUSH_DEVICE_ID)\": \"\(devId)\", \"\(IMFPUSH_TOKEN)\": \"\(token)\", \"\(IMFPUSH_PLATFORM)\": \"A\", \"\(IMFPUSH_USERID)\": \"\(WithUserId!)\"}".data(using: .utf8)
// MARK: Registering for the First Time
getRequest.send(requestBody: data!, completionHandler: { (response, error) -> Void in
if response?.statusCode != nil {
let status = response?.statusCode ?? 0
if (status == 201){
let responseText = response?.responseText ?? ""
self.sendAnalyticsData(logType: LogLevel.info, logStringData: "Response of device registration - Response is: \(responseText)")
completionHandler(responseText, status, "")
}else{
self.sendAnalyticsData(logType: LogLevel.error, logStringData: "Error during device registration - Error code is: \(status) and error is: \(String(describing: response?.responseText))")
completionHandler("", IMFPushErrorvalues.IMFPushRegistrationError.rawValue, "Error during device registration - Error code is: \(status) and error is: \(String(describing: response?.responseText))")
}
}
else if let responseError = error {
self.sendAnalyticsData(logType: LogLevel.error, logStringData: "Error during device registration - Error is: \(responseError.localizedDescription)")
completionHandler("", IMFPushErrorvalues.IMFPushRegistrationError.rawValue, "Error during device registration - Error is: \(responseError.localizedDescription)")
}
})
}else if (status == 200){
// MARK: device is already Registered
self.sendAnalyticsData(logType: LogLevel.debug, logStringData: "Device is already registered. Return the device Id - Response is: \(String(describing: response?.responseText))")
let respJson = response?.responseText
let data = respJson!.data(using: String.Encoding.utf8)
let jsonResponse:NSDictionary = try! JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary
let rToken = jsonResponse.object(forKey: IMFPUSH_TOKEN) as! String
let rDevId = jsonResponse.object(forKey: IMFPUSH_DEVICE_ID) as! String
let userId = jsonResponse.object(forKey: IMFPUSH_USERID) as! String
if ((rToken.compare(token)) != ComparisonResult.orderedSame) ||
(!(WithUserId!.isEmpty) && (WithUserId!.compare(userId) != ComparisonResult.orderedSame)) || (devId.compare(rDevId) != ComparisonResult.orderedSame){
// MARK: Updating the registered device ,userID, token or deviceId changed
self.sendAnalyticsData(logType: LogLevel.debug, logStringData: "Device token or DeviceId has changed. Sending update registration request.")
let resourceURL:String = urlBuilder.getSubscribedDevicesUrl(devID: devId)
let headers = urlBuilder.addHeader()
let method = HttpMethod.PUT
let getRequest = Request(url: resourceURL, method: method, headers: headers, queryParameters: nil, timeout: 60, cachePolicy: .useProtocolCachePolicy)
let data = "{\"\(IMFPUSH_DEVICE_ID)\": \"\(devId)\", \"\(IMFPUSH_TOKEN)\": \"\(token)\", \"\(IMFPUSH_USERID)\": \"\(WithUserId!)\"}".data(using: .utf8)
getRequest.send(requestBody: data!, completionHandler: { (response, error) -> Void in
if response?.statusCode != nil {
let status = response?.statusCode ?? 0
if (status == 200){
let responseText = response?.responseText ?? ""
self.sendAnalyticsData(logType: LogLevel.info, logStringData: "Response of device registration - Response is: \(responseText)")
completionHandler(responseText, status, "")
}else{
self.sendAnalyticsData(logType: LogLevel.error, logStringData: "Error during device registration - Error code is: \(status) and error is: \(String(describing: response?.responseText))")
completionHandler("", IMFPushErrorvalues.IMFPushRegistrationError.rawValue, "Error during device registration - Error code is: \(status) and error is: \(String(describing: response?.responseText))")
}
}
else if let responseError = error {
self.sendAnalyticsData(logType: LogLevel.error, logStringData: "Error during device updatation - Error is : \(responseError.localizedDescription)")
completionHandler("", IMFPushErrorvalues.IMFPushRegistrationUpdateError.rawValue, "Error during device updatation - Error is : \(responseError.localizedDescription)")
}
})
}
else {
// MARK: device already registered and parameteres not changed.
self.sendAnalyticsData(logType: LogLevel.info, logStringData: "Device is already registered and device registration parameters not changed.")
completionHandler(response?.responseText, status, "")
}
}
else{
self.sendAnalyticsData(logType: LogLevel.error, logStringData: "Error while verifying previous registration - Error is: \(error!.localizedDescription)")
completionHandler("", status, responseText)
}
}
else if let responseError = error {
self.sendAnalyticsData(logType: LogLevel.error, logStringData: "Error while verifying previous registration - Error is: \(responseError.localizedDescription)")
completionHandler("", IMFPushErrorvalues.IMFPushRegistrationVerificationError.rawValue , "Error while verifying previous registration - Error is: \(responseError.localizedDescription)")
}
})
}else{
self.sendAnalyticsData(logType: LogLevel.error, logStringData: "Error while registration - Provide a valid userId value")
completionHandler("", IMFPushErrorvalues.IMFPushRegistrationError.rawValue , "Error while registration - Provide a valid userId value")
}
}else{
self.sendAnalyticsData(logType: LogLevel.error, logStringData: "Error while registration - BMSPush is not initialized")
completionHandler("", IMFPushErrorvalues.IMFPushRegistrationError.rawValue , "Error while registration - BMSPush is not initialized")
}
}
/**
This Methode used to register the client device to the Bluemix Push service. This is the normal registration, without userId.
Call this methode after successfully registering for remote push notification in the Apple Push
Notification Service .
- Parameter deviceToken: This is the response we get from the push registartion in APNS.
- Parameter completionHandler: The closure that will be called when this request finishes. The response will contain response (String), StatusCode (Int) and error (string).
*/
public func registerWithDeviceToken (deviceToken:Data, completionHandler: @escaping(_ response:String?, _ statusCode:Int?, _ error:String) -> Void) {
if (isInitialized){
let devId = self.getDeviceID()
BMSPushUtils.saveValueToNSUserDefaults(value: devId, key: "deviceId")
var token = ""
for i in 0..<deviceToken.count {
token = token + String(format: "%02.2hhx", arguments: [deviceToken[i]])
}
self.applicationId = BMSPushUtils.getValueToNSUserDefaults(key: BMSPUSH_APP_GUID)
self.clientSecret = BMSPushUtils.getValueToNSUserDefaults(key: BMSPUSH_CLIENT_SECRET)
if(self.applicationId == "" || self.clientSecret == ""){
self.sendAnalyticsData(logType: LogLevel.error, logStringData: "Error while registration - Error is: push is not initialized")
completionHandler("", IMFPushErrorvalues.IMFPushRegistrationError.rawValue , "Error while registration - Error is: push is not initialized")
return
}
let urlBuilder = BMSPushUrlBuilder(applicationID: self.applicationId!,clientSecret:self.clientSecret!)
let resourceURL:String = urlBuilder.getSubscribedDevicesUrl(devID: devId)
let headers = urlBuilder.addHeader()
let method = HttpMethod.GET
self.sendAnalyticsData(logType: LogLevel.debug, logStringData: "Verifying previous device registration.")
let getRequest = Request(url: resourceURL, method: method, headers: headers, queryParameters: nil, timeout: 60)
// MARK: FIrst Action, checking for previuos registration
getRequest.send(completionHandler: { (response, error) -> Void in
if response?.statusCode != nil {
let status = response?.statusCode ?? 0
let responseText = response?.responseText ?? ""
if (status == 404) {
self.sendAnalyticsData(logType: LogLevel.debug, logStringData: "Device is not registered before. Registering for the first time.")
let resourceURL:String = urlBuilder.getDevicesUrl()
let headers = urlBuilder.addHeader()
let method = HttpMethod.POST
let getRequest = Request(url: resourceURL, method: method, headers: headers, queryParameters: nil, timeout: 60, cachePolicy: .useProtocolCachePolicy)
let data = "{\"\(IMFPUSH_DEVICE_ID)\": \"\(devId)\", \"\(IMFPUSH_TOKEN)\": \"\(token)\", \"\(IMFPUSH_PLATFORM)\": \"A\"}".data(using: .utf8)
// MARK: Registering for the First Time
getRequest.send(requestBody: data!, completionHandler: { (response, error) -> Void in
if response?.statusCode != nil {
let status = response?.statusCode ?? 0
if (status == 201){
let responseText = response?.responseText ?? ""
self.sendAnalyticsData(logType: LogLevel.info, logStringData: "Response of device registration - Response is: \(responseText)")
completionHandler(responseText, status, "")
}else{
self.sendAnalyticsData(logType: LogLevel.error, logStringData: "Error during device registration - Error code is: \(status) and error is: \(String(describing: response?.responseText)) ")
completionHandler("", IMFPushErrorvalues.IMFPushRegistrationError.rawValue, "Error during device registration - Error code is: \(status) and error is: \(String(describing: response?.responseText))")
}
}
else if let responseError = error {
self.sendAnalyticsData(logType: LogLevel.error, logStringData: "Error during device registration - Error is: \(responseError.localizedDescription)")
completionHandler("", IMFPushErrorvalues.IMFPushRegistrationError.rawValue, "Error during device registration - Error is: \(responseError.localizedDescription)")
}
})
}else if (status == 200){
// MARK: device is already Registered
self.sendAnalyticsData(logType: LogLevel.debug, logStringData: "Device is already registered. Return the device Id - Response is: \(String(describing: response?.responseText))")
let respJson = response?.responseText
let data = respJson!.data(using: String.Encoding.utf8)
let jsonResponse:NSDictionary = try! JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary
let rToken = jsonResponse.object(forKey: IMFPUSH_TOKEN) as! String
let rDevId = jsonResponse.object(forKey: IMFPUSH_DEVICE_ID) as! String
let userId = jsonResponse.object(forKey: IMFPUSH_USERID) as! String
if ((rToken.compare(token)) != ComparisonResult.orderedSame) || (devId.compare(rDevId) != ComparisonResult.orderedSame) || (userId != "anonymous") {
// MARK: Updating the registered userID , token or deviceId changed
self.sendAnalyticsData(logType: LogLevel.debug, logStringData: "Device token or DeviceId has changed. Sending update registration request.")
let resourceURL:String = urlBuilder.getSubscribedDevicesUrl(devID: devId)
let headers = urlBuilder.addHeader()
let method = HttpMethod.PUT
let getRequest = Request(url: resourceURL, method: method, headers: headers, queryParameters: nil, timeout: 60, cachePolicy: .useProtocolCachePolicy)
let data = "{\"\(IMFPUSH_DEVICE_ID)\": \"\(devId)\", \"\(IMFPUSH_TOKEN)\": \"\(token)\"}".data(using: .utf8)
getRequest.send(requestBody: data!, completionHandler: { (response, error) -> Void in
if response?.statusCode != nil {
let status = response?.statusCode ?? 0
if (status == 200){
let responseText = response?.responseText ?? ""
self.sendAnalyticsData(logType: LogLevel.info, logStringData: "Response of device registration - Response is: \(responseText)")
completionHandler(responseText, status, "")
}else{
self.sendAnalyticsData(logType: LogLevel.error, logStringData: "Error during device registration - Error code is: \(status) and error is: \(String(describing: response?.responseText))")
completionHandler("", IMFPushErrorvalues.IMFPushRegistrationError.rawValue, "Error during device registration - Error code is: \(status) and error is: \(String(describing: response?.responseText))")
}
}
else if let responseError = error {
self.sendAnalyticsData(logType: LogLevel.error, logStringData: "Error during device updatation - Error is : \(responseError.localizedDescription)")
completionHandler("", IMFPushErrorvalues.IMFPushRegistrationUpdateError.rawValue, "Error during device updatation - Error is : \(responseError.localizedDescription)")
}
})
}
else {
// MARK: device already registered and parameteres not changed.
self.sendAnalyticsData(logType: LogLevel.info, logStringData: "Device is already registered and device registration parameters not changed.")
completionHandler(response?.responseText, status, "")
}
}else{
self.sendAnalyticsData(logType: LogLevel.error, logStringData: "Error while verifying previous registration - Error is: \(error!.localizedDescription)")
completionHandler("", status, responseText)
}
}
else if let responseError = error {
self.sendAnalyticsData(logType: LogLevel.error, logStringData: "Error while verifying previous registration - Error is: \(responseError.localizedDescription)")
completionHandler("", IMFPushErrorvalues.IMFPushRegistrationVerificationError.rawValue , "Error while verifying previous registration - Error is: \(responseError.localizedDescription)")
}
})
}else{
self.sendAnalyticsData(logType: LogLevel.error, logStringData: "Error while registration - BMSPush is not initialized")
completionHandler("", IMFPushErrorvalues.IMFPushRegistrationError.rawValue , "Error while registration - BMSPush is not initialized")
}
}
/**
This Method used to Retrieve all the available Tags in the Bluemix Push Service.
This methode will return the list of available Tags in an Array.
- Parameter completionHandler: The closure that will be called when this request finishes. The response will contain response (NSMutableArray), StatusCode (Int) and error (string).
*/
public func retrieveAvailableTagsWithCompletionHandler (completionHandler: @escaping(_ response:NSMutableArray?, _ statusCode:Int?, _ error:String) -> Void){
self.sendAnalyticsData(logType: LogLevel.debug, logStringData: "Entering retrieveAvailableTagsWithCompletitionHandler.")
self.applicationId = BMSPushUtils.getValueToNSUserDefaults(key: BMSPUSH_APP_GUID)
self.clientSecret = BMSPushUtils.getValueToNSUserDefaults(key: BMSPUSH_CLIENT_SECRET)
if(self.applicationId == "" || self.clientSecret == ""){
self.sendAnalyticsData(logType: LogLevel.error, logStringData: "Error while retrieving available tags - Error is: push is not initialized")
completionHandler([], IMFPushErrorvalues.IMFPushRetrieveTagsError.rawValue , "Error while retrieving available tags - Error is: push is not initialized")
return
}
let urlBuilder = BMSPushUrlBuilder(applicationID: self.applicationId!,clientSecret:self.clientSecret!)
let resourceURL:String = urlBuilder.getTagsUrl()
let headers = urlBuilder.addHeader()
let method = HttpMethod.GET
let getRequest = Request(url: resourceURL, method: method, headers: headers, queryParameters: nil, timeout: 60)
getRequest.send(completionHandler:{ (response, error) -> Void in
if response?.statusCode != nil {
let status = response?.statusCode ?? 0
if (status == 200){
let responseText = response?.responseText ?? ""
self.sendAnalyticsData(logType: LogLevel.info, logStringData: "Successfully retrieved available tags - Response is: \(responseText)")
let availableTagsArray = response?.availableTags()
completionHandler(availableTagsArray, status, "")
}else{
self.sendAnalyticsData(logType: LogLevel.error, logStringData: "Error while retrieving available tags - Error code is: \(status) and error is: \(String(describing: response?.responseText))")
completionHandler([], IMFPushErrorvalues.IMFPushRetrieveTagsError.rawValue,"Error while retrieving available tags - Error code is: \(status) and error is: \(String(describing: response?.responseText))")
}
} else if let responseError = error {
self.sendAnalyticsData(logType: LogLevel.error, logStringData: "Error while retrieving available tags - Error is: \(responseError.localizedDescription)")
completionHandler([], IMFPushErrorvalues.IMFPushRetrieveTagsError.rawValue,"Error while retrieving available tags - Error is: \(responseError.localizedDescription)")
}
})
}
/**
This Methode used to Subscribe to the Tags in the Bluemix Push srvice.
This methode will return the list of subscribed tags. If you pass the tags that are not present in the Bluemix App it will be classified under the TAGS NOT FOUND section in the response.
- parameter tagsArray: the array that contains name tags.
- Parameter completionHandler: The closure that will be called when this request finishes. The response will contain response (NSMutableDictionary), StatusCode (Int) and error (string).
*/
public func subscribeToTags (tagsArray:NSArray, completionHandler: @escaping (_ response:NSMutableDictionary?, _ statusCode:Int?, _ error:String) -> Void) {
self.sendAnalyticsData(logType: LogLevel.debug, logStringData:"Entering: subscribeToTags." )
if tagsArray.count != 0 {
let devId = self.getDeviceID()
self.applicationId = BMSPushUtils.getValueToNSUserDefaults(key: BMSPUSH_APP_GUID)
self.clientSecret = BMSPushUtils.getValueToNSUserDefaults(key: BMSPUSH_CLIENT_SECRET)
if(self.applicationId == "" || self.clientSecret == ""){
self.sendAnalyticsData(logType: LogLevel.error, logStringData: "Error while subscribing to tags - Error is: push is not initialized")
completionHandler([:], IMFPushErrorvalues.IMFPushTagSubscriptionError.rawValue , "Error while subscribing to tags - Error is: push is not initialized")
return
}
let urlBuilder = BMSPushUrlBuilder(applicationID: self.applicationId!,clientSecret:self.clientSecret!)
let resourceURL:String = urlBuilder.getSubscriptionsUrl()
let headers = urlBuilder.addHeader()
let method = HttpMethod.POST
let getRequest = Request(url: resourceURL, method: method, headers: headers, queryParameters: nil, timeout: 60, cachePolicy: .useProtocolCachePolicy)
let mappedArray = tagsArray.flatMap{"\($0)"}.description;
let data = "{\"\(IMFPUSH_TAGNAMES)\":\(mappedArray), \"\(IMFPUSH_DEVICE_ID)\":\"\(devId)\"}".data(using: .utf8)
getRequest.send(requestBody: data!, completionHandler: { (response, error) -> Void in
if response?.statusCode != nil {
let status = response?.statusCode ?? 0
if (status == 207){
let responseText = response?.responseText ?? ""
self.sendAnalyticsData(logType: LogLevel.info, logStringData: "Successfully subscribed to tags - Response is: \(responseText)")
let subscriptionResponse = response?.subscribeStatus()
completionHandler(subscriptionResponse, status, "")
}else{
self.sendAnalyticsData(logType: LogLevel.error, logStringData: "Error while subscribing to tags - Error code is: \(status) and error is: \(String(describing: response?.responseText))")
completionHandler([:], IMFPushErrorvalues.IMFPushTagSubscriptionError.rawValue,"Error while subscribing to tags - Error code is: \(status) and error is: \(String(describing: response?.responseText))")
}
} else if let responseError = error {
self.sendAnalyticsData(logType: LogLevel.error, logStringData: "Error while subscribing to tags - Error is: \(responseError.localizedDescription)")
completionHandler([:], IMFPushErrorvalues.IMFPushTagSubscriptionError.rawValue,"Error while subscribing to tags - Error is: \(responseError.localizedDescription)")
}
})
} else {
let subscriptionResponse = NSMutableDictionary()
self.sendAnalyticsData(logType: LogLevel.error, logStringData: "Error. Tag array cannot be null. Create tags in your Bluemix App")
completionHandler(subscriptionResponse, IMFPushErrorvalues.IMFPushErrorEmptyTagArray.rawValue, "Error. Tag array cannot be null. Create tags in your Bluemix App")
}
}
/**
This Methode used to Retrieve the Subscribed Tags in the Bluemix Push srvice.
This methode will return the list of subscribed tags.
- Parameter completionHandler: The closure that will be called when this request finishes. The response will contain response (NSMutableArray), StatusCode (Int) and error (string).
*/
public func retrieveSubscriptionsWithCompletionHandler (completionHandler: @escaping (_ response:NSMutableArray?, _ statusCode:Int?, _ error:String) -> Void) {
self.sendAnalyticsData(logType: LogLevel.debug, logStringData: "Entering retrieveSubscriptionsWithCompletitionHandler.")
let devId = self.getDeviceID()
self.applicationId = BMSPushUtils.getValueToNSUserDefaults(key: BMSPUSH_APP_GUID)
self.clientSecret = BMSPushUtils.getValueToNSUserDefaults(key: BMSPUSH_CLIENT_SECRET)
if(self.applicationId == "" || self.clientSecret == ""){
self.sendAnalyticsData(logType: LogLevel.error, logStringData: "Error while retrieving subscriptions - Error is: push is not initialized")
completionHandler([], IMFPushErrorvalues.IMFPushTagSubscriptionError.rawValue , "Error while retrieving subscriptions - Error is: push is not initialized")
return
}
let urlBuilder = BMSPushUrlBuilder(applicationID: self.applicationId!,clientSecret:self.clientSecret!)
let resourceURL:String = urlBuilder.getAvailableSubscriptionsUrl(deviceId: devId)
let headers = urlBuilder.addHeader()
let method = HttpMethod.GET
let getRequest = Request(url: resourceURL, method: method, headers: headers, queryParameters: nil, timeout: 60)
getRequest.send(completionHandler: { (response, error) -> Void in
if response?.statusCode != nil {
let status = response?.statusCode ?? 0
if (status == 200){
let responseText = response?.responseText ?? ""
self.sendAnalyticsData(logType: LogLevel.info, logStringData: "Subscription retrieved successfully - Response is: \(responseText)")
let subscriptionArray = response?.subscriptions()
completionHandler(subscriptionArray, status, "")
}else{
self.sendAnalyticsData(logType: LogLevel.error, logStringData: "Error while retrieving subscriptions - Error codeis: \(status) and error is: \(String(describing: response?.responseText))")
completionHandler([], IMFPushErrorvalues.IMFPushRetrieveSubscriptionError.rawValue,"Error while retrieving subscriptions - Error code is: \(status) and error is: \(String(describing: response?.responseText))")
}
} else if let responseError = error {
self.sendAnalyticsData(logType: LogLevel.error, logStringData: "Error while retrieving subscriptions - Error is: \(responseError.localizedDescription)")
completionHandler([], IMFPushErrorvalues.IMFPushRetrieveSubscriptionError.rawValue,"Error while retrieving subscriptions - Error is: \(responseError.localizedDescription)")
}
})
}
/**
This Methode used to Unsubscribe from the Subscribed Tags in the Bluemix Push srvice.
This methode will return the details of Unsubscription status.
- Parameter tagsArray: The list of tags that need to be unsubscribed.
- Parameter completionHandler: The closure that will be called when this request finishes. The response will contain response (NSMutableDictionary), StatusCode (Int) and error (string).
*/
public func unsubscribeFromTags (tagsArray:NSArray, completionHandler: @escaping (_ response:NSMutableDictionary?, _ statusCode:Int?, _ error:String) -> Void) {
self.sendAnalyticsData(logType: LogLevel.debug, logStringData: "Entering: unsubscribeFromTags")
if tagsArray.count != 0 {
let devId = self.getDeviceID()
self.applicationId = BMSPushUtils.getValueToNSUserDefaults(key: BMSPUSH_APP_GUID)
self.clientSecret = BMSPushUtils.getValueToNSUserDefaults(key: BMSPUSH_CLIENT_SECRET)
if(self.applicationId == "" || self.clientSecret == ""){
self.sendAnalyticsData(logType: LogLevel.error, logStringData: "Error while unsubscribing from tags - Error is: push is not initialized")
completionHandler([:], IMFPushErrorvalues.IMFPushTagUnsubscriptionError.rawValue , "Error while unsubscribing from tags - Error is: push is not initialized")
return
}
let urlBuilder = BMSPushUrlBuilder(applicationID: self.applicationId!,clientSecret:self.clientSecret!)
let resourceURL:String = urlBuilder.getUnSubscribetagsUrl()
let headers = urlBuilder.addHeader()
let method = HttpMethod.POST
let getRequest = Request(url: resourceURL, method: method, headers: headers, queryParameters: nil, timeout: 60, cachePolicy: .useProtocolCachePolicy)
let mappedArray = tagsArray.flatMap{"\($0)"}.description;
let data = "{\"\(IMFPUSH_TAGNAMES)\":\(mappedArray), \"\(IMFPUSH_DEVICE_ID)\":\"\(devId)\"}".data(using: .utf8)
getRequest.send(requestBody: data!, completionHandler: { (response, error) -> Void in
if response?.statusCode != nil {
let status = response?.statusCode ?? 0
let responseText = response?.responseText ?? ""
self.sendAnalyticsData(logType: LogLevel.info, logStringData: "Successfully unsubscribed from tags - Response is: \(responseText)")
let unSubscriptionResponse = response?.unsubscribeStatus()
completionHandler(unSubscriptionResponse, status, "")
} else if let responseError = error{
let unSubscriptionResponse = NSMutableDictionary()
self.sendAnalyticsData(logType: LogLevel.error, logStringData: "Error while unsubscribing from tags - Error is: \(responseError.localizedDescription)")
completionHandler(unSubscriptionResponse, IMFPushErrorvalues.IMFPushTagUnsubscriptionError.rawValue,"Error while unsubscribing from tags - Error is: \(responseError.localizedDescription)")
}
})
} else {
let unSubscriptionResponse = NSMutableDictionary()
self.sendAnalyticsData(logType: LogLevel.error, logStringData: "Error. Tag array cannot be null.")
completionHandler(unSubscriptionResponse, IMFPushErrorvalues.IMFPushErrorEmptyTagArray.rawValue, "Error. Tag array cannot be null.")
}
}
/**
This Methode used to UnRegister the client App from the Bluemix Push srvice.
- Parameter completionHandler: The closure that will be called when this request finishes. The response will contain response (String), StatusCode (Int) and error (string).
*/
public func unregisterDevice (completionHandler: @escaping (_ response:String?, _ statusCode:Int?, _ error:String) -> Void) {
self.sendAnalyticsData(logType: LogLevel.debug, logStringData: "Entering unregisterDevice.")
let devId = self.getDeviceID()
self.applicationId = BMSPushUtils.getValueToNSUserDefaults(key: BMSPUSH_APP_GUID)
self.clientSecret = BMSPushUtils.getValueToNSUserDefaults(key: BMSPUSH_CLIENT_SECRET)
if(self.applicationId == "" || self.clientSecret == ""){
self.sendAnalyticsData(logType: LogLevel.error, logStringData: "Error while unregistering device - Error is: push is not initialized")
completionHandler("", IMFPushErrorvalues.IMFPushTagUnsubscriptionError.rawValue , "Error while unregistering device - Error is: push is not initialized")
return
}
let urlBuilder = BMSPushUrlBuilder(applicationID: self.applicationId!,clientSecret:self.clientSecret!)
let resourceURL:String = urlBuilder.getUnregisterUrl(deviceId: devId)
let headers = urlBuilder.addHeader()
let method = HttpMethod.DELETE
let getRequest = Request(url: resourceURL, method: method, headers: headers, queryParameters: nil, timeout: 60)
getRequest.send(completionHandler: { (response, error) -> Void in
if response?.statusCode != nil {
let status = response?.statusCode ?? 0
if (status == 204){
let responseText = response?.responseText ?? ""
self.sendAnalyticsData(logType: LogLevel.info, logStringData: "Successfully unregistered the device. - Response is: \(String(describing: response?.responseText))")
completionHandler(responseText, status, "")
}else{
self.sendAnalyticsData(logType: LogLevel.error, logStringData: "Error while unregistering device - Error code is: \(status) and error is: \(String(describing: response?.responseText))")
completionHandler("", IMFPushErrorvalues.BMSPushUnregitrationError.rawValue,"Error while unregistering device - Error code is: \(status) and error is: \(String(describing: response?.responseText))")
}
} else if let responseError = error {
self.sendAnalyticsData(logType: LogLevel.error, logStringData: "Error while unregistering device - Error is: \(responseError.localizedDescription)")
completionHandler("", IMFPushErrorvalues.BMSPushUnregitrationError.rawValue,"Error while unregistering device - Error is: \(responseError.localizedDescription)")
}
})
}
public func sendMessageDeliveryStatus (messageId:String, completionHandler: @escaping (_ response:String?, _ statusCode:Int?, _ error:String) -> Void) {
self.sendAnalyticsData(logType: LogLevel.debug, logStringData: "Entering sendMessageDeliveryStatus.")
let devId = self.getDeviceID()
self.applicationId = BMSPushUtils.getValueToNSUserDefaults(key: BMSPUSH_APP_GUID)
self.clientSecret = BMSPushUtils.getValueToNSUserDefaults(key: BMSPUSH_CLIENT_SECRET)
if(self.applicationId == "" || self.clientSecret == ""){
self.sendAnalyticsData(logType: LogLevel.error, logStringData: "Failed to update the message status - Error is: push is not initialized")
completionHandler("", IMFPushErrorvalues.IMFPushTagUnsubscriptionError.rawValue , "Failed to update the message status - Error is: push is not initialized")
return
}
let urlBuilder = BMSPushUrlBuilder(applicationID: self.applicationId!,clientSecret:self.clientSecret!)
let resourceURL:String = urlBuilder.getSendMessageDeliveryStatus(messageId: messageId)
let headers = urlBuilder.addHeader()
let method = HttpMethod.PUT
var status = "";
if (UIApplication.shared.applicationState == UIApplicationState.background){
status = "SEEN";
} else {
status = "OPEN"
}
if !(status.isEmpty){
let json = [
IMFPUSH_DEVICE_ID : devId,
IMFPUSH_STATUS : status
]
let data = try? JSONSerialization.data(withJSONObject: json, options: [])
let getRequest = Request(url: resourceURL, method: method, headers: headers, queryParameters: nil, timeout: 60)
getRequest.send(requestBody: data!, completionHandler: { (response, error) -> Void in
if response?.statusCode != nil {
let responseText = response?.responseText ?? ""
self.sendAnalyticsData(logType: LogLevel.info, logStringData: "Successfully updated the message status. The response is: \(responseText)")
print("Successfully updated the message status. The response is: "+responseText)
completionHandler(responseText,200,"")
} else if let responseError = error{
self.sendAnalyticsData(logType: LogLevel.error, logStringData: "Failed to update the message status. The response is: \(responseError.localizedDescription)")
print("Failed to update the message status. The response is: "+responseError.localizedDescription)
completionHandler("",400,responseError.localizedDescription)
}
})
} else{
self.sendAnalyticsData(logType: LogLevel.error, logStringData: "Failed to update the message status. The response is: Status should be either SEEN or OPEN")
print("Failed to update the message status. The response is: Status should be either SEEN or OPEN")
}
}
// MARK: Methods (Internal)
//Begin Logger implementation
// Setting Log info
internal func sendAnalyticsData (logType:LogLevel, logStringData:String){
let devId = self.getDeviceID()
let testLogger = Logger.logger(name:devId)
if (logType == LogLevel.debug){
Logger.logLevelFilter = LogLevel.debug
testLogger.debug(message: logStringData)
} else if (logType == LogLevel.error){
Logger.logLevelFilter = LogLevel.error
testLogger.error(message: logStringData)
} else if (logType == LogLevel.analytics){
Logger.logLevelFilter = LogLevel.analytics
testLogger.debug(message: logStringData)
} else if (logType == LogLevel.fatal){
Logger.logLevelFilter = LogLevel.fatal
testLogger.fatal(message: logStringData)
} else if (logType == LogLevel.warn){
Logger.logLevelFilter = LogLevel.warn
testLogger.warn(message: logStringData)
} else if (logType == LogLevel.info){
Logger.logLevelFilter = LogLevel.info
testLogger.info(message: logStringData)
}
else {
Logger.logLevelFilter = LogLevel.none
testLogger.debug(message: logStringData)
}
}
internal func validateString(object:String) -> Bool{
if (object.isEmpty || object == "") {
return false;
}
return true
}
internal func getDeviceID() -> String{
var devId = String()
if ((self.bluemixDeviceId == nil) || (self.bluemixDeviceId?.isEmpty)!) {
// Generate new ID
let authManager = BMSClient.sharedInstance.authorizationManager
devId = authManager.deviceIdentity.ID!
}else{
devId = self.bluemixDeviceId!
}
return devId
}
internal func checkStatusChange(){
if(UserDefaults.standard.object(forKey: BMSPUSH_APP_INSTALL) != nil) {
let notificationType = UIApplication.shared.currentUserNotificationSettings?.types
if notificationType?.rawValue == 0 {
print("Push Disabled")
self.delegate?.onChangePermission(status: false)
} else {
print("Push Enabled")
self.delegate?.onChangePermission(status: true)
UIApplication.shared.registerForRemoteNotifications()
}
} else {
UserDefaults.standard.set(true, forKey: BMSPUSH_APP_INSTALL)
UserDefaults.standard.synchronize()
NotificationCenter.default.addObserver(forName: NSNotification.Name.UIApplicationDidBecomeActive, object: nil, queue: OperationQueue.main) { (notifiction) in
let when = DispatchTime.now() + 1
DispatchQueue.main.asyncAfter(deadline: when) {
let notificationType = UIApplication.shared.currentUserNotificationSettings?.types
if notificationType?.rawValue == 0 {
print("Push Disabled")
self.delegate?.onChangePermission(status: false)
} else {
print("Push Enabled")
self.delegate?.onChangePermission(status: true)
UIApplication.shared.registerForRemoteNotifications()
}
}
}
}
}
}
/**************************************************************************************************/
// MARK: - Swift 2
#else
public enum IMFPushErrorvalues: Int {
/// - IMFPushErrorInternalError: Denotes the Internal Server Error occured.
case IMFPushErrorInternalError = 1
/// - IMFPushErrorEmptyTagArray: Denotes the Empty Tag Array Error.
case IMFPushErrorEmptyTagArray = 2
/// - IMFPushRegistrationVerificationError: Denotes the Previous Push registration Error.
case IMFPushRegistrationVerificationError = 3
/// - IMFPushRegistrationError: Denotes the First Time Push registration Error.
case IMFPushRegistrationError = 4
/// - IMFPushRegistrationUpdateError: Denotes the Device updation Error.
case IMFPushRegistrationUpdateError = 5
/// - IMFPushRetrieveSubscriptionError: Denotes the Subscribed tags retrieval error.
case IMFPushRetrieveSubscriptionError = 6
/// - IMFPushRetrieveSubscriptionError: Denotes the Available tags retrieval error.
case IMFPushRetrieveTagsError = 7
/// - IMFPushTagSubscriptionError: Denotes the Tag Subscription error.
case IMFPushTagSubscriptionError = 8
/// - IMFPushTagUnsubscriptionError: Denotes the tag Unsubscription error.
case IMFPushTagUnsubscriptionError = 9
/// - BMSPushUnregitrationError: Denotes the Push Unregistration error.
case BMSPushUnregitrationError = 10
}
/**
A singleton that serves as an entry point to Bluemix client-Push service communication.
*/
public class BMSPushClient: NSObject {
// MARK: Properties (Public)
/// This singleton should be used for all `BMSPushClient` activity.
public static let sharedInstance = BMSPushClient()
private var _notificationOptions : BMSPushClientOptions?
public var notificationOptions:BMSPushClientOptions? {
get{
return _notificationOptions
}
set(value){
_notificationOptions = value
}
}
// Specifies the bluemix push clientSecret value
public private(set) var clientSecret: String?
public private(set) var applicationId: String?
public private(set) var bluemixDeviceId: String?
// used to test in test zone and dev zone
public static var overrideServerHost = "";
// MARK: Properties (private)
/// `BMSClient` object.
private var bmsClient = BMSClient.sharedInstance
// Notification Count
private var notificationcount:Int = 0
private var isInitialized = false;
public var delegate:BMSPushObserver?
// MARK: Initializers
/**
The required intializer for the `BMSPushClient` class.
This method will intialize the BMSPushClient with clientSecret based registration.
- parameter clientSecret: The clientSecret of the Push Service
- parameter appGUID: The pushAppGUID of the Push Service
*/
public func initializeWithAppGUID (appGUID appGUID: String, clientSecret: String) {
if validateString(clientSecret) {
self.clientSecret = clientSecret
self.applicationId = appGUID
BMSPushUtils.saveValueToNSUserDefaults(appGUID, key: BMSPUSH_APP_GUID)
BMSPushUtils.saveValueToNSUserDefaults(clientSecret, key: BMSPUSH_CLIENT_SECRET)
isInitialized = true;
let settings = UIUserNotificationSettings(forTypes: [.Alert,.Badge,.Sound], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
self.checkStatusChange()
}
else{
self.sendAnalyticsData(LogLevel.error, logStringData: "Error while registration - Client secret is not valid")
print("Error while registration - Client secret is not valid")
}
}
/**
The required intializer for the `BMSPushClient` class.
This method will intialize the BMSPushClient with clientSecret based registration and take in notificationOptions.
- parameter clientSecret: The clientSecret of the Push Service
- parameter appGUID: The pushAppGUID of the Push Service
- parameter options: The optional push notification options
*/
public func initializeWithAppGUID (appGUID: String, clientSecret: String, options: BMSPushClientOptions) {
if validateString(clientSecret) {
self.clientSecret = clientSecret
self.applicationId = appGUID
BMSPushUtils.saveValueToNSUserDefaults(appGUID, key: BMSPUSH_APP_GUID)
BMSPushUtils.saveValueToNSUserDefaults(clientSecret, key: BMSPUSH_CLIENT_SECRET)
isInitialized = true;
let category : [BMSPushNotificationActionCategory] = options.category
self.bluemixDeviceId = options.deviceId
var notifCategory = Set<UIUserNotificationCategory>();
for singleCategory in category {
let categoryFirst : BMSPushNotificationActionCategory = singleCategory
let pushNotificationAction : [BMSPushNotificationAction] = categoryFirst.actions
let pushCategoryIdentifier : String = categoryFirst.identifier
var pushActionsArray = [UIUserNotificationAction]()
for actionButton in pushNotificationAction {
let newActionButton : BMSPushNotificationAction = actionButton
let addButton : UIMutableUserNotificationAction = UIMutableUserNotificationAction()
addButton.identifier = newActionButton.identifier
addButton.title = newActionButton.title
addButton.activationMode = newActionButton.activationMode
pushActionsArray.append(addButton)
}
let responseCategory : UIMutableUserNotificationCategory = UIMutableUserNotificationCategory()
responseCategory.identifier = pushCategoryIdentifier
responseCategory.setActions(pushActionsArray, forContext:UIUserNotificationActionContext.Default)
responseCategory.setActions(pushActionsArray, forContext:UIUserNotificationActionContext.Minimal)
notifCategory.insert(responseCategory)
}
if notifCategory.isEmpty {
let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories:nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
}else{
let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: notifCategory)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
}
self.checkStatusChange()
}
else{
self.sendAnalyticsData(LogLevel.error, logStringData: "Error while registration - Client secret is not valid")
print("Error while registration - Client secret is not valid")
}
}
// MARK: Methods (Public)
/**
This Methode used to register the client device to the Bluemix Push service. This is the normal registration, without userId.
Call this methode after successfully registering for remote push notification in the Apple Push
Notification Service .
- Parameter deviceToken: This is the response we get from the push registartion in APNS.
- Parameter WithUserId: This is the userId value.
- Parameter completionHandler: The closure that will be called when this request finishes. The response will contain response (String), StatusCode (Int) and error (string).
*/
public func registerWithDeviceToken(deviceToken:NSData , WithUserId:String?, completionHandler: (response:String?, statusCode:Int?, error:String) -> Void) {
if (isInitialized){
if (validateString(WithUserId!)){
let devId = self.getDeviceID()
BMSPushUtils.saveValueToNSUserDefaults(devId, key: "deviceId")
self.applicationId = BMSPushUtils.getValueToNSUserDefaults(BMSPUSH_APP_GUID)
self.clientSecret = BMSPushUtils.getValueToNSUserDefaults(BMSPUSH_CLIENT_SECRET)
if (self.applicationId == "" || self.clientSecret == "") {
self.sendAnalyticsData(LogLevel.error, logStringData: "Error during device registration - Error is: push is not initialized")
completionHandler(response: "", statusCode: IMFPushErrorvalues.IMFPushRegistrationError.rawValue, error: "Error during device registration - Error is: push is not initialized")
}
var token:String = deviceToken.description
token = token.stringByReplacingOccurrencesOfString("<", withString: "")
token = token.stringByReplacingOccurrencesOfString(">", withString: "")
token = token.stringByReplacingOccurrencesOfString(" ", withString: "").stringByTrimmingCharactersInSet(NSCharacterSet.symbolCharacterSet())
let urlBuilder = BMSPushUrlBuilder(applicationID: self.applicationId!, clientSecret: self.clientSecret!)
let resourceURL:String = urlBuilder.getSubscribedDevicesUrl(devId)
let headers = urlBuilder.addHeader()
let method = HttpMethod.GET
self.sendAnalyticsData(LogLevel.debug, logStringData: "Verifying previous device registration.")
let getRequest = Request(url: resourceURL, headers: headers, queryParameters: nil, method: method, timeout: 60)
// MARK: FIrst Action, checking for previuos registration
getRequest.send(completionHandler: { (response, error) -> Void in
if response?.statusCode != nil {
let status = response?.statusCode ?? 0
let responseText = response?.responseText ?? ""
if (status == 404) {
self.sendAnalyticsData(LogLevel.debug, logStringData: "Device is not registered before. Registering for the first time.")
let resourceURL:String = urlBuilder.getDevicesUrl()
let headers = urlBuilder.addHeader()
let method = HttpMethod.POST
let getRequest = Request(url: resourceURL, method: method, headers: headers, queryParameters: nil, timeout: 60, cachePolicy: .UseProtocolCachePolicy)
let data = "{\"\(IMFPUSH_DEVICE_ID)\": \"\(devId)\", \"\(IMFPUSH_TOKEN)\": \"\(token)\", \"\(IMFPUSH_PLATFORM)\": \"A\", \"\(IMFPUSH_USERID)\": \"\(WithUserId!)\"}".dataUsingEncoding(NSUTF8StringEncoding)
// MARK: Registering for the First Time
getRequest.send(requestBody: data!, completionHandler: { (response, error) -> Void in
if response?.statusCode != nil {
let status = response?.statusCode ?? 0
if (status == 201){
let responseText = response?.responseText ?? ""
self.sendAnalyticsData(LogLevel.info, logStringData: "Response of device registration - Response is: \(responseText)")
completionHandler(response: responseText, statusCode: status, error: "")
}else{
self.sendAnalyticsData(LogLevel.error, logStringData: "Error during device registration - Error code is: \(status) and error is: \(response?.responseText)")
completionHandler(response: "", statusCode: IMFPushErrorvalues.IMFPushRegistrationError.rawValue, error: "Error during device registration - Error code is: \(status) and error is: \(response?.responseText)")
}
}
else if let responseError = error {
self.sendAnalyticsData(LogLevel.error, logStringData: "Error during device registration - Error is: \(responseError.localizedDescription)")
completionHandler(response: "", statusCode: IMFPushErrorvalues.IMFPushRegistrationError.rawValue, error: "Error during device registration - Error is: \(responseError.localizedDescription)")
}
})
}else if (status == 200) {
// MARK: device is already Registered
self.sendAnalyticsData(LogLevel.debug, logStringData: "Device is already registered. Return the device Id - Response is: \(response?.responseText)")
let respJson = response?.responseText
let data = respJson!.dataUsingEncoding(NSUTF8StringEncoding)
let jsonResponse:NSDictionary = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary
let rToken = jsonResponse.objectForKey(IMFPUSH_TOKEN) as! String
let rDevId = jsonResponse.objectForKey(IMFPUSH_DEVICE_ID) as! String
let userId = jsonResponse.objectForKey(IMFPUSH_USERID) as! String
if ((rToken.compare(token)) != NSComparisonResult.OrderedSame) ||
(!(WithUserId!.isEmpty) && (WithUserId!.compare(userId) != NSComparisonResult.OrderedSame)) || (devId.compare(rDevId) != NSComparisonResult.OrderedSame){
// MARK: Updating the registered device ,userID, token or deviceId changed
self.sendAnalyticsData(LogLevel.debug, logStringData: "Device token or DeviceId has changed. Sending update registration request.")
let resourceURL:String = urlBuilder.getSubscribedDevicesUrl(devId)
let headers = urlBuilder.addHeader()
let method = HttpMethod.PUT
let getRequest = Request(url: resourceURL, method: method, headers: headers, queryParameters: nil, timeout: 60, cachePolicy: .UseProtocolCachePolicy)
let data = "{\"\(IMFPUSH_DEVICE_ID)\": \"\(devId)\", \"\(IMFPUSH_TOKEN)\": \"\(token)\", \"\(IMFPUSH_USERID)\": \"\(WithUserId!)\"}".dataUsingEncoding(NSUTF8StringEncoding)
getRequest.send(requestBody: data!, completionHandler: { (response, error) -> Void in
if response?.statusCode != nil {
let status = response?.statusCode ?? 0
if (status == 200){
let responseText = response?.responseText ?? ""
self.sendAnalyticsData(LogLevel.info, logStringData: "Response of device updation - Response is: \(responseText)")
completionHandler(response: responseText, statusCode: status, error: "")
}else{
self.sendAnalyticsData(LogLevel.error, logStringData: "Error during device updatation - Error code is: \(status) and error is: \(response?.responseText)")
completionHandler(response: "", statusCode: IMFPushErrorvalues.IMFPushRegistrationUpdateError.rawValue, error: "Error during device updatation - Error code is: \(status) and error is: \(response?.responseText)")
}
}
else if let responseError = error {
self.sendAnalyticsData(LogLevel.error, logStringData: "Error during device updatation - Error is : \(responseError.description)")
completionHandler(response: "", statusCode: IMFPushErrorvalues.IMFPushRegistrationUpdateError.rawValue, error: "Error during device updatation - Error is : \(responseError.description)")
}
})
}
else {
// MARK: device already registered and parameteres not changed.
self.sendAnalyticsData(LogLevel.info, logStringData: "Device is already registered and device registration parameters not changed.")
completionHandler(response: response?.responseText, statusCode: status, error: "")
}
}else{
self.sendAnalyticsData(LogLevel.error, logStringData: "Error while verifying previous registration - Error is: \(error!.localizedDescription)")
completionHandler(response: "", statusCode: status, error: responseText)
}
}
else if let responseError = error {
self.sendAnalyticsData(LogLevel.error, logStringData: "Error while verifying previous registration - Error is: \(responseError.localizedDescription)")
completionHandler(response: "", statusCode: IMFPushErrorvalues.IMFPushRegistrationVerificationError.rawValue , error: "Error while verifying previous registration - Error is: \(responseError.localizedDescription)")
}
})
}else{
self.sendAnalyticsData(LogLevel.error, logStringData: "Error while registration - Provide a valid userId value")
completionHandler(response: "", statusCode: IMFPushErrorvalues.IMFPushRegistrationError.rawValue , error: "Error while registration - Provide a valid userId value")
}
}else{
self.sendAnalyticsData(LogLevel.error, logStringData: "Error while registration - BMSPush is not initialized")
completionHandler(response: "", statusCode: IMFPushErrorvalues.IMFPushRegistrationError.rawValue , error: "Error while registration - BMSPush is not initialized")
}
}
/**
This Methode used to register the client device to the Bluemix Push service. This is the normal registration, without userId.
Call this methode after successfully registering for remote push notification in the Apple Push
Notification Service .
- Parameter deviceToken: This is the response we get from the push registartion in APNS.
- Parameter completionHandler: The closure that will be called when this request finishes. The response will contain response (String), StatusCode (Int) and error (string).
*/
public func registerWithDeviceToken (deviceToken:NSData, completionHandler: (response:String?, statusCode:Int?, error:String) -> Void) {
if (isInitialized){
let devId = self.getDeviceID()
BMSPushUtils.saveValueToNSUserDefaults(devId, key: "deviceId")
self.applicationId = BMSPushUtils.getValueToNSUserDefaults(BMSPUSH_APP_GUID)
self.clientSecret = BMSPushUtils.getValueToNSUserDefaults(BMSPUSH_CLIENT_SECRET)
if (self.applicationId == "" || self.clientSecret == "") {
self.sendAnalyticsData(LogLevel.error, logStringData: "Error during device registration - Error is: push is not initialized")
completionHandler(response: "", statusCode: IMFPushErrorvalues.IMFPushRegistrationError.rawValue, error: "Error during device registration - Error is: push is not initialized")
}
var token:String = deviceToken.description
token = token.stringByReplacingOccurrencesOfString("<", withString: "")
token = token.stringByReplacingOccurrencesOfString(">", withString: "")
token = token.stringByReplacingOccurrencesOfString(" ", withString: "").stringByTrimmingCharactersInSet(NSCharacterSet.symbolCharacterSet())
let urlBuilder = BMSPushUrlBuilder(applicationID: self.applicationId!, clientSecret: self.clientSecret!)
let resourceURL:String = urlBuilder.getSubscribedDevicesUrl(devId)
let headers = urlBuilder.addHeader()
let method = HttpMethod.GET
self.sendAnalyticsData(LogLevel.debug, logStringData: "Verifying previous device registration.")
let getRequest = Request(url: resourceURL, headers: headers, queryParameters: nil, method: method, timeout: 60)
// MARK: FIrst Action, checking for previuos registration
getRequest.send(completionHandler: { (response, error) -> Void in
if response?.statusCode != nil {
let status = response?.statusCode ?? 0
let responseText = response?.responseText ?? ""
if (status == 404) {
self.sendAnalyticsData(LogLevel.debug, logStringData: "Device is not registered before. Registering for the first time.")
let resourceURL:String = urlBuilder.getDevicesUrl()
let headers = urlBuilder.addHeader()
let method = HttpMethod.POST
let getRequest = Request(url: resourceURL, method: method, headers: headers, queryParameters: nil, timeout: 60, cachePolicy: .UseProtocolCachePolicy)
let data = "{\"\(IMFPUSH_DEVICE_ID)\": \"\(devId)\", \"\(IMFPUSH_TOKEN)\": \"\(token)\", \"\(IMFPUSH_PLATFORM)\": \"A\"}".dataUsingEncoding(NSUTF8StringEncoding)
// MARK: Registering for the First Time
getRequest.send(requestBody: data!, completionHandler: { (response, error) -> Void in
if response?.statusCode != nil {
let status = response?.statusCode ?? 0
if (status == 201){
let responseText = response?.responseText ?? ""
self.sendAnalyticsData(LogLevel.info, logStringData: "Response of device registration - Response is: \(responseText)")
completionHandler(response: responseText, statusCode: status, error: "")
}else{
self.sendAnalyticsData(LogLevel.error, logStringData: "Error during device registration - Error code is: \(status) and error is: \(response?.responseText)")
completionHandler(response: "", statusCode: IMFPushErrorvalues.IMFPushRegistrationError.rawValue, error: "Error during device registration - Error code is: \(status) and error is: \(response?.responseText)")
}
}
else if let responseError = error {
self.sendAnalyticsData(LogLevel.error, logStringData: "Error during device registration - Error is: \(responseError.localizedDescription)")
completionHandler(response: "", statusCode: IMFPushErrorvalues.IMFPushRegistrationError.rawValue, error: "Error during device registration - Error is: \(responseError.localizedDescription)")
}
})
}else if (status == 200){
// MARK: device is already Registered
self.sendAnalyticsData(LogLevel.debug, logStringData: "Device is already registered. Return the device Id - Response is: \(response?.responseText)")
let respJson = response?.responseText
let data = respJson!.dataUsingEncoding(NSUTF8StringEncoding)
let jsonResponse:NSDictionary = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary
let rToken = jsonResponse.objectForKey(IMFPUSH_TOKEN) as! String
let rDevId = jsonResponse.objectForKey(IMFPUSH_DEVICE_ID) as! String
let userId = jsonResponse.objectForKey(IMFPUSH_USERID) as! String
if ((rToken.compare(token)) != NSComparisonResult.OrderedSame) || (devId.compare(rDevId) != NSComparisonResult.OrderedSame) || (userId != "anonymous") {
// MARK: Updating the registered userID , token or deviceId changed
self.sendAnalyticsData(LogLevel.debug, logStringData: "Device token or DeviceId has changed. Sending update registration request.")
let resourceURL:String = urlBuilder.getSubscribedDevicesUrl(devId)
let headers = urlBuilder.addHeader()
let method = HttpMethod.PUT
let getRequest = Request(url: resourceURL, method: method, headers: headers, queryParameters: nil, timeout: 60, cachePolicy: .UseProtocolCachePolicy)
let data = "{\"\(IMFPUSH_DEVICE_ID)\": \"\(devId)\", \"\(IMFPUSH_TOKEN)\": \"\(token)\"}".dataUsingEncoding(NSUTF8StringEncoding)
getRequest.send(requestBody: data!, completionHandler: { (response, error) -> Void in
if response?.statusCode != nil {
let status = response?.statusCode ?? 0
if (status == 200){
let responseText = response?.responseText ?? ""
self.sendAnalyticsData(LogLevel.info, logStringData: "Response of device updation - Response is: \(responseText)")
completionHandler(response: responseText, statusCode: status, error: "")
}else{
self.sendAnalyticsData(LogLevel.error, logStringData: "Error during device updatation - Error code is: \(status) and error is: \(response?.responseText)")
completionHandler(response: "", statusCode: IMFPushErrorvalues.IMFPushRegistrationUpdateError.rawValue, error: "Error during device updatation - Error code is: \(status) and error is: \(response?.responseText)")
}
}
else if let responseError = error {
self.sendAnalyticsData(LogLevel.error, logStringData: "Error during device updatation - Error is : \(responseError.description)")
completionHandler(response: "", statusCode: IMFPushErrorvalues.IMFPushRegistrationUpdateError.rawValue, error: "Error during device updatation - Error is : \(responseError.description)")
}
})
}
else {
// MARK: device already registered and parameteres not changed.
self.sendAnalyticsData(LogLevel.info, logStringData: "Device is already registered and device registration parameters not changed.")
completionHandler(response: response?.responseText, statusCode: status, error: "")
}
}else{
self.sendAnalyticsData(LogLevel.error, logStringData: "Error while verifying previous registration - Error is: \(error!.localizedDescription)")
completionHandler(response:"" , statusCode: status, error: responseText)
}
}
else if let responseError = error {
self.sendAnalyticsData(LogLevel.error, logStringData: "Error while verifying previous registration - Error is: \(responseError.localizedDescription)")
completionHandler(response: "", statusCode: IMFPushErrorvalues.IMFPushRegistrationVerificationError.rawValue , error: "Error while verifying previous registration - Error is: \(responseError.localizedDescription)")
}
})
}else{
self.sendAnalyticsData(LogLevel.error, logStringData: "Error while registration - BMSPush is not initialized")
completionHandler(response: "", statusCode: IMFPushErrorvalues.IMFPushRegistrationError.rawValue , error: "Error while registration - BMSPush is not initialized")
}
}
/**
This Method used to Retrieve all the available Tags in the Bluemix Push Service.
This methode will return the list of available Tags in an Array.
- Parameter completionHandler: The closure that will be called when this request finishes. The response will contain response (NSMutableArray), StatusCode (Int) and error (string).
*/
public func retrieveAvailableTagsWithCompletionHandler (completionHandler: (response:NSMutableArray?, statusCode:Int?, error:String) -> Void){
self.sendAnalyticsData(LogLevel.debug, logStringData: "Entering retrieveAvailableTagsWithCompletitionHandler.")
self.applicationId = BMSPushUtils.getValueToNSUserDefaults(BMSPUSH_APP_GUID)
self.clientSecret = BMSPushUtils.getValueToNSUserDefaults(BMSPUSH_CLIENT_SECRET)
if (self.applicationId == "" || self.clientSecret == "") {
self.sendAnalyticsData(LogLevel.error, logStringData: "Error while retrieving available tags - Error is: push is not initialized")
completionHandler(response:[], statusCode: IMFPushErrorvalues.IMFPushRetrieveTagsError.rawValue, error: "Error while retrieving available tags - Error is: push is not initialized")
}
let urlBuilder = BMSPushUrlBuilder(applicationID: self.applicationId!, clientSecret: self.clientSecret!)
let resourceURL:String = urlBuilder.getTagsUrl()
let headers = urlBuilder.addHeader()
let method = HttpMethod.GET
let getRequest = Request(url: resourceURL, headers: headers, queryParameters: nil, method: method, timeout: 60)
getRequest.send(completionHandler: { (response, error) -> Void in
if response?.statusCode != nil {
let status = response?.statusCode ?? 0
if (status == 200){
let responseText = response?.responseText ?? ""
self.sendAnalyticsData(LogLevel.info, logStringData: "Successfully retrieved available tags - Response is: \(responseText)")
let availableTagsArray = response?.availableTags()
completionHandler(response: availableTagsArray, statusCode: status, error: "")
}else{
self.sendAnalyticsData(LogLevel.error, logStringData: "Error while retrieving available tags - Error code is: \(status) and error is: \(response?.responseText)")
completionHandler(response: [], statusCode: IMFPushErrorvalues.IMFPushRetrieveTagsError.rawValue,error: "Error while retrieving available tags - Error code is: \(status) and error is: \(response?.responseText)")
}
} else if let responseError = error {
self.sendAnalyticsData(LogLevel.error, logStringData: "Error while retrieving available tags - Error is: \(responseError.description)")
completionHandler(response: [], statusCode: IMFPushErrorvalues.IMFPushRetrieveTagsError.rawValue,error: "Error while retrieving available tags - Error is: \(responseError.description)")
}
})
}
/**
This Methode used to Subscribe to the Tags in the Bluemix Push srvice.
This methode will return the list of subscribed tags. If you pass the tags that are not present in the Bluemix App it will be classified under the TAGS NOT FOUND section in the response.
- parameter tagsArray: the array that contains name tags.
- Parameter completionHandler: The closure that will be called when this request finishes. The response will contain response (NSMutableDictionary), StatusCode (Int) and error (string).
*/
public func subscribeToTags (tagsArray:NSArray, completionHandler: (response:NSMutableDictionary?, statusCode:Int?, error:String) -> Void) {
self.sendAnalyticsData(LogLevel.debug, logStringData:"Entering: subscribeToTags." )
if tagsArray.count != 0 {
let devId = self.getDeviceID()
self.applicationId = BMSPushUtils.getValueToNSUserDefaults(BMSPUSH_APP_GUID)
self.clientSecret = BMSPushUtils.getValueToNSUserDefaults(BMSPUSH_CLIENT_SECRET)
if (self.applicationId == "" || self.clientSecret == "") {
self.sendAnalyticsData(LogLevel.error, logStringData: "Error while subscribing to tags - Error is: push is not initialized")
completionHandler(response:[:], statusCode: IMFPushErrorvalues.IMFPushErrorEmptyTagArray.rawValue, error: "Error while subscribing to tags - Error is: push is not initialized")
}
let urlBuilder = BMSPushUrlBuilder(applicationID: self.applicationId!, clientSecret: self.clientSecret!)
let resourceURL:String = urlBuilder.getSubscriptionsUrl()
let headers = urlBuilder.addHeader()
let method = HttpMethod.POST
let getRequest = Request(url: resourceURL, method: method, headers: headers, queryParameters: nil, timeout: 60, cachePolicy: .UseProtocolCachePolicy)
let mappedArray = tagsArray.flatMap{"\($0)"}.description;
let data = "{\"\(IMFPUSH_TAGNAMES)\":\(mappedArray), \"\(IMFPUSH_DEVICE_ID)\":\"\(devId)\"}".dataUsingEncoding(NSUTF8StringEncoding)
getRequest.send(requestBody: data!, completionHandler: { (response, error) -> Void in
if response?.statusCode != nil {
let status = response?.statusCode ?? 0
if (status == 207){
let responseText = response?.responseText ?? ""
self.sendAnalyticsData(LogLevel.info, logStringData: "Successfully subscribed to tags - Response is: \(responseText)")
let subscriptionResponse = response?.subscribeStatus()
completionHandler(response: subscriptionResponse, statusCode: status, error: "")
}else{
self.sendAnalyticsData(LogLevel.error, logStringData: "Error while subscribing to tags - Error code is: \(status) and error is: \(response?.responseText)")
completionHandler(response: [:], statusCode: IMFPushErrorvalues.IMFPushTagSubscriptionError.rawValue,error: "Error while subscribing to tags - Error code is: \(status) and error is: \(response?.responseText)")
}
} else if let responseError = error {
self.sendAnalyticsData(LogLevel.error, logStringData: "Error while subscribing to tags - Error is: \(responseError.description)")
completionHandler(response: [:], statusCode: IMFPushErrorvalues.IMFPushTagSubscriptionError.rawValue,error: "Error while subscribing to tags - Error is: \(responseError.description)")
}
})
} else {
let subscriptionResponse = NSMutableDictionary()
self.sendAnalyticsData(LogLevel.error, logStringData: "Error. Tag array cannot be null. Create tags in your Bluemix App")
completionHandler(response: subscriptionResponse, statusCode: IMFPushErrorvalues.IMFPushErrorEmptyTagArray.rawValue, error: "Error. Tag array cannot be null. Create tags in your Bluemix App")
}
}
/**
This Methode used to Retrieve the Subscribed Tags in the Bluemix Push srvice.
This methode will return the list of subscribed tags.
- Parameter completionHandler: The closure that will be called when this request finishes. The response will contain response (NSMutableArray), StatusCode (Int) and error (string).
*/
public func retrieveSubscriptionsWithCompletionHandler (completionHandler: (response:NSMutableArray?, statusCode:Int?, error:String) -> Void) {
self.sendAnalyticsData(LogLevel.debug, logStringData: "Entering retrieveSubscriptionsWithCompletitionHandler.")
let devId = self.getDeviceID()
self.applicationId = BMSPushUtils.getValueToNSUserDefaults(BMSPUSH_APP_GUID)
self.clientSecret = BMSPushUtils.getValueToNSUserDefaults(BMSPUSH_CLIENT_SECRET)
if (self.applicationId == "" || self.clientSecret == "") {
self.sendAnalyticsData(LogLevel.error, logStringData: "Error while retrieving subscriptions - Error is: push is not initialized")
completionHandler(response:[], statusCode: IMFPushErrorvalues.IMFPushRetrieveSubscriptionError.rawValue, error: "Error while retrieving subscriptions - Error is: push is not initialized")
}
let urlBuilder = BMSPushUrlBuilder(applicationID: self.applicationId!, clientSecret: self.clientSecret!)
let resourceURL:String = urlBuilder.getAvailableSubscriptionsUrl(devId)
let headers = urlBuilder.addHeader()
let method = HttpMethod.GET
let getRequest = Request(url: resourceURL, headers: headers, queryParameters: nil, method: method, timeout: 60)
getRequest.send(completionHandler: { (response, error) -> Void in
if response?.statusCode != nil {
let status = response?.statusCode ?? 0
if (status == 200){
let responseText = response?.responseText ?? ""
self.sendAnalyticsData(LogLevel.info, logStringData: "Subscription retrieved successfully - Response is: \(responseText)")
let subscriptionArray = response?.subscriptions()
completionHandler(response: subscriptionArray, statusCode: status, error: "")
}else {
self.sendAnalyticsData(LogLevel.error, logStringData: "Error while retrieving subscriptions - Error codeis: \(status) and error is: \(response?.responseText)")
completionHandler(response: [], statusCode: IMFPushErrorvalues.IMFPushRetrieveSubscriptionError.rawValue,error: "Error while retrieving subscriptions - Error codeis: \(status) and error is: \(response?.responseText)")
}
} else if let responseError = error {
self.sendAnalyticsData(LogLevel.error, logStringData: "Error while retrieving subscriptions - Error is: \(responseError.localizedDescription)")
completionHandler(response: [], statusCode: IMFPushErrorvalues.IMFPushRetrieveSubscriptionError.rawValue,error: "Error while retrieving subscriptions - Error is: \(responseError.localizedDescription)")
}
})
}
/**
This Methode used to Unsubscribe from the Subscribed Tags in the Bluemix Push srvice.
This methode will return the details of Unsubscription status.
- Parameter tagsArray: The list of tags that need to be unsubscribed.
- Parameter completionHandler: The closure that will be called when this request finishes. The response will contain response (NSMutableDictionary), StatusCode (Int) and error (string).
*/
public func unsubscribeFromTags (tagsArray:NSArray, completionHandler: (response:NSMutableDictionary?, statusCode:Int?, error:String) -> Void) {
self.sendAnalyticsData(LogLevel.debug, logStringData: "Entering: unsubscribeFromTags")
if tagsArray.count != 0 {
let devId = self.getDeviceID()
self.applicationId = BMSPushUtils.getValueToNSUserDefaults(BMSPUSH_APP_GUID)
self.clientSecret = BMSPushUtils.getValueToNSUserDefaults(BMSPUSH_CLIENT_SECRET)
if (self.applicationId == "" || self.clientSecret == "") {
self.sendAnalyticsData(LogLevel.error, logStringData: "Error while unsubscribing from tags - Error is: push is not initialized")
completionHandler(response:[:], statusCode: IMFPushErrorvalues.IMFPushTagUnsubscriptionError.rawValue, error: "Error while unsubscribing from tags - Error is: push is not initialized")
}
let urlBuilder = BMSPushUrlBuilder(applicationID: self.applicationId!, clientSecret: self.clientSecret!)
let resourceURL:String = urlBuilder.getUnSubscribetagsUrl()
let headers = urlBuilder.addHeader()
let method = HttpMethod.POST
let getRequest = Request(url: resourceURL, method: method, headers: headers, queryParameters: nil, timeout: 60, cachePolicy: .UseProtocolCachePolicy)
let data1 = tagsArray.flatMap{"\($0)"}.description;
let data = "{\"\(IMFPUSH_TAGNAMES)\":\(data1), \"\(IMFPUSH_DEVICE_ID)\":\"\(devId)\"}".dataUsingEncoding(NSUTF8StringEncoding)
getRequest.send(requestBody: data, completionHandler: { (response, error) -> Void in
if response?.statusCode != nil {
let status = response?.statusCode ?? 0
let responseText = response?.responseText ?? ""
self.sendAnalyticsData(LogLevel.info, logStringData: "Successfully unsubscribed from tags - Response is: \(responseText)")
let unSubscriptionResponse = response?.unsubscribeStatus()
completionHandler(response: unSubscriptionResponse, statusCode: status, error: "")
} else if let responseError = error{
let unSubscriptionResponse = NSMutableDictionary()
self.sendAnalyticsData(LogLevel.error, logStringData: "Error while unsubscribing from tags - Error is: \(responseError.description)")
completionHandler(response: unSubscriptionResponse, statusCode: IMFPushErrorvalues.IMFPushTagUnsubscriptionError.rawValue,error: "Error while unsubscribing from tags - Error is: \(responseError.description)")
}
})
} else {
let unSubscriptionResponse = NSMutableDictionary()
self.sendAnalyticsData(LogLevel.error, logStringData: "Error. Tag array cannot be null.")
completionHandler(response: unSubscriptionResponse, statusCode: IMFPushErrorvalues.IMFPushErrorEmptyTagArray.rawValue, error: "Error. Tag array cannot be null.")
}
}
/**
This Methode used to UnRegister the client App from the Bluemix Push srvice.
- Parameter completionHandler: The closure that will be called when this request finishes. The response will contain response (String), StatusCode (Int) and error (string).
*/
public func unregisterDevice (completionHandler: (response:String?, statusCode:Int?, error:String) -> Void) {
self.sendAnalyticsData(LogLevel.debug, logStringData: "Entering unregisterDevice.")
let devId = self.getDeviceID()
self.applicationId = BMSPushUtils.getValueToNSUserDefaults(BMSPUSH_APP_GUID)
self.clientSecret = BMSPushUtils.getValueToNSUserDefaults(BMSPUSH_CLIENT_SECRET)
if (self.applicationId == "" || self.clientSecret == "") {
self.sendAnalyticsData(LogLevel.error, logStringData: "Error while unregistering device - Error is: push is not initialized")
completionHandler(response:"", statusCode: IMFPushErrorvalues.BMSPushUnregitrationError.rawValue, error: "Error while unregistering device - Error is: push is not initialized")
}
let urlBuilder = BMSPushUrlBuilder(applicationID: self.applicationId!, clientSecret: self.clientSecret!)
let resourceURL:String = urlBuilder.getUnregisterUrl(devId)
let headers = urlBuilder.addHeader()
let method = HttpMethod.DELETE
let getRequest = Request(url: resourceURL, headers: headers, queryParameters: nil, method: method, timeout: 60)
getRequest.send(completionHandler: { (response, error) -> Void in
if response?.statusCode != nil {
let status = response?.statusCode ?? 0
if (status == 204){
let responseText = response?.responseText ?? ""
self.sendAnalyticsData(LogLevel.info, logStringData: "Successfully unregistered the device. - Response is: \(response?.responseText)")
completionHandler(response: responseText, statusCode: status, error: "")
}else{
self.sendAnalyticsData(LogLevel.error, logStringData: "Error while unregistering device - Error code is: \(status) and error is: \(response?.responseText)")
completionHandler(response:"", statusCode: IMFPushErrorvalues.BMSPushUnregitrationError.rawValue,error: "Error while unregistering device - Error code is: \(status) and error is: \(response?.responseText)")
}
} else if let responseError = error {
self.sendAnalyticsData(LogLevel.error, logStringData: "Error while unregistering device - Error is: \(responseError.description)")
completionHandler(response:"", statusCode: IMFPushErrorvalues.BMSPushUnregitrationError.rawValue,error: "Error while unregistering device - Error is: \(responseError.description)")
}
})
}
public func sendMessageDeliveryStatus (messageId:String, completionHandler: (response:String?, statusCode:Int?, error:String) -> Void) {
self.sendAnalyticsData(LogLevel.debug, logStringData: "Entering sendMessageDeliveryStatus.")
let devId = self.getDeviceID()
self.applicationId = BMSPushUtils.getValueToNSUserDefaults(BMSPUSH_APP_GUID)
self.clientSecret = BMSPushUtils.getValueToNSUserDefaults(BMSPUSH_CLIENT_SECRET)
if (self.applicationId == "" || self.clientSecret == "") {
self.sendAnalyticsData(LogLevel.error, logStringData: "Failed to update the message status - Error is: push is not initialized")
completionHandler(response:"", statusCode: 502, error: "Failed to update the message status - Error is: push is not initialized")
}
let urlBuilder = BMSPushUrlBuilder(applicationID: self.applicationId!,clientSecret:self.clientSecret!)
let resourceURL:String = urlBuilder.getSendMessageDeliveryStatus(messageId)
let headers = urlBuilder.addHeader()
let method = HttpMethod.PUT
var status = "";
if ( UIApplication.sharedApplication().applicationState == UIApplicationState.Background){
status = "SEEN";
} else{
status = "OPEN"
}
if !(status.isEmpty){
let json = [
IMFPUSH_DEVICE_ID:devId,
IMFPUSH_STATUS:status
]
let data = try? NSJSONSerialization.dataWithJSONObject(json, options: [])
let getRequest = Request(url: resourceURL, method: method, headers: headers, queryParameters: nil, timeout: 60)
getRequest.send(requestBody: data!, completionHandler: { (response, error) -> Void in
if response?.statusCode != nil {
let responseText = response?.responseText ?? ""
let status = response?.statusCode ?? 0
self.sendAnalyticsData(LogLevel.info, logStringData: "Successfully updated the message status. The response is: \(responseText)")
print("Successfully updated the message status. The response is: "+responseText)
completionHandler(response: responseText, statusCode: status, error: "")
} else if let responseError = error{
let status = response?.statusCode ?? 0
self.sendAnalyticsData(LogLevel.error, logStringData: "Failed to update the message status. The response is: \(responseError.localizedDescription)")
print("Failed to update the message status. The response is: "+responseError.localizedDescription)
completionHandler(response: "", statusCode: status, error: responseError.localizedDescription)
}
})
}else{
self.sendAnalyticsData(LogLevel.error, logStringData: "Failed to update the message status. The response is: Status should be either SEEN or OPEN")
print("Failed to update the message status. The response is: Status should be either SEEN or OPEN")
}
}
// MARK: Methods (Internal)
//Begin Logger implementation
// Setting Log info
internal func sendAnalyticsData (logType:LogLevel, logStringData:String){
let devId = self.getDeviceID()
let testLogger = Logger.logger(name:devId)
if (logType == LogLevel.debug){
Logger.logLevelFilter = LogLevel.debug
testLogger.debug(message: logStringData)
} else if (logType == LogLevel.error){
Logger.logLevelFilter = LogLevel.error
testLogger.error(message: logStringData)
} else if (logType == LogLevel.analytics){
Logger.logLevelFilter = LogLevel.analytics
testLogger.debug(message: logStringData)
} else if (logType == LogLevel.fatal){
Logger.logLevelFilter = LogLevel.fatal
testLogger.fatal(message: logStringData)
} else if (logType == LogLevel.warn){
Logger.logLevelFilter = LogLevel.warn
testLogger.warn(message: logStringData)
} else if (logType == LogLevel.warn){
Logger.logLevelFilter = LogLevel.warn
testLogger.info(message: logStringData)
}
else {
Logger.logLevelFilter = LogLevel.none
testLogger.debug(message: logStringData)
}
}
internal func validateString(object:String) -> Bool{
if (object.isEmpty || object == "") {
return false;
}
return true
}
internal func getDeviceID() -> String{
var devId = String()
if ((self.bluemixDeviceId == nil) || (self.bluemixDeviceId?.isEmpty)!) {
// Generate new ID
let authManager = BMSClient.sharedInstance.authorizationManager
devId = authManager.deviceIdentity.ID!
}else{
devId = self.bluemixDeviceId!
}
return devId
}
internal func checkStatusChange(){
if(NSUserDefaults.standardUserDefaults().objectForKey(BMSPUSH_APP_INSTALL) != nil) {
let notificationType = UIApplication.sharedApplication().currentUserNotificationSettings()?.types
if notificationType?.rawValue == 0 {
print("Disabled")
self.delegate?.onChangePermission(false)
} else {
print("Enabled")
self.delegate?.onChangePermission( true)
UIApplication.sharedApplication().registerForRemoteNotifications()
}
} else {
NSUserDefaults.standardUserDefaults().setBool(true, forKey: BMSPUSH_APP_INSTALL)
NSUserDefaults.standardUserDefaults().synchronize()
NSNotificationCenter.defaultCenter().addObserverForName(UIApplicationDidBecomeActiveNotification, object: nil, queue: NSOperationQueue.mainQueue(), usingBlock: { (notification) in
sleep(1)
let notificationType = UIApplication.sharedApplication().currentUserNotificationSettings()?.types
if notificationType?.rawValue == 0 {
print("Disabled")
self.delegate?.onChangePermission(false)
} else {
print("Enabled")
self.delegate?.onChangePermission( true)
UIApplication.sharedApplication().registerForRemoteNotifications()
}
})
}
}
}
#endif
| 491b4971b2a8b0832df74a5c7bbc3962 | 55.455465 | 255 | 0.580762 | false | false | false | false |
pennlabs/penn-mobile-ios | refs/heads/main | PennMobile/Home/Cells/Polls/HomePollsCellFooter.swift | mit | 1 | //
// HomePollsCellFooter.swift
// PennMobile
//
// Created by Lucy Yuewei Yuan on 10/18/20.
// Copyright © 2020 PennLabs. All rights reserved.
//
import UIKit
import SnapKit
class HomePollsCellFooter: UIView {
static let height: CGFloat = 16
var noteLabel: UILabel!
private var dividerLine: UIView!
//
// Must be called after being added to a view
func prepare() {
prepareFooter(inside: self.superview ?? UIView())
prepareNoteLabel()
prepareDividerLine()
}
// MARK: Footer
private func prepareFooter(inside safeArea: UIView) {
self.snp.makeConstraints { (make) in
make.leading.equalTo(safeArea)
make.bottom.equalTo(safeArea)
make.trailing.equalTo(safeArea)
make.height.equalTo(HomePollsCellFooter.height)
}
}
// MARK: Labels
private func prepareNoteLabel() {
noteLabel = getNoteLabel()
addSubview(noteLabel)
noteLabel.snp.makeConstraints { (make) in
make.leading.equalTo(self)
make.bottom.equalTo(self).offset(3)
make.trailing.equalTo(self)
}
}
// MARK: Divider Line
private func prepareDividerLine() {
dividerLine = getDividerLine()
addSubview(dividerLine)
dividerLine.snp.makeConstraints { (make) in
make.leading.equalTo(self)
make.trailing.equalTo(self)
make.top.equalTo(self)
make.height.equalTo(2)
}
}
private func getNoteLabel() -> UILabel {
let label = UILabel()
label.font = .footerDescriptionFont
label.textColor = .labelSecondary
label.textAlignment = .left
label.text = "Penn Mobile anonymously shares info with the organization."
label.numberOfLines = 1
return label
}
private func getDividerLine() -> UIView {
let view = UIView()
view.backgroundColor = .grey5
view.layer.cornerRadius = 2.0
return view
}
}
| a951c6d0c86ac92cd19d7e7534b030e5 | 25.480519 | 81 | 0.613046 | false | false | false | false |
CompassSoftware/pocket-turchin | refs/heads/master | PocketTurchin/ArchiveViewController.swift | apache-2.0 | 1 | //
// ArchiveViewController.swift
//
import UIKit
class ArchiveViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
// MARK: Properties
@IBOutlet weak var descText: UITextField!
@IBOutlet weak var photoImageView: UIImageView!
var archive: Archive?
@IBAction func selectImageFromPhotoLibrary(sender: UITapGestureRecognizer) {
// Hide the keyboard.
//nameTextField.resignFirstResponder()
// UIImagePickerController is a view controller that lets a user pick media from their photo library.
let imagePickerController = UIImagePickerController()
// Only allow photos to be picked, not taken.
imagePickerController.sourceType = .PhotoLibrary
// Make sure ViewController is notified when the user picks an image.
imagePickerController.delegate = self
presentViewController(imagePickerController, animated: true, completion: nil)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
// Dismiss the picker if the user canceled.
dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
// The info dictionary contains multiple representations of the image, and this uses the original.
let selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage
// Set photoImageView to display the selected image.
photoImageView.image = selectedImage
// Dismiss the picker.
dismissViewControllerAnimated(true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
//
//nameTextField.delegate = self
// Set up views if editing an existing Meal.
if let archive = archive {
navigationItem.title = archive.name
descText.text = archive.desc
//nameTextField.text = archive.name
photoImageView.image = archive.photo
}
}
func textFieldDidEndEditing(textField: UITextField) {
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
| bf71d68ac0039f44cdd72461b5de5503 | 31.918919 | 133 | 0.667898 | false | false | false | false |
Speicher210/wingu-sdk-ios-demoapp | refs/heads/master | Example/Pods/KDEAudioPlayer/AudioPlayer/AudioPlayer/player/extensions/AudioPlayer+CurrentItem.swift | apache-2.0 | 2 | //
// AudioPlayer+CurrentItem.swift
// AudioPlayer
//
// Created by Kevin DELANNOY on 29/03/16.
// Copyright © 2016 Kevin Delannoy. All rights reserved.
//
import Foundation
public typealias TimeRange = (earliest: TimeInterval, latest: TimeInterval)
extension AudioPlayer {
/// The current item progression or nil if no item.
public var currentItemProgression: TimeInterval? {
return player?.currentItem?.currentTime().ap_timeIntervalValue
}
/// The current item duration or nil if no item or unknown duration.
public var currentItemDuration: TimeInterval? {
return player?.currentItem?.duration.ap_timeIntervalValue
}
/// The current seekable range.
public var currentItemSeekableRange: TimeRange? {
let range = player?.currentItem?.seekableTimeRanges.last?.timeRangeValue
if let start = range?.start.ap_timeIntervalValue, let end = range?.end.ap_timeIntervalValue {
return (start, end)
}
if let currentItemProgression = currentItemProgression {
// if there is no start and end point of seekable range
// return the current time, so no seeking possible
return (currentItemProgression, currentItemProgression)
}
// cannot seek at all, so return nil
return nil
}
/// The current loaded range.
public var currentItemLoadedRange: TimeRange? {
let range = player?.currentItem?.loadedTimeRanges.last?.timeRangeValue
if let start = range?.start.ap_timeIntervalValue, let end = range?.end.ap_timeIntervalValue {
return (start, end)
}
return nil
}
}
| fbb8ea4bf9a2602b9c8b26c82f38fec4 | 34.404255 | 101 | 0.677284 | false | false | false | false |
J-Mendes/Weather | refs/heads/master | Weather/Weather/Core Layer/Data Model/WeatherData.swift | gpl-3.0 | 1 | //
// WeatherData.swift
// Weather
//
// Created by Jorge Mendes on 04/07/17.
// Copyright © 2017 Jorge Mendes. All rights reserved.
//
import Foundation
struct WeatherData {
internal var units: Units!
internal var city: String!
internal var country: String!
internal var wind: Wind!
internal var atmosphere: Atmosphere!
internal var astronomy: Astronomy!
internal var weather: Weather!
init() {
self.units = Units()
self.city = ""
self.country = ""
self.wind = Wind()
self.atmosphere = Atmosphere()
self.astronomy = Astronomy()
self.weather = Weather()
}
init(dictionary: [String: Any]) {
self.init()
if let units: [String: Any] = dictionary["units"] as? [String: Any] {
self.units = Units(dictionary: units)
}
if let location: [String: Any] = dictionary["location"] as? [String: Any] {
if let city: String = location["city"] as? String {
self.city = city
}
if let country: String = location["country"] as? String {
self.country = country
}
}
if let wind: [String: Any] = dictionary["wind"] as? [String: Any] {
self.wind = Wind(dictionary: wind)
}
if let atmosphere: [String: Any] = dictionary["atmosphere"] as? [String: Any] {
self.atmosphere = Atmosphere(dictionary: atmosphere)
}
if let astronomy: [String: Any] = dictionary["astronomy"] as? [String: Any] {
self.astronomy = Astronomy(dictionary: astronomy)
}
if let weather: [String: Any] = dictionary["item"] as? [String: Any] {
self.weather = Weather(dictionary: weather)
}
}
}
| ca8ddd1cde1fc51d2e829adee8562cb6 | 27.738462 | 87 | 0.542291 | false | false | false | false |
strivingboy/CocoaChinaPlus | refs/heads/master | Code/CocoaChinaPlus/Application/Business/CocoaChina/BBS/CCPBBSViewController.swift | mit | 1 | //
// CCPBBSViewController.swift
// CocoaChinaPlus
//
// Created by zixun on 15/8/12.
// Copyright © 2015年 zixun. All rights reserved.
//
import UIKit
import Alamofire
import SDWebImage
import MBProgressHUD
import ZXKit
class CCPBBSViewController: ZXBaseViewController {
var tableView:UITableView = UITableView()
var dataSource:CCPBBSModel = CCPBBSModel(options: [CCPBBSOptionModel]())
required init(navigatorURL URL: NSURL, query: Dictionary<String, String>) {
super.init(navigatorURL: URL, query: query)
self.setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setup()
}
private func setup() {
self.tableView.backgroundColor = ZXColor(0x000000, alpha: 0.8)
self.tableView.delegate = self
self.tableView.dataSource = self
self.tableView.separatorStyle = .None
self.view.addSubview(self.tableView)
weak var weakSelf = self
self.tableView.addPullToRefreshWithActionHandler({ () -> Void in
if let weakSelf = weakSelf {
weakSelf._reloadTableView()
}
})
}
override func viewDidLoad() {
super.viewDidLoad()
self._reloadTableView()
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
self.tableView.fillSuperview()
}
private func _reloadTableView() {
MBProgressHUD.showHUDAddedTo(self.tableView, animated: true)
weak var weakSelf = self
CCPBBSParser.sharedParser.parserBBS { (model) -> Void in
if let weakSelf = weakSelf {
weakSelf.dataSource = model
weakSelf.tableView.reloadData()
weakSelf.tableView.pullToRefreshView.stopAnimating()
MBProgressHUD.hideHUDForView(weakSelf.tableView, animated: true)
}
}
}
}
extension CCPBBSViewController : UITableViewDataSource,UITableViewDelegate {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dataSource.options.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("CCPBBSTableViewCell")
if cell == nil {
cell = CCPBBSTableViewCell(style: .Default, reuseIdentifier: "CCPBBSTableViewCell")
}
let option = self.dataSource.options[indexPath.row]
(cell as! CCPBBSTableViewCell).configure(option)
return cell!
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 40
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let link = self.dataSource.options[indexPath.row].urlString
ZXOpenURL("go/ccp/edition", param: ["link": link])
}
}
class CCPBBSTableViewCell : CCPTableViewCell {
private var titleLabel:UILabel!
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.titleLabel = UILabel()
self.titleLabel.font = UIFont.systemFontOfSize(14)
self.titleLabel.textColor = UIColor.whiteColor()
self.titleLabel.textAlignment = .Left
self.titleLabel.numberOfLines = 2
self.titleLabel.lineBreakMode = .ByTruncatingTail
self.containerView.addSubview(self.titleLabel)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func layoutSubviews() {
super.layoutSubviews()
self.titleLabel.fillSuperview(left: 4, right: 0, top: 4, bottom: 0)
}
func configure(model:CCPBBSOptionModel) {
self.titleLabel.text = model.title
}
}
| 3f9e06a73426a85416fa94d695792480 | 30.703125 | 109 | 0.654017 | false | false | false | false |
borglab/SwiftFusion | refs/heads/main | Sources/SwiftFusion/Geometry/PinholeCamera.swift | apache-2.0 | 1 | import _Differentiation
/// Pinhole camera model.
public struct PinholeCamera<Calibration: CameraCalibration>: Differentiable {
/// Camera pose in the world/reference frame.
public var wTc: Pose3
/// Camera calibration.
public var calibration: Calibration
/// Initializes from camera pose and calibration.
@differentiable
public init(_ calibration: Calibration, _ wTc: Pose3) {
self.calibration = calibration
self.wTc = wTc
}
/// Initializes with identity pose.
@differentiable
public init(_ calibration: Calibration) {
self.init(calibration, Pose3())
}
/// Initializes to default.
public init() {
self.init(Calibration(), Pose3())
}
}
/// Project and backproject.
extension PinholeCamera {
/// Projects a 3D point in the world frame to 2D point in the image.
@differentiable
public func project(_ wp: Vector3) -> Vector2 {
let np: Vector2 = projectToNormalized(wp)
let ip = calibration.uncalibrate(np)
return ip
}
/// Backprojects a 2D image point into 3D point in the world frame at given depth.
@differentiable
public func backproject(_ ip: Vector2, _ depth: Double) -> Vector3 {
let np = calibration.calibrate(ip)
let cp = Vector3(np.x * depth, np.y * depth, depth)
let wp = wTc * cp
return wp
}
/// Projects a 3D point in the world frame to 2D normalized coordinate.
@differentiable
func projectToNormalized(_ wp: Vector3) -> Vector2 {
projectToNormalized(wp).ip
}
/// Computes the derivative of the projection function wrt to self and the point wp.
@usableFromInline
@derivative(of: projectToNormalized)
func vjpProjectToNormalized(_ wp: Vector3) ->
(value: Vector2, pullback: (Vector2) -> (TangentVector, Vector3))
{
let (ip, cRw, zInv) = projectToNormalized(wp)
let (u, v) = (ip.x, ip.y)
let R = cRw.coordinate.R
return (
value: ip,
pullback: { p in
let dpose = Vector6(
p.x * (u * v) + p.y * (1 + v * v),
p.x * -(1 + u * u) + p.y * -(u * v),
p.x * v + p.y * -u,
p.x * -zInv,
p.y * -zInv,
p.x * (zInv * u) + p.y * (zInv * v))
let dpoint = zInv * Vector3(
p.x * (R[0, 0] - u * R[2, 0]) + p.y * (R[1, 0] - v * R[2, 0]),
p.x * (R[0, 1] - u * R[2, 1]) + p.y * (R[1, 1] - v * R[2, 1]),
p.x * (R[0, 2] - u * R[2, 2]) + p.y * (R[1, 2] - v * R[2, 2]))
return (
TangentVector(wTc: dpose, calibration: calibration.zeroTangentVector()),
dpoint)
}
)
}
/// Projects a 3D point in the world frame to 2D normalized coordinate and returns intermediate values.
func projectToNormalized(_ wp: Vector3) ->
(ip: Vector2, cRw: Rot3, zInv: Double)
{
// Transform the point to camera coordinate
let cTw = wTc.inverse()
let cp = cTw * wp
// TODO: check for cheirality (whether the point is behind the camera)
// Project to normalized coordinate
let zInv = 1.0 / cp.z
return (
ip: Vector2(cp.x * zInv, cp.y * zInv),
cRw: cTw.rot,
zInv: zInv)
}
}
| ab753ffc39bd400e4568eeb7981fc1ef | 28.52381 | 105 | 0.60129 | false | false | false | false |
AndreMuis/TISensorTag | refs/heads/master | TISensorTag/Views/TSTSimpleKeyView.swift | mit | 1 | //
// TSTSimpleKeyView.swift
// TISensorTag
//
// Created by Andre Muis on 5/21/16.
// Copyright © 2016 Andre Muis. All rights reserved.
//
import UIKit
class TSTSimpleKeyView: UIView
{
var depressedFrame : CGRect
var pressedFrame : CGRect
required init?(coder aDecoder: NSCoder)
{
self.depressedFrame = CGRectZero
self.pressedFrame = CGRectZero
super.init(coder: aDecoder)
}
func setup()
{
self.depressedFrame = self.frame
self.pressedFrame = CGRectMake(self.frame.origin.x,
self.frame.origin.y + self.frame.size.height * TSTConstants.SimpleKeyView.depressedPercent,
self.frame.size.width,
self.frame.size.height * (1.0 - TSTConstants.SimpleKeyView.depressedPercent))
let cornerRadius : CGFloat = TSTConstants.SimpleKeyView.cornerRadius
let bezierPath : UIBezierPath = UIBezierPath(roundedRect: self.bounds,
byRoundingCorners: [UIRectCorner.TopLeft, UIRectCorner.TopRight],
cornerRadii: CGSizeMake(cornerRadius, cornerRadius))
let shapeLayer : CAShapeLayer = CAShapeLayer()
shapeLayer.frame = self.bounds
shapeLayer.path = bezierPath.CGPath
self.layer.mask = shapeLayer
}
func press()
{
self.frame = self.pressedFrame
}
func depress()
{
self.frame = self.depressedFrame
}
}
| 25ee21573b7eefc9dffdefd2eca08645 | 22.536232 | 130 | 0.569581 | false | false | false | false |
russelhampton05/MenMew | refs/heads/master | App Prototypes/App_Prototype_A_001/App_Prototype_Alpha_001/SettingsViewController.swift | mit | 1 | //
// SettingsViewController.swift
// App_Prototype_Alpha_001
//
// Created by Jon Calanio on 9/20/16.
// Copyright © 2016 Jon Calanio. All rights reserved.
//
import UIKit
class SettingsViewController: UITableViewController {
//IBOutlets
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var locationLabel: UILabel!
@IBOutlet weak var profilePhoto: UIImageView!
@IBOutlet weak var personaTab: UITableViewCell!
@IBOutlet weak var profileTab: UITableViewCell!
@IBOutlet weak var ordersTab: UITableViewCell!
@IBOutlet weak var settingsTab: UITableViewCell!
@IBOutlet weak var logoutTab: UITableViewCell!
//Variables
var restaurantName: String?
var didLogout: Bool = false
override func viewDidLoad() {
super.viewDidLoad()
loadPage()
}
override func viewWillAppear(_ animated: Bool) {
if didLogout {
loadPage()
didLogout = false
}
}
func loadPage()
{
nameLabel.text = currentUser!.name
MenuManager.GetMenu(id: currentUser!.ticket!.restaurant_ID!) {
menu in
self.locationLabel.text = "At " + menu.title!
self.restaurantName = menu.title!
}
if currentUser!.image != nil {
profilePhoto.getImage(urlString: currentUser!.image!, circle: false)
}
loadTheme()
loadCells()
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
//Segue
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ProfileSegue" {
let profileVC = segue.destination as! ProfileViewController
profileVC.restaurantName = self.restaurantName!
}
if segue.identifier == "SummarySegue" {
let orderVC = segue.destination as! OrderSummaryViewController
orderVC.ticket = currentUser!.ticket
}
if segue.identifier == "UnwindToLoginSegue" {
didLogout = true
self.revealViewController().revealToggle(animated: true)
}
}
//Unwind Segue
@IBAction func unwindToSettings(_ sender: UIStoryboardSegue) {
if let sourceVC = sender.source as? ProfileViewController {
if sourceVC.newImageURL != nil {
currentUser!.image = sourceVC.newImageURL!
profilePhoto.image = nil
profilePhoto.getImage(urlString: currentUser!.image!, circle: false)
}
}
else if sender.source is AppSettingsViewController {
reloadTheme()
}
}
func reloadTheme() {
let delay = DispatchTime.now() + 0.5
DispatchQueue.main.asyncAfter(deadline: delay) {
UIView.animate(withDuration: 0.25, animations: { () -> Void in
self.loadTheme()
self.loadCells()
})
}
}
func loadCells() {
let bgView = UIView()
if currentTheme!.name! == "Salmon" {
bgView.backgroundColor = currentTheme!.primary!
}
else {
bgView.backgroundColor = currentTheme!.highlight!
}
ordersTab.selectedBackgroundView = bgView
profileTab.selectedBackgroundView = bgView
settingsTab.selectedBackgroundView = bgView
if currentTheme!.name! == "Salmon" {
ordersTab.textLabel?.highlightedTextColor = currentTheme!.highlight!
profileTab.textLabel?.highlightedTextColor = currentTheme!.highlight!
settingsTab.textLabel?.highlightedTextColor = currentTheme!.highlight!
logoutTab.textLabel?.highlightedTextColor = currentTheme!.highlight!
}
else {
ordersTab.textLabel?.highlightedTextColor = currentTheme!.primary!
profileTab.textLabel?.highlightedTextColor = currentTheme!.primary!
settingsTab.textLabel?.highlightedTextColor = currentTheme!.primary!
logoutTab.textLabel?.highlightedTextColor = currentTheme!.primary!
}
}
func loadTheme() {
//Background and Tint
self.view.backgroundColor = currentTheme!.secondary!
self.view.tintColor = currentTheme!.invert!
self.tableView.backgroundColor = currentTheme!.secondary!
if currentTheme!.name! == "Midnight" || currentTheme!.name! == "Slate" {
UIApplication.shared.statusBarStyle = .lightContent
}
else {
UIApplication.shared.statusBarStyle = .default
}
//Labels
nameLabel.textColor = currentTheme!.invert!
locationLabel.textColor = currentTheme!.invert!
ordersTab.textLabel?.textColor = currentTheme!.invert!
profileTab.textLabel?.textColor = currentTheme!.invert!
settingsTab.textLabel?.textColor = currentTheme!.invert!
logoutTab.textLabel?.textColor = currentTheme!.invert!
//Cells
personaTab.backgroundColor = currentTheme!.secondary!
profileTab.backgroundColor = currentTheme!.secondary!
ordersTab.backgroundColor = currentTheme!.secondary!
settingsTab.backgroundColor = currentTheme!.secondary!
logoutTab.backgroundColor = currentTheme!.secondary!
}
}
| 1f9455f852ea41a3d82834c41d931be6 | 32.45509 | 92 | 0.608914 | false | false | false | false |
richardpiazza/XCServerAPI | refs/heads/master | Example/Pods/CodeQuickKit/Sources/WebAPI+HTTP.swift | mit | 2 | import Foundation
/// A Collection of methods/headers/values/types used during basic HTTP
/// interactions.
public struct HTTP {
/// HTTP defines a set of request methods to indicate the desired action to be performed for a given resource.
/// Although they can also be nouns, these request methods are sometimes referred as HTTP verbs.
public enum RequestMethod: String {
case get = "GET"
case put = "PUT"
case post = "POST"
case patch = "PATCH"
case delete = "DELETE"
public var description: String {
switch self {
case .get:
return "The GET method requests a representation of the specified resource. Requests using GET should only retrieve data."
case .put:
return "The PUT method replaces all current representations of the target resource with the request payload."
case .post:
return "The POST method is used to submit an entity to the specified resource, often causing a change in state or side effects on the server."
case .patch:
return "The PATCH method is used to apply partial modifications to a resource."
case .delete:
return "The DELETE method deletes the specified resource."
}
}
}
/// HTTP Headers as provided from HTTPURLResponse
public typealias Headers = [AnyHashable : Any]
/// Command HTTP Header
public enum Header: String {
case accept = "Accept"
case authorization = "Authorization"
case contentLength = "Content-Length"
case contentMD5 = "Content-MD5"
case contentType = "Content-Type"
case date = "Date"
public var description: String {
switch self {
case .accept:
return "The Accept request HTTP header advertises which content types, expressed as MIME types, the client is able to understand."
case .authorization:
return "The HTTP Authorization request header contains the credentials to authenticate a user agent with a server, usually after the server has responded with a 401 Unauthorized status and the WWW-Authenticate header."
case .contentLength:
return "The Content-Length entity header is indicating the size of the entity-body, in bytes, sent to the recipient."
case .contentType:
return "The Content-Type entity header is used to indicate the media type of the resource."
case .contentMD5:
return "The Content-MD5 header, may be used as a message integrity check (MIC), to verify that the decoded data are the same data that were initially sent."
case .date:
return "The Date general HTTP header contains the date and time at which the message was originated."
}
}
/// HTTP Header date formatter; RFC1123
public static var dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "EEE',' dd MMM yyyy HH':'mm':'ss 'GMT'"
formatter.timeZone = TimeZone(identifier: "GMT")!
formatter.locale = Locale(identifier: "en_US_POSIX")
return formatter
}()
}
/// MIME Types used in the API
public enum MIMEType: String {
case applicationJson = "application/json"
}
/// Authorization schemes used in the API
public enum Authorization {
case basic(username: String, password: String?)
case bearer(token: String)
case custom(headerField: String, headerValue: String)
public var headerValue: String {
switch self {
case .basic(let username, let password):
let pwd = password ?? ""
guard let data = "\(username):\(pwd)".data(using: .utf8) else {
return ""
}
let base64 = data.base64EncodedString(options: [])
return "Basic \(base64)"
case .bearer(let token):
return "Bearer \(token)"
case .custom(let headerField, let headerValue):
return "\(headerField) \(headerValue))"
}
}
}
/// General errors that may be emitted during HTTP Request/Response handling.
public enum Error: Swift.Error, LocalizedError {
case invalidURL
case invalidRequest
case invalidResponse
public var errorDescription: String? {
switch self {
case .invalidURL:
return "Invalid URL: URL is nil or invalid."
case .invalidRequest:
return "Invalid URL Request: URLRequest is nil or invalid."
case .invalidResponse:
return "Invalid URL Response: HTTPURLResponse is nil or invalid."
}
}
}
/// A general completion handler for HTTP requests.
public typealias DataTaskCompletion = (_ statusCode: Int, _ headers: Headers?, _ data: Data?, _ error: Swift.Error?) -> Void
}
public extension URLRequest {
public mutating func setValue(_ value: String, forHTTPHeader header: HTTP.Header) {
self.setValue(value, forHTTPHeaderField: header.rawValue)
}
}
| 5858a83319686b473f1dfc6ac634c4d7 | 41.716535 | 234 | 0.602765 | false | false | false | false |
dclelland/Gong | refs/heads/master | Sources/Gong/Core/MIDINotice.swift | mit | 1 | //
// MIDINotice.swift
// Pods
//
// Created by Daniel Clelland on 19/04/17.
// Copyright © 2017 Daniel Clelland. All rights reserved.
//
import Foundation
import CoreMIDI
public enum MIDINotice {
case setupChanged
case objectAdded(parent: MIDIObject, child: MIDIObject)
case objectRemoved(parent: MIDIObject, child: MIDIObject)
case propertyChanged(object: MIDIObject, property: String)
case throughConnectionsChanged
case serialPortOwnerChanged
case ioError(device: MIDIDevice, error: MIDIError)
}
extension MIDINotice {
public init(_ reference: UnsafePointer<MIDINotification>) {
let notification = reference.pointee
switch notification.messageID {
case .msgSetupChanged:
self = .setupChanged
case .msgObjectAdded:
self = reference.withMemoryRebound(to: MIDIObjectAddRemoveNotification.self, capacity: Int(notification.messageSize)) { pointer in
let notification = pointer.pointee
let parent = MIDIObject.create(with: notification.parent, type: notification.parentType)
let child = MIDIObject.create(with: notification.child, type: notification.childType)
return .objectAdded(parent: parent, child: child)
}
case .msgObjectRemoved:
self = reference.withMemoryRebound(to: MIDIObjectAddRemoveNotification.self, capacity: Int(notification.messageSize)) { pointer in
let notification = pointer.pointee
let parent = MIDIObject.create(with: notification.parent, type: notification.parentType)
let child = MIDIObject.create(with: notification.child, type: notification.childType)
return .objectRemoved(parent: parent, child: child)
}
case .msgPropertyChanged:
self = reference.withMemoryRebound(to: MIDIObjectPropertyChangeNotification.self, capacity: Int(notification.messageSize)) { pointer in
let notification = pointer.pointee
let object = MIDIObject.create(with: notification.object, type: notification.objectType)
let property = notification.propertyName.takeUnretainedValue()
return .propertyChanged(object: object, property: property as String)
}
case .msgThruConnectionsChanged:
self = .throughConnectionsChanged
case .msgSerialPortOwnerChanged:
self = .serialPortOwnerChanged
case .msgIOError:
self = reference.withMemoryRebound(to: MIDIIOErrorNotification.self, capacity: Int(notification.messageSize)) { pointer in
let notification = pointer.pointee
let device = MIDIDevice(notification.driverDevice)
let error = MIDIError(status: notification.errorCode, comment: "Notification error")
return .ioError(device: device, error: error)
}
@unknown default:
fatalError("Unrecognized notification message ID")
}
}
}
| 5b9a8fb58c7eca794148076bc0cc9691 | 45.636364 | 147 | 0.666667 | false | false | false | false |
evgeny-emelyanov/if-park-safe | refs/heads/master | ParkSafe/UserPageInfoController.swift | apache-2.0 | 2 | //
// UserPageInfo.swift
// ParkSafe
//
// Created by Sergey Gorlanov on 22.11.16.
// Copyright © 2016 IF. All rights reserved.
//
import UIKit
class UserPageInfoController: UIViewController {
@IBOutlet weak var PromoCodeText: UILabel!
@IBOutlet weak var promoCodeLabel: UILabel!
@IBOutlet weak var yourDiscountLabel: UILabel!
@IBOutlet weak var spCount: UITextView!
let storage = UserDefaults()
@IBOutlet weak var parkingSpCount: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
toggleDiscountInfo()
spCount.text = storage.string(forKey: "safetyPoints") ?? "0"
parkingSpCount.text = storage.string(forKey: "safetyPoints") ?? "0"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool) {
toggleDiscountInfo()
spCount.text = storage.string(forKey: "safetyPoints") ?? "0"
parkingSpCount.text = storage.string(forKey: "safetyPoints") ?? "0"
}
func toggleDiscountInfo() {
var spState = storage.integer(forKey: "safetyPoints")
if (spState > 10) {
PromoCodeText.isHidden = false
promoCodeLabel.isHidden = false
yourDiscountLabel.isHidden = false
} else {
PromoCodeText.isHidden = true
promoCodeLabel.isHidden = true
yourDiscountLabel.isHidden = true
}
}
}
| 2d262267ec07e8e6fc6c5cf55b227fa3 | 30.16 | 75 | 0.634146 | false | false | false | false |
0xced/Carthage | refs/heads/master | Source/CarthageKit/Git.swift | mit | 1 | //
// Git.swift
// Carthage
//
// Created by Alan Rogers on 14/10/2014.
// Copyright (c) 2014 Carthage. All rights reserved.
//
import Foundation
import LlamaKit
import ReactiveCocoa
import ReactiveTask
/// Represents a URL for a Git remote.
public struct GitURL: Equatable {
/// The string representation of the URL.
public let URLString: String
/// A normalized URL string, without protocol, authentication, or port
/// information. This is mostly useful for comparison, and not for any
/// actual Git operations.
private var normalizedURLString: String {
let parsedURL: NSURL? = NSURL(string: URLString)
if let parsedURL = parsedURL {
// Normal, valid URL.
let host = parsedURL.host ?? ""
let path = stripGitSuffix(parsedURL.path ?? "")
return "\(host)\(path)"
} else if URLString.hasPrefix("/") {
// Local path.
return stripGitSuffix(URLString)
} else {
// scp syntax.
var strippedURLString = URLString
if let index = find(strippedURLString, "@") {
strippedURLString.removeRange(Range(start: strippedURLString.startIndex, end: index))
}
var host = ""
if let index = find(strippedURLString, ":") {
host = strippedURLString[Range(start: strippedURLString.startIndex, end: index.predecessor())]
strippedURLString.removeRange(Range(start: strippedURLString.startIndex, end: index))
}
var path = strippedURLString
if !path.hasPrefix("/") {
// This probably isn't strictly legit, but we'll have a forward
// slash for other URL types.
path.insert("/", atIndex: path.startIndex)
}
return "\(host)\(path)"
}
}
/// The name of the repository, if it can be inferred from the URL.
public var name: String? {
let components = split(URLString, { $0 == "/" }, allowEmptySlices: false)
return components.last.map { self.stripGitSuffix($0) }
}
public init(_ URLString: String) {
self.URLString = URLString
}
/// Strips any trailing .git in the given name, if one exists.
private func stripGitSuffix(string: String) -> String {
if string.hasSuffix(".git") {
let nsString = string as NSString
return nsString.substringToIndex(nsString.length - 4) as String
} else {
return string
}
}
}
public func ==(lhs: GitURL, rhs: GitURL) -> Bool {
return lhs.normalizedURLString == rhs.normalizedURLString
}
extension GitURL: Hashable {
public var hashValue: Int {
return normalizedURLString.hashValue
}
}
extension GitURL: Printable {
public var description: String {
return URLString
}
}
/// A Git submodule.
public struct Submodule: Equatable {
/// The name of the submodule. Usually (but not always) the same as the
/// path.
public let name: String
/// The relative path at which the submodule is checked out.
public let path: String
/// The URL from which the submodule should be cloned, if present.
public var URL: GitURL
/// The SHA checked out in the submodule.
public var SHA: String
public init(name: String, path: String, URL: GitURL, SHA: String) {
self.name = name
self.path = path
self.URL = URL
self.SHA = SHA
}
}
public func ==(lhs: Submodule, rhs: Submodule) -> Bool {
return lhs.name == rhs.name && lhs.path == rhs.path && lhs.URL == rhs.URL && lhs.SHA == rhs.SHA
}
extension Submodule: Hashable {
public var hashValue: Int {
return name.hashValue
}
}
extension Submodule: Printable {
public var description: String {
return "\(name) @ \(SHA)"
}
}
/// Shells out to `git` with the given arguments, optionally in the directory
/// of an existing repository.
public func launchGitTask(arguments: [String], repositoryFileURL: NSURL? = nil, standardOutput: SinkOf<NSData>? = nil, standardError: SinkOf<NSData>? = nil, environment: [String: String]? = nil) -> ColdSignal<String> {
let taskDescription = TaskDescription(launchPath: "/usr/bin/env", arguments: [ "git" ] + arguments, workingDirectoryPath: repositoryFileURL?.path, environment: environment)
return launchTask(taskDescription, standardOutput: standardOutput, standardError: standardError)
.map { NSString(data: $0, encoding: NSUTF8StringEncoding) as String }
}
/// Returns a signal that completes when cloning completes successfully.
public func cloneRepository(cloneURL: GitURL, destinationURL: NSURL, bare: Bool = true) -> ColdSignal<String> {
precondition(destinationURL.fileURL)
var arguments = [ "clone" ]
if bare {
arguments.append("--bare")
}
return launchGitTask(arguments + [ "--quiet", cloneURL.URLString, destinationURL.path! ])
}
/// Returns a signal that completes when the fetch completes successfully.
public func fetchRepository(repositoryFileURL: NSURL, remoteURL: GitURL? = nil, refspec: String? = nil) -> ColdSignal<String> {
precondition(repositoryFileURL.fileURL)
var arguments = [ "fetch", "--tags", "--prune", "--quiet" ]
if let remoteURL = remoteURL {
arguments.append(remoteURL.URLString)
}
if let refspec = refspec {
arguments.append(refspec)
}
return launchGitTask(arguments, repositoryFileURL: repositoryFileURL)
}
/// Sends each tag found in the given Git repository.
public func listTags(repositoryFileURL: NSURL) -> ColdSignal<String> {
return launchGitTask([ "tag" ], repositoryFileURL: repositoryFileURL)
.map { (allTags: String) -> ColdSignal<String> in
return ColdSignal { (sink, disposable) in
let string = allTags as NSString
string.enumerateSubstringsInRange(NSMakeRange(0, string.length), options: NSStringEnumerationOptions.ByLines | NSStringEnumerationOptions.Reverse) { (line, substringRange, enclosingRange, stop) in
if disposable.disposed {
stop.memory = true
}
sink.put(.Next(Box(line as String)))
}
sink.put(.Completed)
}
}
.merge(identity)
}
/// Returns the text contents of the path at the given revision, or an error if
/// the path could not be loaded.
public func contentsOfFileInRepository(repositoryFileURL: NSURL, path: String, revision: String = "HEAD") -> ColdSignal<String> {
let showObject = "\(revision):\(path)"
return launchGitTask([ "show", showObject ], repositoryFileURL: repositoryFileURL, standardError: SinkOf<NSData> { _ in () })
}
/// Checks out the working tree of the given (ideally bare) repository, at the
/// specified revision, to the given folder. If the folder does not exist, it
/// will be created.
public func checkoutRepositoryToDirectory(repositoryFileURL: NSURL, workingDirectoryURL: NSURL, revision: String = "HEAD", shouldCloneSubmodule: Submodule -> Bool = { _ in true }) -> ColdSignal<()> {
return ColdSignal.lazy {
var error: NSError?
if !NSFileManager.defaultManager().createDirectoryAtURL(workingDirectoryURL, withIntermediateDirectories: true, attributes: nil, error: &error) {
return .error(error ?? CarthageError.RepositoryCheckoutFailed(workingDirectoryURL: workingDirectoryURL, reason: "Could not create working directory").error)
}
var environment = NSProcessInfo.processInfo().environment as [String: String]
environment["GIT_WORK_TREE"] = workingDirectoryURL.path!
return launchGitTask([ "checkout", "--quiet", "--force", revision ], repositoryFileURL: repositoryFileURL, environment: environment)
.then(cloneSubmodulesForRepository(repositoryFileURL, workingDirectoryURL, revision: revision, shouldCloneSubmodule: shouldCloneSubmodule))
}
}
/// Clones matching submodules for the given repository at the specified
/// revision, into the given working directory.
public func cloneSubmodulesForRepository(repositoryFileURL: NSURL, workingDirectoryURL: NSURL, revision: String = "HEAD", shouldCloneSubmodule: Submodule -> Bool = { _ in true }) -> ColdSignal<()> {
return submodulesInRepository(repositoryFileURL, revision: revision)
.map { submodule -> ColdSignal<()> in
if shouldCloneSubmodule(submodule) {
return cloneSubmoduleInWorkingDirectory(submodule, workingDirectoryURL)
} else {
return .empty()
}
}
.concat(identity)
.then(.empty())
}
/// Clones the given submodule into the working directory of its parent
/// repository, but without any Git metadata.
public func cloneSubmoduleInWorkingDirectory(submodule: Submodule, workingDirectoryURL: NSURL) -> ColdSignal<()> {
let submoduleDirectoryURL = workingDirectoryURL.URLByAppendingPathComponent(submodule.path, isDirectory: true)
let purgeGitDirectories = ColdSignal<()> { (sink, disposable) in
let enumerator = NSFileManager.defaultManager().enumeratorAtURL(submoduleDirectoryURL, includingPropertiesForKeys: [ NSURLIsDirectoryKey!, NSURLNameKey! ], options: nil, errorHandler: nil)!
while !disposable.disposed {
let URL: NSURL! = enumerator.nextObject() as? NSURL
if URL == nil {
break
}
var name: AnyObject?
var error: NSError?
if !URL.getResourceValue(&name, forKey: NSURLNameKey, error: &error) {
sink.put(.Error(error ?? CarthageError.RepositoryCheckoutFailed(workingDirectoryURL: submoduleDirectoryURL, reason: "could not enumerate name of descendant at \(URL.path!)").error))
return
}
if let name = name as? NSString {
if name != ".git" {
continue
}
} else {
continue
}
var isDirectory: AnyObject?
if !URL.getResourceValue(&isDirectory, forKey: NSURLIsDirectoryKey, error: &error) || isDirectory == nil {
sink.put(.Error(error ?? CarthageError.RepositoryCheckoutFailed(workingDirectoryURL: submoduleDirectoryURL, reason: "could not determine whether \(URL.path!) is a directory").error))
return
}
if let directory = isDirectory?.boolValue {
if directory {
enumerator.skipDescendants()
}
}
if !NSFileManager.defaultManager().removeItemAtURL(URL, error: &error) {
sink.put(.Error(error ?? CarthageError.RepositoryCheckoutFailed(workingDirectoryURL: submoduleDirectoryURL, reason: "could not remove \(URL.path!)").error))
return
}
}
sink.put(.Completed)
}
return ColdSignal<String>.lazy {
var error: NSError?
if !NSFileManager.defaultManager().removeItemAtURL(submoduleDirectoryURL, error: &error) {
return .error(error ?? CarthageError.RepositoryCheckoutFailed(workingDirectoryURL: submoduleDirectoryURL, reason: "could not remove submodule checkout").error)
}
return cloneRepository(submodule.URL, workingDirectoryURL.URLByAppendingPathComponent(submodule.path), bare: false)
}
.then(checkoutSubmodule(submodule, submoduleDirectoryURL))
.then(purgeGitDirectories)
}
/// Recursively checks out the given submodule's revision, in its working
/// directory.
private func checkoutSubmodule(submodule: Submodule, submoduleWorkingDirectoryURL: NSURL) -> ColdSignal<()> {
return launchGitTask([ "checkout", "--quiet", submodule.SHA ], repositoryFileURL: submoduleWorkingDirectoryURL)
.then(launchGitTask([ "submodule", "--quiet", "update", "--init", "--recursive" ], repositoryFileURL: submoduleWorkingDirectoryURL))
.then(.empty())
}
/// Parses each key/value entry from the given config file contents, optionally
/// stripping a known prefix/suffix off of each key.
private func parseConfigEntries(contents: String, keyPrefix: String = "", keySuffix: String = "") -> ColdSignal<(String, String)> {
let entries = split(contents, { $0 == "\0" }, allowEmptySlices: false)
return ColdSignal { (sink, disposable) in
for entry in entries {
if disposable.disposed {
break
}
let components = split(entry, { $0 == "\n" }, maxSplit: 1, allowEmptySlices: true)
if components.count != 2 {
continue
}
let value = components[1]
let scanner = NSScanner(string: components[0])
if !scanner.scanString(keyPrefix, intoString: nil) {
continue
}
var key: NSString?
if !scanner.scanUpToString(keySuffix, intoString: &key) {
continue
}
if let key = key as? String {
sink.put(.Next(Box((key, value))))
}
}
sink.put(.Completed)
}
}
/// Determines the SHA that the submodule at the given path is pinned to, in the
/// revision of the parent repository specified.
public func submoduleSHAForPath(repositoryFileURL: NSURL, path: String, revision: String = "HEAD") -> ColdSignal<String> {
return launchGitTask([ "ls-tree", "-z", revision, path ], repositoryFileURL: repositoryFileURL)
.tryMap { string -> Result<String> in
// Example:
// 160000 commit 083fd81ecf00124cbdaa8f86ef10377737f6325a External/ObjectiveGit
let components = split(string, { $0 == " " || $0 == "\t" }, maxSplit: 3, allowEmptySlices: false)
if components.count >= 3 {
return success(components[2])
} else {
return failure(CarthageError.ParseError(description: "expected submodule commit SHA in ls-tree output: \(string)").error)
}
}
}
/// Returns each submodule found in the given repository revision, or an empty
/// signal if none exist.
public func submodulesInRepository(repositoryFileURL: NSURL, revision: String = "HEAD") -> ColdSignal<Submodule> {
let modulesObject = "\(revision):.gitmodules"
let baseArguments = [ "config", "--blob", modulesObject, "-z" ]
return launchGitTask(baseArguments + [ "--get-regexp", "submodule\\..*\\.path" ], repositoryFileURL: repositoryFileURL, standardError: SinkOf<NSData> { _ in () })
.catch { _ in .empty() }
.map { parseConfigEntries($0, keyPrefix: "submodule.", keySuffix: ".path") }
.merge(identity)
.map { (name, path) -> ColdSignal<Submodule> in
return launchGitTask(baseArguments + [ "--get", "submodule.\(name).url" ], repositoryFileURL: repositoryFileURL)
.map { GitURL($0) }
.zipWith(submoduleSHAForPath(repositoryFileURL, path, revision: revision))
.map { (URL, SHA) in
return Submodule(name: name, path: path, URL: URL, SHA: SHA)
}
}
.merge(identity)
}
/// Determines whether the specified revision identifies a valid commit.
///
/// If the specified file URL does not represent a valid Git repository, `false`
/// will be sent.
public func commitExistsInRepository(repositoryFileURL: NSURL, revision: String = "HEAD") -> ColdSignal<Bool> {
return ColdSignal.lazy {
// NSTask throws a hissy fit (a.k.a. exception) if the working directory
// doesn't exist, so pre-emptively check for that.
var isDirectory: ObjCBool = false
if !NSFileManager.defaultManager().fileExistsAtPath(repositoryFileURL.path!, isDirectory: &isDirectory) || !isDirectory {
return .single(false)
}
return launchGitTask([ "rev-parse", "\(revision)^{commit}" ], repositoryFileURL: repositoryFileURL, standardOutput: SinkOf<NSData> { _ in () }, standardError: SinkOf<NSData> { _ in () })
.then(.single(true))
.catch { _ in .single(false) }
}
}
/// Attempts to resolve the given reference into an object SHA.
public func resolveReferenceInRepository(repositoryFileURL: NSURL, reference: String) -> ColdSignal<String> {
return launchGitTask([ "rev-parse", "\(reference)^{object}" ], repositoryFileURL: repositoryFileURL, standardError: SinkOf<NSData> { _ in () })
.map { string in
return string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
}
.catch { _ in .error(CarthageError.RepositoryCheckoutFailed(workingDirectoryURL: repositoryFileURL, reason: "No object named \"\(reference)\" exists").error) }
}
/// Returns the location of the .git folder within the given repository.
private func gitDirectoryURLInRepository(repositoryFileURL: NSURL) -> NSURL {
return repositoryFileURL.URLByAppendingPathComponent(".git")
}
/// Attempts to determine whether the given directory represents a Git
/// repository.
private func isGitRepository(directoryURL: NSURL) -> Bool {
return NSFileManager.defaultManager().fileExistsAtPath(gitDirectoryURLInRepository(directoryURL).path!)
}
/// Adds the given submodule to the given repository, cloning from `fetchURL` if
/// the desired revision does not exist or the submodule needs to be cloned.
public func addSubmoduleToRepository(repositoryFileURL: NSURL, submodule: Submodule, fetchURL: GitURL) -> ColdSignal<()> {
let submoduleDirectoryURL = repositoryFileURL.URLByAppendingPathComponent(submodule.path, isDirectory: true)
return ColdSignal.lazy {
if isGitRepository(submoduleDirectoryURL) {
// If the submodule repository already exists, just check out and
// stage the correct revision.
return fetchRepository(submoduleDirectoryURL, remoteURL: fetchURL)
.then(launchGitTask([ "config", "--file", ".gitmodules", "submodule.\(submodule.name).url", submodule.URL.URLString ], repositoryFileURL: repositoryFileURL))
.then(launchGitTask([ "submodule", "--quiet", "sync" ], repositoryFileURL: repositoryFileURL))
.then(checkoutSubmodule(submodule, submoduleDirectoryURL))
.then(launchGitTask([ "add", "--force", submodule.path ], repositoryFileURL: repositoryFileURL))
.then(.empty())
} else {
let addSubmodule = launchGitTask([ "submodule", "--quiet", "add", "--force", "--name", submodule.name, "--", submodule.URL.URLString, submodule.path ], repositoryFileURL: repositoryFileURL)
// A failure to add usually means the folder was already added
// to the index. That's okay.
.catch { _ in .empty() }
// If it doesn't exist, clone and initialize a submodule from our
// local bare repository.
return cloneRepository(fetchURL, submoduleDirectoryURL, bare: false)
.then(launchGitTask([ "remote", "set-url", "origin", submodule.URL.URLString ], repositoryFileURL: submoduleDirectoryURL))
.then(checkoutSubmodule(submodule, submoduleDirectoryURL))
.then(addSubmodule)
.then(launchGitTask([ "submodule", "--quiet", "init", "--", submodule.path ], repositoryFileURL: repositoryFileURL))
.then(.empty())
}
}
}
/// Moves an item within a Git repository, or within a simple directory if a Git
/// repository is not found.
///
/// Sends the new URL of the item after moving.
public func moveItemInPossibleRepository(repositoryFileURL: NSURL, #fromPath: String, #toPath: String) -> ColdSignal<NSURL> {
let toURL = repositoryFileURL.URLByAppendingPathComponent(toPath)
let parentDirectoryURL = toURL.URLByDeletingLastPathComponent!
return ColdSignal.lazy {
var error: NSError?
if !NSFileManager.defaultManager().createDirectoryAtURL(parentDirectoryURL, withIntermediateDirectories: true, attributes: nil, error: &error) {
return .error(error ?? CarthageError.WriteFailed(parentDirectoryURL).error)
}
if isGitRepository(repositoryFileURL) {
return launchGitTask([ "mv", "-k", fromPath, toPath ], repositoryFileURL: repositoryFileURL)
.then(.single(toURL))
} else {
let fromURL = repositoryFileURL.URLByAppendingPathComponent(fromPath)
var error: NSError?
if NSFileManager.defaultManager().moveItemAtURL(fromURL, toURL: toURL, error: &error) {
return .single(toURL)
} else {
return .error(error ?? CarthageError.WriteFailed(toURL).error)
}
}
}
}
| 0cf5fa62e5c9bc221c80e162f0e8c4c6 | 38.264706 | 218 | 0.726271 | false | false | false | false |
kaushaldeo/Olympics | refs/heads/master | Olympics/ViewControllers/KDCountriesViewController.swift | apache-2.0 | 1 | //
// KDCountriesViewController.swift
// Olympics
//
// Created by Kaushal Deo on 6/10/16.
// Copyright © 2016 Scorpion Inc. All rights reserved.
//
import UIKit
import CoreData
import Firebase
class KDCountriesViewController: UITableViewController, NSFetchedResultsControllerDelegate, UISearchControllerDelegate, UISearchBarDelegate, UISearchResultsUpdating {
lazy var searchController: UISearchController = {
var searchController = UISearchController(searchResultsController: nil)
searchController.searchResultsUpdater = self
searchController.delegate = self
searchController.hidesNavigationBarDuringPresentation = false
searchController.dimsBackgroundDuringPresentation = false
searchController.searchBar.sizeToFit()
searchController.searchBar.tintColor = UIColor.whiteColor()
searchController.searchBar.delegate = self // so we can monitor text changes + others
/*
Search is now just presenting a view controller. As such, normal view controller
presentation semantics apply. Namely that presentation will walk up the view controller
hierarchy until it finds the root view controller or one that defines a presentation context.
*/
return searchController
}()
var leftBarItem : UIBarButtonItem? = nil
var rigthBarItem : UIBarButtonItem? = nil
//MARK: - Private Methods
func cancelTapped(sender: AnyObject) {
self.performSegueWithIdentifier("replace", sender: nil)
}
//MARK: - View Life Cycle
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()
self.tableView.estimatedRowHeight = 44.0
self.tableView.rowHeight = UITableViewAutomaticDimension
self.navigationController?.navigationBar.barTintColor = UIColor(red: 0, green: 103, blue: 173)
self.searchController.searchBar.barTintColor = UIColor(red: 0, green: 103, blue: 173)
let setting = NSUserDefaults.standardUserDefaults()
if let _ = setting.valueForKey("kCountry") {
self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Cancel, target: self, action: #selector(KDCountriesViewController.cancelTapped(_:)))
}
self.tableView.reloadSections(NSIndexSet(indexesInRange: NSMakeRange(0, self.tableView.numberOfSections)), withRowAnimation: .None)
self.navigationItem.titleView = self.searchController.searchBar
self.navigationItem.backBarButtonItem = UIBarButtonItem(title:"", style: .Plain, target: nil, action: nil)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.fetchedResultsController.update()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.fetchedResultsController.sections?.count ?? 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let sectionInfo = self.fetchedResultsController.sections![section]
return sectionInfo.numberOfObjects
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! KDCountryViewCell
// Configure the cell...
let country = self.fetchedResultsController.objectAtIndexPath(indexPath) as! Country
cell.nameLabel.text = country.name
cell.aliasLabel.text = country.alias
if let text = country.alias?.lowercaseString {
cell.iconView.image = UIImage(named: "Images/\(text).png")
}
return cell
}
override func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? {
return self.fetchedResultsController.sectionIndexTitles
}
override func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int {
return self.fetchedResultsController.sectionForSectionIndexTitle(title, atIndex: index)
}
/*
// 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
}
*/
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let country = self.fetchedResultsController.objectAtIndexPath(indexPath) as! Country
let setting = NSUserDefaults.standardUserDefaults()
let url = country.objectID.URIRepresentation().absoluteString
setting.setValue(url, forKey: "kCountry");
if let string = country.alias {
FIRMessaging.messaging().subscribeToTopic(string)
}
}
/*
// 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.
}
*/
// MARK: - Fetched results controller
lazy var fetchedResultsController: NSFetchedResultsController = {
let context = NSManagedObjectContext.mainContext()
let fetchRequest = NSFetchRequest()
// Edit the entity name as appropriate.
let entity = NSEntityDescription.entityForName("Country", inManagedObjectContext: context)
fetchRequest.entity = entity
// Set the batch size to a suitable number.
fetchRequest.fetchBatchSize = 20
// Edit the sort key as appropriate.
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true), NSSortDescriptor(key: "alias", ascending: true)]
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
var fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext:context, sectionNameKeyPath: "name", cacheName: nil)
fetchedResultsController.delegate = self
fetchedResultsController.update()
return fetchedResultsController
}()
/*
func controllerWillChangeContent(controller: NSFetchedResultsController) {
self.tableView.beginUpdates()
}
func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
switch type {
case .Insert:
self.tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
case .Delete:
self.tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
default:
return
}
}
func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
switch type {
case .Insert:
tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
case .Delete:
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
case .Update:
tableView.reloadRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
case .Move:
tableView.moveRowAtIndexPath(indexPath!, toIndexPath: newIndexPath!)
}
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
self.tableView.endUpdates()
}
*/
// Implementing the above methods to update the table view in response to individual changes may have performance implications if a large number of changes are made simultaneously. If this proves to be an issue, you can instead just implement controllerDidChangeContent: which notifies the delegate that all section and object changes have been processed.
func controllerDidChangeContent(controller: NSFetchedResultsController) {
// In the simplest, most efficient, case, reload the table view.
self.tableView.reloadData()
}
// MARK: UISearchBarDelegate
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
searchBar.resignFirstResponder()
}
// MARK: UISearchResultsUpdating
func updateSearchResultsForSearchController(searchController: UISearchController) {
// Strip out all the leading and trailing spaces.
let whitespaceCharacterSet = NSCharacterSet.whitespaceCharacterSet()
let strippedString = searchController.searchBar.text!.stringByTrimmingCharactersInSet(whitespaceCharacterSet)
if strippedString.characters.count > 0 {
let predicate = NSPredicate(format: "name contains[cd] %@ OR alias contains[cd] %@", strippedString,strippedString)
self.fetchedResultsController.fetchRequest.predicate = predicate
}
else {
self.fetchedResultsController.fetchRequest.predicate = nil
}
self.fetchedResultsController.update()
self.tableView.reloadData()
}
func willPresentSearchController(searchController: UISearchController) {
self.leftBarItem = self.navigationItem.leftBarButtonItem
self.rigthBarItem = self.navigationItem.rightBarButtonItem
self.navigationItem.setLeftBarButtonItem(nil, animated: true)
self.navigationItem.setRightBarButtonItem(nil, animated: true)
}
// @available(iOS 8.0, *)
// optional public func didPresentSearchController(searchController: UISearchController)
// @available(iOS 8.0, *)
func willDismissSearchController(searchController: UISearchController) {
self.navigationItem.setLeftBarButtonItem(self.leftBarItem, animated: true)
self.navigationItem.setRightBarButtonItem(self.rigthBarItem, animated: true)
}
}
| 247a1a2ad00fbe3e82832cc4a7d95dbf | 40.910035 | 359 | 0.700297 | false | false | false | false |
robbdimitrov/pixelgram-ios | refs/heads/master | PixelGram/Classes/Shared/Extensions/FullWidthCell.swift | mit | 1 | //
// FullWidthCell.swift
// PixelGram
//
// Created by Robert Dimitrov on 10/31/17.
// Copyright © 2017 Robert Dimitrov. All rights reserved.
//
import UIKit
protocol FullWidth {}
extension FullWidth where Self: UICollectionReusableView {
func calculatePreferredLayoutFrame(_ origin: CGPoint, targetWidth: CGFloat) -> CGRect {
let targetSize = CGSize(width: targetWidth, height: 0)
let horizontalFittingPriority = UILayoutPriority.required
let verticalFittingPriority = UILayoutPriority.defaultLow
var autoLayoutSize: CGSize
if let contentView = (self as? UICollectionViewCell)?.contentView {
autoLayoutSize = contentView.systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: horizontalFittingPriority,
verticalFittingPriority: verticalFittingPriority)
} else {
autoLayoutSize = systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: horizontalFittingPriority,
verticalFittingPriority: verticalFittingPriority)
}
let autoLayoutFrame = CGRect(origin: origin, size: autoLayoutSize)
return autoLayoutFrame
}
}
class FullWidthCollectionReusableView: UICollectionReusableView, FullWidth {
override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
let autoLayoutAttributes = super.preferredLayoutAttributesFitting(layoutAttributes)
autoLayoutAttributes.frame = calculatePreferredLayoutFrame(layoutAttributes.frame.origin,
targetWidth: layoutAttributes.frame.width)
return autoLayoutAttributes
}
}
class FullWidthCollectionViewCell: UICollectionViewCell, FullWidth {
override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
let autoLayoutAttributes = super.preferredLayoutAttributesFitting(layoutAttributes)
autoLayoutAttributes.frame = calculatePreferredLayoutFrame(layoutAttributes.frame.origin,
targetWidth: layoutAttributes.frame.width)
return autoLayoutAttributes
}
}
| 01a0ef2f49b7c50ca9a87d0cf527d29e | 39.241935 | 142 | 0.671343 | false | false | false | false |
twtstudio/WePeiYang-iOS | refs/heads/master | WePeiYang/Read/Model/Recommender.swift | mit | 1 | //
// Recommender.swift
// WePeiYang
//
// Created by JinHongxu on 2016/10/28.
// Copyright © 2016年 Qin Yubo. All rights reserved.
//
class Recommender {
var bannerList: [Banner] = []
var recommendedList: [RecommendedBook] = []
var starList: [StarUser] = []
var reviewList: [Review] = []
var finishFlag = FinishFlag()
var dataDidRefresh = false
static let sharedInstance = Recommender()
private init() {}
struct Banner {
var image: String
var title: String
var url: String
}
struct RecommendedBook {
var id: Int
var title: String
var author: String
var cover: String
}
struct StarUser {
var id: Int
var name: String
var avatar: String
var reviewCount: Int
}
struct FinishFlag {
var bannerFlag = false
var recommendedFlag = false
var hotReviewFlag = false
var starUserFlag = false
func isFinished() -> Bool {
return bannerFlag && recommendedFlag && hotReviewFlag && starUserFlag
}
mutating func reset() {
bannerFlag = false
recommendedFlag = false
hotReviewFlag = false
starUserFlag = false
}
}
func getBannerList(success: () -> ()) {
// bannerList = [
// Banner(id: 1, image: "http://www.twt.edu.cn/upload/banners/hheZnqd196Te76SDF9Ww.png", title: "", url: ""),
// Banner(id: 1, image: "http://www.twt.edu.cn/upload/banners/ZPQqmajzKOI3A6qE7gIR.png", title: "", url: ""),
// Banner(id: 1, image: "http://www.twt.edu.cn/upload/banners/gJjWSlAvkGjZmdbuFtXT.jpeg", title: "", url: "")
// ]
// success()
User.sharedInstance.getToken({
token in
let manager = AFHTTPSessionManager()
manager.requestSerializer.setValue("Bearer {\(token)}", forHTTPHeaderField: "Authorization")
var fooBannerList: [Banner] = []
manager.GET(ReadAPI.bannerURL, parameters: nil, progress: nil, success: { (task, responseObject) in
// print("banner")
// print(responseObject)
guard let dict = responseObject as? Dictionary<String, AnyObject> where dict["error_code"] as! Int == -1,
let data = dict["data"] as? Array<Dictionary<String, AnyObject>>
else {
if let dict = responseObject as? Dictionary<String, AnyObject> where dict["error_code"] as! Int == 10000 {
print("removed read token")
NSUserDefaults.standardUserDefaults().removeObjectForKey("readToken")
}
MsgDisplay.showErrorMsg("获取数据失败")
return
}
for dic in data {
guard let image = dic["img"] as? String,
let title = dic["title"] as? String,
let url = dic["url"] as? String
else {
continue
}
fooBannerList.append(Banner(image: image, title: title, url: url))
//self.bannerList.append(Banner(image: image, title: title, url: url))
}
self.finishFlag.bannerFlag = true
self.bannerList = fooBannerList
success()
}) { (_, error) in
self.finishFlag.bannerFlag = true
MsgDisplay.showErrorMsg("获取 banner 数据失败")
print(error)
}
})
}
func getRecommendedList(success: () -> ()) {
User.sharedInstance.getToken({
token in
let manager = AFHTTPSessionManager()
manager.requestSerializer.setValue("Bearer {\(token)}", forHTTPHeaderField: "Authorization")
var fooRecommendedList: [RecommendedBook] = []
manager.GET(ReadAPI.recommendedURL, parameters: nil, progress: nil, success: { (task, responseObject) in
// print("recommended")
// print(responseObject)
guard let dict = responseObject as? Dictionary<String, AnyObject> where dict["error_code"] as! Int == -1,
let data = dict["data"] as? Array<Dictionary<String, AnyObject>>
else {
if let dict = responseObject as? Dictionary<String, AnyObject> where dict["error_code"] as! Int == 10000 {
print("removed read token")
NSUserDefaults.standardUserDefaults().removeObjectForKey("readToken")
}
MsgDisplay.showErrorMsg("获取热门推荐数据失败")
return
}
for dic in data {
guard let id = dic["id"] as? Int,
let title = dic["title"] as? String,
let author = dic["author"] as? String,
let cover = dic["cover_url"] as? String
else {
continue
}
fooRecommendedList.append(RecommendedBook(id: id, title: title, author: author, cover: cover))
//self.recommendedList.append(RecommendedBook(id: id, title: title, author: author, cover: cover))
}
self.finishFlag.recommendedFlag = true
self.recommendedList = fooRecommendedList
success()
}) { (_, error) in
self.finishFlag.recommendedFlag = true
MsgDisplay.showErrorMsg("获取热门推荐数据失败")
print(error)
}
})
// recommendedList = [
// RecommendedBook(isbn: "", title: "从你的全世界路过", author: "张嘉佳", cover: "http://imgsrc.baidu.com/forum/w%3D580/sign=90a6b0a29f16fdfad86cc6e6848e8cea/fd1f4134970a304e1256eb73d3c8a786c8175cc6.jpg"),
// RecommendedBook(isbn: "", title: "雷雨", author: "曹禺", cover: "http://pic9.997788.com/pic_auction/00/08/13/58/au8135818.jpg"),
// RecommendedBook(isbn: "", title: "目送", author: "龙应台", cover: "http://img7.doubanio.com/lpic/s27222202.jpg"),
// RecommendedBook(isbn: "", title: "活着", author: "余华", cover: "http://www.sxdaily.com.cn/NMediaFile/2014/0512/SXRB201405120949000180440088541.jpg"),
// RecommendedBook(isbn: "", title: "野火集", author: "龙应台", cover: "https://img3.doubanio.com/lpic/s4390060.jpg")
// ]
}
func getStarUserList(success: () -> ()) {
User.sharedInstance.getToken({
token in
let manager = AFHTTPSessionManager()
manager.requestSerializer.setValue("Bearer {\(token)}", forHTTPHeaderField: "Authorization")
var fooStarList: [StarUser] = []
manager.GET(ReadAPI.starUserURL, parameters: nil, progress: nil, success: { (task, responseObject) in
// print("staruser")
// print(responseObject)
guard let dict = responseObject as? Dictionary<String, AnyObject> where dict["error_code"] as! Int == -1,
let data = dict["data"] as? Array<Dictionary<String, AnyObject>>
else {
if let dict = responseObject as? Dictionary<String, AnyObject> where dict["error_code"] as! Int == 10000 {
print("removed read token")
NSUserDefaults.standardUserDefaults().removeObjectForKey("readToken")
}
MsgDisplay.showErrorMsg("获取阅读之星数据失败")
return
}
for dic in data {
guard let id = dic["twtid"] as? Int,
let name = dic["twtuname"] as? String,
let avatar = dic["avatar"] as? String,
let reviewCount = dic["review_count"] as? Int
else {
continue
}
fooStarList.append(StarUser(id: id, name: name, avatar: avatar, reviewCount: reviewCount))
//self.starList.append(StarUser(id: id, name: name, avatar: avatar, reviewCount: reviewCount))
}
self.finishFlag.starUserFlag = true
self.starList = fooStarList
success()
}) { (_, error) in
self.finishFlag.starUserFlag = true
MsgDisplay.showErrorMsg("获取阅读之星数据失败")
print(error)
}
})
// starList = [
// StarUser(id: "1", name: "刘德华", avatar: "http://img.jiqie.com/z/0/5/1039_jiqie_com.jpg", reviewCount: 16),
// StarUser(id: "1", name: "猫酱", avatar: "http://img5q.duitang.com/uploads/item/201505/13/20150513092503_f85Qm.thumb.224_0.jpeg", reviewCount: 6),
// StarUser(id: "1", name: "佐助", avatar: "http://pic.wenwen.soso.com/p/20110604/20110604133102-376475389.jpg", reviewCount: 4),
// ]
}
func getHotReviewList(success: () -> ()) {
User.sharedInstance.getToken({
token in
let manager = AFHTTPSessionManager()
manager.requestSerializer.setValue("Bearer {\(token)}", forHTTPHeaderField: "Authorization")
var fooReviewList: [Review] = []
manager.GET(ReadAPI.hotReviewURL, parameters: nil, progress: nil, success: { (task, responseObject) in
// print("hotreview")
// print(responseObject)
guard let dict = responseObject as? Dictionary<String, AnyObject> where dict["error_code"] as! Int == -1,
let data = dict["data"] as? Array<Dictionary<String, AnyObject>>
else {
if let dict = responseObject as? Dictionary<String, AnyObject> where dict["error_code"] as! Int == 10000 {
print("removed read token")
NSUserDefaults.standardUserDefaults().removeObjectForKey("readToken")
}
MsgDisplay.showErrorMsg("获取热门评论数据失败")
return
}
for dic in data {
guard let reviewID = dic["review_id"] as? Int,
let bookID = dic["book_id"] as? Int,
let title = dic["title"] as? String,
let username = dic["user_name"] as? String,
let avatar = dic["avatar"] as? String,
let score = dic["score"] as? Double,
let like = dic["like_count"] as? Int,
let content = dic["content"] as? String,
let updateTime = dic["updated_at"] as? String,
let liked = dic["liked"] as? Bool
else {
continue
}
fooReviewList.append(Review(reviewID: reviewID, bookID: bookID, bookName: title, userName: username, avatarURL: avatar, rating: score, like: like, content: content, updateTime: updateTime, liked: liked))
//self.reviewList.append(Review(bookId: id, username: username, avatar: avatar, score: 5, like: like, content: content))
}
self.finishFlag.hotReviewFlag = true
self.reviewList = fooReviewList
//print(self.reviewList)
success()
}) { (_, error) in
self.finishFlag.hotReviewFlag = true
MsgDisplay.showErrorMsg("获取热门评论数据失败")
print(error)
}
})
}
} | 95f69ec649698ef7e261401abb3b0f1b | 44.943182 | 223 | 0.507503 | false | false | false | false |
iCrany/iOSExample | refs/heads/master | iOSExample/Module/CoreTextExample/View/LayingOutParagraphView.swift | mit | 1 | //
// LayingOutParagraphView.swift
// iOSExample
//
// Created by iCrany on 2017/10/30.
// Copyright © 2017 iCrany. All rights reserved.
//
import Foundation
import UIKit
import CoreText
class LayingOutParagraphView: UIView {
init() {
super.init(frame: .zero)
self.backgroundColor = .white
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: CGRect) {
NSLog("This is LayingOutParagraphView drawRect method, bounds: \(self.bounds)")
super.draw(rect)
// Initialize a graphics context in iOS.
let currentContext: CGContext? = UIGraphicsGetCurrentContext()
guard let context = currentContext else {
NSLog("[Error] \(NSStringFromClass(LayingOutParagraphView.self)) currentContext is nil")
return
}
// Flip the context coordinates, in iOS only.
//TODO: 这里的这个矩阵变换的逻辑还是没有搞清楚
NSLog("[0] CGContext: a: \(context.ctm.a) b: \(context.ctm.b) c: \(context.ctm.c) d: \(context.ctm.d) tx: \(context.ctm.tx) ty: \(context.ctm.ty)")
context.translateBy(x: 0, y: self.bounds.height)
NSLog("[1] CGContext: a: \(context.ctm.a) b: \(context.ctm.b) c: \(context.ctm.c) d: \(context.ctm.d) tx: \(context.ctm.tx) ty: \(context.ctm.ty)")
context.scaleBy(x: 1.0, y: -1.0)
NSLog("[2] CGContext: a: \(context.ctm.a) b: \(context.ctm.b) c: \(context.ctm.c) d: \(context.ctm.d) tx: \(context.ctm.tx) ty: \(context.ctm.ty)")
// Set the text matrix.
NSLog("[0] CGContext.textMatrix: \(context.textMatrix)")
context.textMatrix = CGAffineTransform.identity
NSLog("[1] CGContext.textMatrix: \(context.textMatrix)")
// Create a path which bounds the area where you will be drawing text. The path need not be rectangular
let path: CGMutablePath = CGMutablePath.init()
// In this simple example, initialize a rectangular path.
let bounds: CGRect = CGRect.init(x: 20.0, y: 0.0, width: 200.0, height: self.bounds.size.height - 20.0)
path.addRect(bounds)
// Initialize a string.
let textString: CFString = "Hello, World! I know nothing in the world that has as much power as a word. Sometimes I write one, and I look at it, until it begins to shine." as CFString
// Create a mutable attributed string with a max length of 0.
// The max length is a hint as to how much internal storage to reserve.
// 0 means no hint.
let attrString: CFMutableAttributedString = CFAttributedStringCreateMutable(kCFAllocatorDefault, 0)
// Copy the textString into the newly created attrString
CFAttributedStringReplaceString(attrString, CFRangeMake(0, 0), textString)
// Create a color that will be added as an attribute to the attrString.
let rgbColorSpace: CGColorSpace = CGColorSpaceCreateDeviceRGB()
let components: [CGFloat] = [1.0, 0.0, 0.0, 0.8]
let red: CGColor? = CGColor.init(colorSpace: rgbColorSpace, components: components)
// Set the color of the first 12 chars to red.
CFAttributedStringSetAttribute(attrString, CFRangeMake(0, 12), NSAttributedStringKey.foregroundColor as CFString, red)
// Create the framesetter with the attributed string.
let framesetter: CTFramesetter = CTFramesetterCreateWithAttributedString(attrString)
//Create a frame
let frame: CTFrame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, nil)
// Draw the specified frame in the given context.
CTFrameDraw(frame, context)
}
}
| c4c6faa0719f10cc4f2fbc07d0f47e70 | 42.223529 | 191 | 0.663038 | false | false | false | false |
lixiangzhou/ZZLib | refs/heads/master | Source/ZZExtension/ZZNSExtension/NSNumber+ZZExtension.swift | mit | 1 | //
// NSNumber+ZZExtension.swift
// ZZLib
//
// Created by lixiangzhou on 2017/8/8.
// Copyright © 2017年 lixiangzhou. All rights reserved.
//
import Foundation
public extension NSNumber {
/// 是否Bool值
var zz_isBool: Bool {
return CFBooleanGetTypeID() == CFGetTypeID(self)
}
}
public extension Int {
/// 从低位到高位,从左到右,获取对应索引的数字
///
/// - Parameter idx: 索引
subscript(idx: UInt) -> Int? {
var decimalBase = 1
for _ in 0..<idx {
decimalBase *= 10
}
if decimalBase > self {
return nil
}
return (self / decimalBase) % 10
}
/// 返回整数的长度,不包括正负符号
var zz_length: Int {
return "\(self)".count - (self < 0 ? 1 : 0)
}
}
public extension Double {
/// 四舍六入规则:
/// 四舍六入五考虑,五后非零则进一,五后皆零看奇偶,五前偶舍奇进一
func zz_46Value(point: UInt) -> Double {
let components = self.description.split(separator: ".")
// 判断是否有小数
guard let floatValueString = components.last,
let intValueString = components.first,
floatValueString.count > point else {
return self
}
let startIdx = floatValueString.startIndex
let midIdx = floatValueString.index(startIdx, offsetBy: Int(point))
let beforeStrings = floatValueString[startIdx..<midIdx]
let midString = floatValueString[midIdx].description
// flag = true 表示进1,否则表示舍弃
var flag = true
let five = "5"
// 小数点后面的数字
if midString < five { // 四舍
flag = false
} else if midString > five { // 六入
flag = true
} else { // 五考虑
if Double(floatValueString)! == Double(beforeStrings + midString)! { // 五后皆零看奇偶
let beforeMidString = floatValueString[floatValueString.index(before: midIdx)].description
// 五前偶舍奇进一
flag = Int(beforeMidString)! % 2 != 0
} else { // 五后非零则进一
flag = true
}
}
let pointString = (Int(beforeStrings)! + (flag ? 1 : 0)).description
return Double(intValueString + "." + pointString)!
}
static func zz_46Value(value: Double, point: UInt) -> Double {
return value.zz_46Value(point: point)
}
}
| e522d0d7d609d3f599de290f8af0c20c | 25.931818 | 106 | 0.540928 | false | false | false | false |
L-Zephyr/Drafter | refs/heads/master | Sources/Drafter/Parser/Swift/SwiftClassParser.swift | mit | 1 | //
// SwiftClassParser.swift
// drafterPackageDescription
//
// Created by LZephyr on 2017/11/9.
//
import Foundation
import SwiftyParse
// MARK: - SwiftClassParser
class SwiftClassParser: ConcreteParserType {
var parser: TokenParser<[ClassNode]> {
return classParser.continuous
}
}
// MARK: - class parser
extension SwiftClassParser {
/// 解析单个Class节点
var classParser: TokenParser<ClassNode> {
return classDef
}
/// 解析class和struct的定义
/**
class_definition = 'class' NAME generics_type? super_class? ',' protocols?
*/
var classDef: TokenParser<ClassNode> {
// TODO: 区分struct和class
return curry(ClassNode.init)
<^> pure(true)
<*> token(.accessControl).try => stringify
<*> (token(.cls) <|> token(.structure)) *> token(.name) <* genericType.try => stringify // 类名
<*> superCls.try => stringify // 父类
<*> (token(.comma) *> protocols).try => stringify // 协议列表
<*> anyTokens(inside: token(.leftBrace), and: token(.rightBrace)).map { SwiftMethodParser().parser.run($0) ?? [] } // 方法
}
/// 解析泛型
/**
generics_type = '<' ANY '>'
*/
var genericType: TokenParser<String> {
return anyTokens(inside: token(.leftAngle), and: token(.rightAngle)) *> pure("")
}
/// 父类
/**
super_class = ':' NAME
*/
var superCls: TokenParser<Token> {
return token(.colon) *> token(.name)
}
/// 协议列表
/**
protocols = NAME (',' NAME)*
*/
var protocols: TokenParser<[Token]> {
return token(.name).sepBy(token(.comma))
}
}
| 7a5e416136f52d1657aafe5372f17a7f | 23.910448 | 132 | 0.567406 | false | false | false | false |
creatubbles/ctb-api-swift | refs/heads/develop | CreatubblesAPIClient/Sources/Mapper/DataIncludeMapper/DataIncludeMapper.swift | mit | 1 | //
// DataIncludeMapper.swift
// CreatubblesAPIClient
//
// Copyright (c) 2017 Creatubbles Pte. Ltd.
//
// 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 ObjectMapper
public protocol DataIncludeMapperParser {
func dataIncludeMapper(sender: DataIncludeMapper, mapperFor json: [String: Any], typeString: String) -> Mappable?
func dataIncludeMapper(sender: DataIncludeMapper, objectFor mapper: Mappable, metadata: Metadata?, shouldMap2ndLevelRelationships: Bool) -> Identifiable?
}
public class DataIncludeMapper {
private let metadata: Metadata?
private let includeResponse: Array<Dictionary<String, AnyObject>>
private lazy var mappers: Dictionary<String, Mappable> = self.parseMappers()
private let parser: DataIncludeMapperParser
public init(includeResponse: Array<Dictionary<String, AnyObject>>, metadata: Metadata?, parser: DataIncludeMapperParser = DataIncludeMapperDefaultParser()) {
self.metadata = metadata
self.includeResponse = includeResponse
self.parser = parser
}
fileprivate func parseMappers() -> Dictionary<String, Mappable> {
var mappers = Dictionary<String, Mappable>()
for object in includeResponse {
if let mappedObject = mapperForObject(object) {
mappers[mappedObject.identifier] = mappedObject.mapper
}
}
return mappers
}
func objectWithIdentifier<T: Identifiable>(_ identifier: String, type: T.Type, shouldMap2ndLevelRelationships: Bool = true) -> T? {
guard let mapper = mappers[identifier]
else { return nil }
return parser.dataIncludeMapper(sender: self, objectFor: mapper, metadata: metadata, shouldMap2ndLevelRelationships: shouldMap2ndLevelRelationships) as? T
}
// MARK: - Included response parse
fileprivate func mapperForObject(_ obj: Dictionary<String, AnyObject>) -> (identifier: String, mapper: Mappable)? {
guard let typeString = obj["type"] as? String,
let identifierString = obj["id"] as? String
else { return nil }
let mapper = parser.dataIncludeMapper(sender: self, mapperFor: obj, typeString: typeString)
if (mapper == nil) { Logger.log(.warning, "Unknown typeString: \(typeString)") }
return mapper == nil ? nil : (identifierString, mapper!)
}
}
| 919911b7d9587c1151139e4257a8e592 | 44.6 | 162 | 0.71462 | false | false | false | false |
GYLibrary/A_Y_T | refs/heads/master | GYVideo/Pods/BMPlayer/BMPlayer/Classes/BMPlayerControlView.swift | mit | 1 | //
// BMPlayerControlView.swift
// Pods
//
// Created by BrikerMan on 16/4/29.
//
//
import UIKit
import NVActivityIndicatorView
class BMPlayerControlView: UIView, BMPlayerCustomControlView {
weak var delegate: BMPlayerControlViewDelegate?
var playerTitleLabel : UILabel? { get { return titleLabel } }
var playerCurrentTimeLabel : UILabel? { get { return currentTimeLabel } }
var playerTotalTimeLabel : UILabel? { get { return totalTimeLabel } }
var playerPlayButton : UIButton? { get { return playButton } }
var playerFullScreenButton : UIButton? { get { return fullScreenButton } }
var playerBackButton : UIButton? { get { return backButton } }
var playerReplayButton : UIButton? { get { return centerButton } }
var playerRatioButton : UIButton? { get { return ratioButton }}
var playerTimeSlider : UISlider? { get { return timeSlider } }
var playerProgressView : UIProgressView? { get { return progressView } }
var playerSlowButton : UIButton? { get { return slowButton } }
var playerMirrorButton : UIButton? { get { return mirrorButton } }
var getView: UIView { return self }
/// 主体
var mainMaskView = UIView()
var topMaskView = UIView()
var bottomMaskView = UIView()
var maskImageView = UIImageView()
/// 顶部
var backButton = UIButton(type: UIButtonType.custom)
var titleLabel = UILabel()
var chooseDefitionView = UIView()
var ratioButton = UIButton(type: .custom) //调整视频画面比例按钮 Added by toodoo
/// 底部
var currentTimeLabel = UILabel()
var totalTimeLabel = UILabel()
var timeSlider = BMTimeSlider()
var progressView = UIProgressView()
var playButton = UIButton(type: UIButtonType.custom)
var fullScreenButton = UIButton(type: UIButtonType.custom)
var slowButton = UIButton(type: UIButtonType.custom)
var mirrorButton = UIButton(type: UIButtonType.custom)
/// 中间部分
var loadingIndector = NVActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
var seekToView = UIView()
var seekToViewImage = UIImageView()
var seekToLabel = UILabel()
var centerButton = UIButton(type: UIButtonType.custom)
var videoItems:[BMPlayerItemDefinitionProtocol] = []
var selectedIndex = 0
fileprivate var isSelectecDefitionViewOpened = false
var isFullScreen = false
// MARK: - funcitons
func showPlayerUIComponents() {
topMaskView.alpha = 1.0
bottomMaskView.alpha = 1.0
mainMaskView.backgroundColor = UIColor ( red: 0.0, green: 0.0, blue: 0.0, alpha: 0.4 )
if isFullScreen {
chooseDefitionView.alpha = 1.0
}
}
func hidePlayerUIComponents() {
centerButton.isHidden = true
topMaskView.alpha = 0.0
bottomMaskView.alpha = 0.0
mainMaskView.backgroundColor = UIColor ( red: 0.0, green: 0.0, blue: 0.0, alpha: 0.0 )
chooseDefitionView.snp.updateConstraints { (make) in
make.height.equalTo(35)
}
chooseDefitionView.alpha = 0.0
}
func aspectRatioChanged(_ state:BMPlayerAspectRatio) {
switch state {
case .default:
ratioButton.setBackgroundImage(BMImageResourcePath("BMPlayer_ratio"), for: UIControlState())
break
case .sixteen2NINE:
ratioButton.setBackgroundImage(BMImageResourcePath("BMPlayer_169"), for: UIControlState())
break
case .four2THREE:
ratioButton.setBackgroundImage(BMImageResourcePath("BMPlayer_43"), for: UIControlState())
break
}
}
func updateUI(_ isForFullScreen: Bool) {
isFullScreen = isForFullScreen
if isForFullScreen {
if BMPlayerConf.slowAndMirror {
self.slowButton.isHidden = false
self.mirrorButton.isHidden = false
fullScreenButton.snp.remakeConstraints { (make) in
make.width.equalTo(50)
make.height.equalTo(50)
make.centerY.equalTo(currentTimeLabel)
make.left.equalTo(slowButton.snp.right)
make.right.equalTo(bottomMaskView.snp.right)
}
}
fullScreenButton.setImage(BMImageResourcePath("BMPlayer_portialscreen"), for: UIControlState())
ratioButton.isHidden = false
chooseDefitionView.isHidden = false
if BMPlayerConf.topBarShowInCase.rawValue == 2 {
topMaskView.isHidden = true
} else {
topMaskView.isHidden = false
}
} else {
if BMPlayerConf.topBarShowInCase.rawValue >= 1 {
topMaskView.isHidden = true
} else {
topMaskView.isHidden = false
}
ratioButton.isHidden = true
chooseDefitionView.isHidden = true
self.slowButton.isHidden = true
self.mirrorButton.isHidden = true
fullScreenButton.setImage(BMImageResourcePath("BMPlayer_fullscreen"), for: UIControlState())
fullScreenButton.snp.remakeConstraints { (make) in
make.width.equalTo(50)
make.height.equalTo(50)
make.centerY.equalTo(currentTimeLabel)
make.left.equalTo(totalTimeLabel.snp.right)
make.right.equalTo(bottomMaskView.snp.right)
}
}
if !BMPlayerConf.showScaleChangeButton {
ratioButton.isHidden = true
}
}
func showPlayToTheEndView() {
centerButton.isHidden = false
}
func showLoader() {
loadingIndector.isHidden = false
loadingIndector.startAnimating()
}
func hideLoader() {
loadingIndector.isHidden = true
}
func showSeekToView(_ toSecound: TimeInterval, isAdd: Bool) {
seekToView.isHidden = false
let Min = Int(toSecound / 60)
let Sec = Int(toSecound.truncatingRemainder(dividingBy: 60))
seekToLabel.text = String(format: "%02d:%02d", Min, Sec)
let rotate = isAdd ? 0 : CGFloat(M_PI)
seekToViewImage.transform = CGAffineTransform(rotationAngle: rotate)
}
func hideSeekToView() {
seekToView.isHidden = true
}
func showCoverWithLink(_ cover:String) {
if let url = URL(string: cover) {
DispatchQueue.global(qos: .default).async {
let data = try? Data(contentsOf: url) //make sure your image in this url does exist, otherwise unwrap in a if let check
DispatchQueue.main.async(execute: {
if let data = data {
self.maskImageView.image = UIImage(data: data)
} else {
self.maskImageView.image = nil
}
self.hideLoader()
});
}
}
}
func hideCoverImageView() {
self.maskImageView.isHidden = true
}
func prepareChooseDefinitionView(_ items:[BMPlayerItemDefinitionProtocol], index: Int) {
self.videoItems = items
for item in chooseDefitionView.subviews {
item.removeFromSuperview()
}
for i in 0..<items.count {
let button = BMPlayerClearityChooseButton()
if i == 0 {
button.tag = index
} else if i <= index {
button.tag = i - 1
} else {
button.tag = i
}
button.setTitle("\(items[button.tag].definitionName)", for: UIControlState())
chooseDefitionView.addSubview(button)
button.addTarget(self, action: #selector(self.onDefinitionSelected(_:)), for: UIControlEvents.touchUpInside)
button.snp.makeConstraints({ (make) in
make.top.equalTo(chooseDefitionView.snp.top).offset(35 * i)
make.width.equalTo(50)
make.height.equalTo(25)
make.centerX.equalTo(chooseDefitionView)
})
if items.count == 1 {
button.isEnabled = false
}
}
}
@objc fileprivate func onDefinitionSelected(_ button:UIButton) {
let height = isSelectecDefitionViewOpened ? 35 : videoItems.count * 40
chooseDefitionView.snp.updateConstraints { (make) in
make.height.equalTo(height)
}
UIView.animate(withDuration: 0.3, animations: {
self.layoutIfNeeded()
})
isSelectecDefitionViewOpened = !isSelectecDefitionViewOpened
if selectedIndex != button.tag {
selectedIndex = button.tag
delegate?.controlViewDidChooseDefition(button.tag)
}
prepareChooseDefinitionView(videoItems, index: selectedIndex)
}
@objc fileprivate func onReplyButtonPressed() {
centerButton.isHidden = true
delegate?.controlViewDidPressOnReply()
}
// MARK: - 初始化
override init(frame: CGRect) {
super.init(frame: frame)
initUI()
addSnapKitConstraint()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initUI()
addSnapKitConstraint()
}
fileprivate func initUI() {
// 主体
addSubview(mainMaskView)
mainMaskView.addSubview(topMaskView)
mainMaskView.addSubview(bottomMaskView)
mainMaskView.insertSubview(maskImageView, at: 0)
mainMaskView.backgroundColor = UIColor ( red: 0.0, green: 0.0, blue: 0.0, alpha: 0.4 )
// 顶部
topMaskView.addSubview(backButton)
topMaskView.addSubview(titleLabel)
topMaskView.addSubview(ratioButton)
self.addSubview(chooseDefitionView)
backButton.setImage(BMImageResourcePath("BMPlayer_back"), for: UIControlState())
ratioButton.setBackgroundImage(BMImageResourcePath("BMPlayer_ratio"), for: UIControlState())
titleLabel.textColor = UIColor.white
titleLabel.text = "Hello World"
titleLabel.font = UIFont.systemFont(ofSize: 16)
chooseDefitionView.clipsToBounds = true
// 底部
bottomMaskView.addSubview(playButton)
bottomMaskView.addSubview(currentTimeLabel)
bottomMaskView.addSubview(totalTimeLabel)
bottomMaskView.addSubview(progressView)
bottomMaskView.addSubview(timeSlider)
bottomMaskView.addSubview(fullScreenButton)
bottomMaskView.addSubview(mirrorButton)
bottomMaskView.addSubview(slowButton)
playButton.setImage(BMImageResourcePath("BMPlayer_play"), for: UIControlState())
playButton.setImage(BMImageResourcePath("BMPlayer_pause"), for: UIControlState.selected)
currentTimeLabel.textColor = UIColor.white
currentTimeLabel.font = UIFont.systemFont(ofSize: 12)
currentTimeLabel.text = "00:00"
currentTimeLabel.textAlignment = NSTextAlignment.center
totalTimeLabel.textColor = UIColor.white
totalTimeLabel.font = UIFont.systemFont(ofSize: 12)
totalTimeLabel.text = "00:00"
totalTimeLabel.textAlignment = NSTextAlignment.center
timeSlider.maximumValue = 1.0
timeSlider.minimumValue = 0.0
timeSlider.value = 0.0
timeSlider.setThumbImage(BMImageResourcePath("BMPlayer_slider_thumb"), for: UIControlState())
timeSlider.maximumTrackTintColor = UIColor.clear
timeSlider.minimumTrackTintColor = BMPlayerConf.tintColor
progressView.tintColor = UIColor ( red: 1.0, green: 1.0, blue: 1.0, alpha: 0.6 )
progressView.trackTintColor = UIColor ( red: 1.0, green: 1.0, blue: 1.0, alpha: 0.3 )
fullScreenButton.setImage(BMImageResourcePath("BMPlayer_fullscreen"), for: UIControlState())
mirrorButton.layer.borderWidth = 1
mirrorButton.layer.borderColor = UIColor(red: 204.0 / 255.0, green: 204.0 / 255.0, blue: 204.0 / 255.0, alpha: 1.0).cgColor
mirrorButton.layer.cornerRadius = 2.0
mirrorButton.setTitle("镜像", for: UIControlState())
mirrorButton.titleLabel?.font = UIFont.systemFont(ofSize: 14)
mirrorButton.isHidden = true
slowButton.layer.borderWidth = 1
slowButton.layer.borderColor = UIColor(red: 204.0 / 255.0, green: 204.0 / 255.0, blue: 204.0 / 255.0, alpha: 1.0).cgColor
slowButton.layer.cornerRadius = 2.0
slowButton.setTitle("慢放", for: UIControlState())
slowButton.titleLabel?.font = UIFont.systemFont(ofSize: 14)
mirrorButton.isHidden = true
// 中间
mainMaskView.addSubview(loadingIndector)
// loadingIndector.hidesWhenStopped = true
loadingIndector.type = BMPlayerConf.loaderType
loadingIndector.color = BMPlayerConf.tintColor
// 滑动时间显示
addSubview(seekToView)
seekToView.addSubview(seekToViewImage)
seekToView.addSubview(seekToLabel)
seekToLabel.font = UIFont.systemFont(ofSize: 13)
seekToLabel.textColor = UIColor ( red: 0.9098, green: 0.9098, blue: 0.9098, alpha: 1.0 )
seekToView.backgroundColor = UIColor ( red: 0.0, green: 0.0, blue: 0.0, alpha: 0.7 )
seekToView.layer.cornerRadius = 4
seekToView.layer.masksToBounds = true
seekToView.isHidden = true
seekToViewImage.image = BMImageResourcePath("BMPlayer_seek_to_image")
self.addSubview(centerButton)
centerButton.isHidden = true
centerButton.setImage(BMImageResourcePath("BMPlayer_replay"), for: UIControlState())
centerButton.addTarget(self, action: #selector(self.onReplyButtonPressed), for: UIControlEvents.touchUpInside)
}
fileprivate func addSnapKitConstraint() {
// 主体
mainMaskView.snp.makeConstraints { (make) in
make.edges.equalTo(self)
}
maskImageView.snp.makeConstraints { (make) in
make.edges.equalTo(mainMaskView)
}
topMaskView.snp.makeConstraints { (make) in
make.top.left.right.equalTo(mainMaskView)
make.height.equalTo(65)
}
bottomMaskView.snp.makeConstraints { (make) in
make.bottom.left.right.equalTo(mainMaskView)
make.height.equalTo(50)
}
// 顶部
backButton.snp.makeConstraints { (make) in
make.width.height.equalTo(50)
make.left.bottom.equalTo(topMaskView)
}
titleLabel.snp.makeConstraints { (make) in
make.left.equalTo(backButton.snp.right)
make.centerY.equalTo(backButton)
}
ratioButton.snp.makeConstraints { (make) in
make.right.equalTo(topMaskView.snp.right).offset(-20)
make.top.equalTo(titleLabel.snp.top).offset(-4)
make.width.equalTo(50)
make.height.equalTo(25)
}
chooseDefitionView.snp.makeConstraints { (make) in
if BMPlayerConf.showScaleChangeButton {
make.right.equalTo(ratioButton.snp.left).offset(-10)
} else {
make.right.equalTo(topMaskView.snp.right).offset(-20)
}
make.top.equalTo(titleLabel.snp.top).offset(-4)
make.width.equalTo(60)
make.height.equalTo(30)
}
// 底部
playButton.snp.makeConstraints { (make) in
make.width.equalTo(50)
make.height.equalTo(50)
make.left.bottom.equalTo(bottomMaskView)
}
currentTimeLabel.snp.makeConstraints { (make) in
make.left.equalTo(playButton.snp.right)
make.centerY.equalTo(playButton)
make.width.equalTo(40)
}
timeSlider.snp.makeConstraints { (make) in
make.centerY.equalTo(currentTimeLabel)
make.left.equalTo(currentTimeLabel.snp.right).offset(10).priority(750)
make.height.equalTo(30)
}
progressView.snp.makeConstraints { (make) in
make.centerY.left.right.equalTo(timeSlider)
make.height.equalTo(2)
}
totalTimeLabel.snp.makeConstraints { (make) in
make.centerY.equalTo(currentTimeLabel)
make.left.equalTo(timeSlider.snp.right).offset(5)
make.width.equalTo(40)
}
mirrorButton.snp.makeConstraints { (make) in
make.width.equalTo(50)
make.height.equalTo(30)
make.left.equalTo(totalTimeLabel.snp.right).offset(10)
make.centerY.equalTo(currentTimeLabel)
}
slowButton.snp.makeConstraints { (make) in
make.width.equalTo(50)
make.height.equalTo(30)
make.left.equalTo(mirrorButton.snp.right).offset(10)
make.centerY.equalTo(currentTimeLabel)
}
fullScreenButton.snp.makeConstraints { (make) in
make.width.equalTo(50)
make.height.equalTo(50)
make.centerY.equalTo(currentTimeLabel)
make.left.equalTo(totalTimeLabel.snp.right)
make.right.equalTo(bottomMaskView.snp.right)
}
// 中间
loadingIndector.snp.makeConstraints { (make) in
make.centerX.equalTo(mainMaskView.snp.centerX).offset(0)
make.centerY.equalTo(mainMaskView.snp.centerY).offset(0)
}
seekToView.snp.makeConstraints { (make) in
make.center.equalTo(self.snp.center)
make.width.equalTo(100)
make.height.equalTo(40)
}
seekToViewImage.snp.makeConstraints { (make) in
make.left.equalTo(seekToView.snp.left).offset(15)
make.centerY.equalTo(seekToView.snp.centerY)
make.height.equalTo(15)
make.width.equalTo(25)
}
seekToLabel.snp.makeConstraints { (make) in
make.left.equalTo(seekToViewImage.snp.right).offset(10)
make.centerY.equalTo(seekToView.snp.centerY)
}
centerButton.snp.makeConstraints { (make) in
make.centerX.equalTo(mainMaskView.snp.centerX)
make.centerY.equalTo(mainMaskView.snp.centerY)
make.width.height.equalTo(50)
}
}
fileprivate func BMImageResourcePath(_ fileName: String) -> UIImage? {
let bundle = Bundle(for: self.classForCoder)
let image = UIImage(named: fileName, in: bundle, compatibleWith: nil)
return image
// let podBundle = Bundle(for: self.classForCoder)
// if let bundleURL = podBundle.url(forResource: "BMPlayer", withExtension: "bundle") {
// if let bundle = Bundle(url: bundleURL) {
// let image = UIImage(named: fileName, in: bundle, compatibleWith: nil)
// return image
// }else {
// assertionFailure("Could not load the bundle")
// }
// }else {
// assertionFailure("Could not create a path to the bundle")
// }
// return nil
}
}
open class BMTimeSlider: UISlider {
override open func trackRect(forBounds bounds: CGRect) -> CGRect {
let trackHeigt:CGFloat = 2
let position = CGPoint(x: 0 , y: 14)
let customBounds = CGRect(origin: position, size: CGSize(width: bounds.size.width, height: trackHeigt))
super.trackRect(forBounds: customBounds)
return customBounds
}
override open func thumbRect(forBounds bounds: CGRect, trackRect rect: CGRect, value: Float) -> CGRect {
let rect = super.thumbRect(forBounds: bounds, trackRect: rect, value: value)
let newx = rect.origin.x - 10
let newRect = CGRect(x: newx, y: 0, width: 30, height: 30)
return newRect
}
}
| 2f08bf6cf37daccd7eea6d92aa8abe2b | 36.476277 | 135 | 0.596144 | false | false | false | false |
remobjects/Marzipan | refs/heads/master | CodeGen4/CGCPlusPlusCodeGenerator.swift | bsd-3-clause | 1 | public enum CGCPlusPlusCodeGeneratorDialect {
case Standard
case CPlusPlusBuilder //C++Builder
case VCPlusPlus //MS Visual C++
}
//
// Abstract base implementation for C++. Inherited by specific .cpp and .h Generators
//
public __abstract class CGCPlusPlusCodeGenerator : CGCStyleCodeGenerator {
public var Dialect: CGCPlusPlusCodeGeneratorDialect = .Standard
func isStandard() -> Boolean{
return Dialect == CGCPlusPlusCodeGeneratorDialect.Standard;
}
func isCBuilder() -> Boolean{
return Dialect == CGCPlusPlusCodeGeneratorDialect.CPlusPlusBuilder;
}
func isVC() -> Boolean{
return Dialect == CGCPlusPlusCodeGeneratorDialect.VCPlusPlus;
}
public init() {
super.init()
// from http://en.cppreference.com/w/cpp/keyword
keywords = ["alignas", "alignof", "and", "and_eq", "asm", "auto", "bitand", "bitor", "bool", "break",
"case", "catch", "char", "char16_t", "char32_t", "class", "compl", "concept", "const",
"const_cast", "constexpr", "continue", "decltype", "default", "define", "defined", "delete",
"do", "double", "dynamic_cast", "elif", "else", "endif", "enum", "error", "explicit", "export",
"extern", "false", "final", "float", "for", "friend", "goto", "if", "ifdef", "ifndef", "include",
"inline", "int", "line", "long", "mutable", "namespace", "new", "noexcept", "not", "not_eq",
"nullptr", "operator", "or", "or_eq", "override", "pragma", "private", "protected", "public",
"register", "reinterpret_cast", "requires", "return", "short", "signed", "sizeof", "static",
"static_assert", "static_cast", "struct", "switch", "template", "this", "thread_local", "throw",
"true", "try", "typedef", "typeid", "typename", "undef", "union", "unsigned", "using", "virtual",
"void", "volatile", "wchar_t", "while", "xor", "xor_eq"].ToList() as! List<String>;
// // c++Builder keywords
// keywords = ["__asm", "__automated", "__cdecl", "__classid", "__classmethod", "__closure", "__declspec",
// "__delphirtti", "__dispid", "__except", "__export", "__fastcall", "__finally", "__import",
// "__inline", "__int16", "__int32", "__int64", "__int8", "__msfastcall", "__msreturn",
// "__pascal", "__property", "__published", "__rtti", "__stdcall", "__thread", "__try", "_asm",
// "_Bool", "_cdecl", "_Complex", "_export", "_fastcall", "_Imaginary", "_import", "_pascal",
// "_stdcall", "alignas", "alignof", "and", "and_eq", "asm", "auto", "axiom", "bitand", "bitor",
// "bool", "break", "case", "catch", "cdecl", "char", "char16_t", "char32_t", "class", "compl",
// "concept", "concept_map", "const", "const_cast", "constexpr", "continue", "decltype", "default",
// "define", "defined", "delete", "deprecated", "do", "double", "Dynamic cast", "dynamic_cast",
// "elif", "else", "endif", "enum", "error", "explicit", "export", "extern", "false", "final",
// "float", "for", "friend", "goto", "if", "ifdef", "ifndef", "include", "inline", "int",
// "late_check", "line", "long", "mutable", "namespace", "new", "noexcept", "noreturn",
// "not", "not_eq", "nullptr", "operator", "or", "or_eq", "override", "pascal", "pragma",
// "private", "protected", "public", "register", "reinterpret_cast", "requires", "restrict",
// "return", "short", "signed", "sizeof", "static", "static_assert", "static_cast", "struct",
// "switch", "template", "this", "thread_local", "throw", "true", "try", "typedef", "typeid",
// "typename", "typeof", "undef", "union", "unsigned", "using", "uuidof", "virtual", "void",
// "volatile", "wchar_t", "while", "xor", "xor_eq"].ToList() as! List<String>;
}
public convenience init(dialect: CGCPlusPlusCodeGeneratorDialect) {
init()
Dialect = dialect
}
override func generateAll() {
// overriden in .h and .cpp
}
//
// Statements
//
// in C-styleCG Base class
/*
override func generateBeginEndStatement(_ statement: CGBeginEndBlockStatement) {
// handled in base
}
*/
/*
override func generateIfElseStatement(_ statement: CGIfThenElseStatement) {
// handled in base
}
*/
/*
override func generateForToLoopStatement(_ statement: CGForToLoopStatement) {
// handled in base
}
*/
override func generateForEachLoopStatement(_ statement: CGForEachLoopStatement) {
assert(false, "generateForEachLoopStatement is not supported in C++")
}
/*
override func generateWhileDoLoopStatement(_ statement: CGWhileDoLoopStatement) {
// handled in base
}
*/
/*
override func generateDoWhileLoopStatement(_ statement: CGDoWhileLoopStatement) {
// handled in base
}
*/
/*
override func generateInfiniteLoopStatement(_ statement: CGInfiniteLoopStatement) {
// handled in base
}
*/
/*
override func generateSwitchStatement(_ statement: CGSwitchStatement) {
// handled in base
}
*/
override func generateLockingStatement(_ statement: CGLockingStatement) {
assert(false, "generateLockingStatement is not supported in C++")
}
override func generateUsingStatement(_ statement: CGUsingStatement) {
assert(false, "generateUsingStatement is not supported in C++")
}
override func generateAutoReleasePoolStatement(_ statement: CGAutoReleasePoolStatement) {
assert(false, "generateAutoReleasePoolStatement is not supported in C++")
}
override func generateTryFinallyCatchStatement(_ statement: CGTryFinallyCatchStatement) {
if isStandard() {
if let finallyStatements = statement.FinallyStatements, finallyStatements.Count > 0 {
assert(false, "FinallyStatements in generateTryFinallyCatchStatement is not supported in Standard, except in CPlusPlusBuilder and VCPlusPlus");
}
}
// __try {
// try {}
// body
// catch {}
// }
// __finally {}
if let finallyStatements = statement.FinallyStatements, finallyStatements.Count > 0 {
AppendLine("__try")
}
if let catchBlocks = statement.CatchBlocks, catchBlocks.Count > 0 {
AppendLine("try")
}
AppendLine("{")
incIndent()
generateStatements(statement.Statements)
decIndent()
AppendLine("}")
if let catchBlocks = statement.CatchBlocks, catchBlocks.Count > 0 {
for b in catchBlocks {
if let name = b.Name, let type = b.`Type` {
Append("catch (")
generateTypeReference(type)
Append(" ")
generateIdentifier(name)
AppendLine(")")
} else {
AppendLine("catch (...)")
}
AppendLine("{")
incIndent()
generateStatements(b.Statements)
decIndent()
AppendLine("}")
}
}
if let finallyStatements = statement.FinallyStatements, finallyStatements.Count > 0 {
AppendLine("__finally")
AppendLine("{")
incIndent()
generateStatements(finallyStatements)
decIndent()
AppendLine("}")
}
}
/*
override func generateReturnStatement(_ statement: CGReturnStatement) {
// handled in base
}
*/
override func generateThrowStatement(_ statement: CGThrowStatement) {
if let value = statement.Exception {
Append("throw ")
generateExpression(value)
AppendLine(";")
} else {
AppendLine("throw;")
}
}
/*
override func generateBreakStatement(_ statement: CGBreakStatement) {
// handled in base
}
*/
/*
override func generateContinueStatement(_ statement: CGContinueStatement) {
// handled in base
}
*/
override func generateVariableDeclarationStatement(_ statement: CGVariableDeclarationStatement) {
if statement.Constant {
Append("const ");
}
if let type = statement.`Type` {
generateTypeReference(type)
Append(" ")
} else {
// Append("id ")
}
generateIdentifier(statement.Name)
if let value = statement.Value {
Append(" = ")
generateExpression(value)
}
AppendLine(";")
}
/*
override func generateAssignmentStatement(_ statement: CGAssignmentStatement) {
// handled in base
}
*/
override func generateConstructorCallStatement(_ statement: CGConstructorCallStatement) {
// empty
}
//
// Expressions
//
/*
override func generateNamedIdentifierExpression(_ expression: CGNamedIdentifierExpression) {
// handled in base
}
*/
/*
override func generateAssignedExpression(_ expression: CGAssignedExpression) {
// handled in base
}
*/
/*
override func generateSizeOfExpression(_ expression: CGSizeOfExpression) {
// handled in base
}
*/
override func generateTypeOfExpression(_ expression: CGTypeOfExpression) {
Append("[")
generateExpression(expression.Expression, ignoreNullability: true)
// if let typeReferenceExpression = expression.Expression as? CGTypeReferenceExpression {
// generateTypeReference(typeReferenceExpression.`Type`, ignoreNullability: true)
// } else {
// generateExpression(expression.Expression)
// }
Append(" class]")
}
override func generateDefaultExpression(_ expression: CGDefaultExpression) {
assert(false, "generateDefaultExpression is not supported in Objective-C")
}
override func generateSelectorExpression(_ expression: CGSelectorExpression) {
Append("@selector(\(expression.Name))")
}
override func generateTypeCastExpression(_ cast: CGTypeCastExpression) {
if cast.ThrowsException {
//dynamic_cast<MyClass *>(ptr)
Append("dynamic_cast<")
generateTypeReference(cast.TargetType)
Append(">(")
generateExpression(cast.Expression)
Append(")")
} else {
// (MyClass *)ptr
Append("(")
generateTypeReference(cast.TargetType)
Append(")")
generateExpression(cast.Expression)
}
}
override func generateInheritedExpression(_ expression: CGInheritedExpression) {
Append("inherited")
}
override func generateSelfExpression(_ expression: CGSelfExpression) {
Append("this")
}
override func generateNilExpression(_ expression: CGNilExpression) {
Append("NULL")
}
override func generatePropertyValueExpression(_ expression: CGPropertyValueExpression) {
Append(CGPropertyDefinition.MAGIC_VALUE_PARAMETER_NAME)
}
override func generateAwaitExpression(_ expression: CGAwaitExpression) {
if isVC() {
Append("__await ")
generateExpression(expression.Expression)
} else {
assert(false, "generateAwaitExpression is not supported in C++")
}
}
override func generateAnonymousMethodExpression(_ expression: CGAnonymousMethodExpression) {
// todo
}
override func generateAnonymousTypeExpression(_ expression: CGAnonymousTypeExpression) {
// todo
}
/*
override func generatePointerDereferenceExpression(_ expression: CGPointerDereferenceExpression) {
// handled in base
}
*/
/*
override func generateUnaryOperatorExpression(_ expression: CGUnaryOperatorExpression) {
// handled in base
}
*/
/*
override func generateBinaryOperatorExpression(_ expression: CGBinaryOperatorExpression) {
// handled in base
}
*/
/*
override func generateUnaryOperator(_ `operator`: CGUnaryOperatorKind) {
// handled in base
}
*/
/*
override func generateBinaryOperator(_ `operator`: CGBinaryOperatorKind) {
// handled in base
}
*/
/*
override func generateIfThenElseExpression(_ expression: CGIfThenElseExpression) {
// handled in base
}
*/
/*
override func generateArrayElementAccessExpression(_ expression: CGArrayElementAccessExpression) {
// handled in base
}
*/
internal func cppGenerateCallSiteForExpression(_ expression: CGMemberAccessExpression, forceSelf: Boolean = false) {
if let callSite = expression.CallSite {
if let typeReferenceExpression = expression.CallSite as? CGTypeReferenceExpression {
generateTypeReference(typeReferenceExpression.`Type`, ignoreNullability: true)
} else {
generateExpression(callSite)
}
} else if forceSelf {
generateExpression(CGSelfExpression.`Self`)
}
}
func cppGenerateCallParameters(_ parameters: List<CGCallParameter>) {
for p in 0 ..< parameters.Count {
let param = parameters[p]
if p > 0 {
Append(", ")
}
switch param.Modifier {
case .Var: Append(" &")
case .Out: Append(" &")
default:
}
generateExpression(param.Value)
}
}
func cppGenerateAttributeParameters(_ parameters: List<CGCallParameter>) {
// not needed
}
func cppGenerateDefinitionParameters(_ parameters: List<CGParameterDefinition>, header: Boolean) {
helpGenerateCommaSeparatedList(parameters) { param in
switch param.Modifier {
case .Const: self.Append("const ")
case .Var: self.Append("/* var */ ")
case .Out: self.Append("/* out */ ")
default:
}
if let type = param.`Type` {
self.generateTypeReference(type)
} else {
self.assert("CGParameterDefinition needs a type, for Objective-C")
}
switch param.Modifier {
case .Var: self.Append(" &")
case .Out: self.Append(" &")
default:
}
self.Append(" ")
self.generateIdentifier(param.Name)
if header {
if let pv = param.DefaultValue, pv != nil {
self.Append(" = ")
self.generateExpression(pv)
}
}
}
}
func cppGenerateAncestorList(_ type: CGClassOrStructTypeDefinition) {
if type.Ancestors.Count > 0 {
Append(" : ")
cppGenerateTypeVisibilityPrefix(type.Visibility)
for a in 0 ..< type.Ancestors.Count {
if let ancestor = type.Ancestors[a] {
if a > 0 {
Append(", ")
}
generateTypeReference(ancestor, ignoreNullability: true)
}
}
}
if type.ImplementedInterfaces.Count > 0 {
for a in 0 ..< type.ImplementedInterfaces.Count {
if let interface = type.ImplementedInterfaces[a] {
Append(", ")
generateTypeReference(interface, ignoreNullability: true)
}
}
}
}
func cppGenerateAddressing(_ expression: CGMemberAccessExpression) {
if (expression.CallSite != nil) {
switch expression.CallSiteKind{
case .Instance: Append(".");
case .Reference: Append("->");
case .Static: Append("::");
case .Unspecified:
if let typeref = expression.CallSite as? CGTypeReferenceExpression {
Append("::")
}
else if let typeref = expression.CallSite as? CGInheritedExpression {
Append("::")
}
else if let typeref = expression.CallSite as? CGSelfExpression {
Append(".")
}
else {
Append(".")
}
}
}
}
override func generateFieldAccessExpression(_ expression: CGFieldAccessExpression) {
if expression.CallSite != nil {
cppGenerateCallSiteForExpression(expression, forceSelf: true)
cppGenerateAddressing(expression);
}
generateIdentifier(expression.Name)
}
override func generateMethodCallExpression(_ method: CGMethodCallExpression) {
if method.CallSite != nil {
cppGenerateCallSiteForExpression(method, forceSelf: true)
cppGenerateAddressing(method)
}
Append(method.Name)
Append("(")
cppGenerateCallParameters(method.Parameters)
Append(")")
}
override func generateNewInstanceExpression(_ expression: CGNewInstanceExpression) {
Append("new ")
generateExpression(expression.`Type`, ignoreNullability: true)
Append("(")
cppGenerateCallParameters(expression.Parameters)
Append(")")
}
override func generateDestroyInstanceExpression(_ expression: CGDestroyInstanceExpression) {
//#hint cover 'delete [] a' case
// problem with deleting arrays:
// int * a = new int[500];
// delete [] a;
Append("delete ");
generateExpression(expression.Instance);
}
override func generatePropertyAccessExpression(_ property: CGPropertyAccessExpression) {
cppGenerateCallSiteForExpression(property, forceSelf: false)
cppGenerateAddressing(property)
Append(property.Name)
if let params = property.Parameters, params.Count > 0 {
Append("[")
cppGenerateCallParameters(property.Parameters)
Append("]")
}
}
override func generateEnumValueAccessExpression(_ expression: CGEnumValueAccessExpression) {
// don't prefix with typename in cpp
generateIdentifier(expression.ValueName)
}
/*
override func generateStringLiteralExpression(_ expression: CGStringLiteralExpression) {
// handled in base
}
*/
/*
override func generateCharacterLiteralExpression(_ expression: CGCharacterLiteralExpression) {
// handled in base
}
*/
/*
override func generateIntegerLiteralExpression(_ expression: CGIntegerLiteralExpression) {
// handled in base
}
*/
/*
override func generateFloatLiteralExpression(_ literalExpression: CGFloatLiteralExpression) {
// handled in base
}
*/
override func generateArrayLiteralExpression(_ array: CGArrayLiteralExpression) {
if isCBuilder() {
if array.ArrayKind == .Dynamic {
var isOpenArray = false
if let ltype = array.ElementType {
// open array
isOpenArray = true;
Append("OPENARRAY(")
generateTypeReference(ltype)
Append(", (")
}
else {
// array of const
Append("ARRAYOFCONST((")
}
helpGenerateCommaSeparatedList(array.Elements) { e in
self.generateExpression(e)
}
Append(")")
Append(")")
return;
}
}
Append("[")
helpGenerateCommaSeparatedList(array.Elements) { e in
self.generateExpression(e)
}
Append("]")
}
override func generateSetLiteralExpression(_ expression: CGSetLiteralExpression) {
if let type = expression.ElementType {
generateTypeReference(type, ignoreNullability: true)
}
Append("()")
if expression.Elements.Count > 0 {
Append(" << ")
helpGenerateCommaSeparatedList(expression.Elements) { e in
self.generateExpression(e)
}
}
}
override func generateDictionaryExpression(_ dictionary: CGDictionaryLiteralExpression) {
assert(dictionary.Keys.Count == dictionary.Values.Count, "Number of keys and values in Dictionary doesn't match.")
Append("{")
for e in 0 ..< dictionary.Keys.Count {
if e > 0 {
Append(", ")
}
generateExpression(dictionary.Keys[e])
Append(": ")
generateExpression(dictionary.Values[e])
}
Append("}")
}
/*
override func generateTupleExpression(_ expression: CGTupleLiteralExpression) {
// default handled in base
}
*/
// override func generateSetTypeReference(_ setType: CGSetTypeReference) {
// assert(false, "generateSetTypeReference is not supported in C++")
// }
//
// override func generateSequenceTypeReference(_ sequence: CGSequenceTypeReference) {
// assert(false, "generateSequenceTypeReference is not supported in C++")
// }
//
// Type Definitions
//
override func generateAttribute(_ attribute: CGAttribute, inline: Boolean) {
// no-op, we dont support attribtes in Objective-C
}
override func generateAliasType(_ type: CGTypeAliasDefinition) {
}
override func generateBlockType(_ type: CGBlockTypeDefinition) {
}
override func generateEnumType(_ type: CGEnumTypeDefinition) {
// overriden in H
}
override func generateClassTypeStart(_ type: CGClassTypeDefinition) {
// overriden and H
}
override func generateClassTypeEnd(_ type: CGClassTypeDefinition) {
AppendLine()
}
// func cppGenerateFields(_ type: CGTypeDefinition) {
// for m in type.Members {
// if let property = m as? CGPropertyDefinition {
// if property.GetStatements == nil && property.SetStatements == nil && property.GetExpression == nil && property.SetExpression == nil {
// if let type = property.`Type` {
// generateTypeReference(type)
// Append(" ")
// } else {
// Append("id ")
// }
// Append("__p_")
// generateIdentifier(property.Name, escaped: false)
// AppendLine(";")
// }
// } else if let field = m as? CGFieldDefinition {
// if let type = field.`Type` {
// generateTypeReference(type)
// Append(" ")
// } else {
// Append("id ")
// }
// generateIdentifier(field.Name)
// AppendLine(";")
// }
// }
// }
override func generateStructTypeStart(_ type: CGStructTypeDefinition) {
// overriden in H
}
override func generateStructTypeEnd(_ type: CGStructTypeDefinition) {
// overriden in H
}
override func generateInterfaceTypeStart(_ type: CGInterfaceTypeDefinition) {
// overriden in H
}
override func generateInterfaceTypeEnd(_ type: CGInterfaceTypeDefinition) {
// overriden in H
}
override func generateExtensionTypeStart(_ type: CGExtensionTypeDefinition) {
// overriden in M and H
}
override func generateExtensionTypeEnd(_ type: CGExtensionTypeDefinition) {
AppendLine("@end")
}
//
// Type Members
//
func cppGenerateCallingConversion(_ callingConvention: CGCallingConventionKind){
if isCBuilder() {
switch callingConvention {
case .CDecl: Append("__cdecl ")
case .Pascal: Append("__pascal ")
case .FastCall: Append("__msfastcall ")
case .StdCall: Append("__stdcall ")
case .Register: Append("__fastcall ")
default:
}
}
else if isVC(){
switch callingConvention {
case .CDecl: Append("__cdecl ")
case .ClrCall: Append("__clrcall ")
case .StdCall: Append("__stdcall ")
case .FastCall: Append("__fastcall ")
case .ThisCall: Append("__thiscall ")
case .VectorCall: Append("__vectorcall ")
default:
}
}
else if isStandard() {
// only cdecl is used be default;
}
}
func cppGenerateMethodDefinitionHeader(_ method: CGMethodLikeMemberDefinition, type: CGTypeDefinition, header: Boolean) {
let isCtor = (method as? CGConstructorDefinition) != nil
let isDtor = (method as? CGDestructorDefinition) != nil
let isInterface = (type as? CGInterfaceTypeDefinition) != nil
let isGlobal = type is CGGlobalTypeDefinition
if header {
if method.Static {
if isCBuilder() {
Append("__classmethod ")
}
else
{
Append("static ")
}
}
}
if header {
if isInterface && isCBuilder(){
Append("virtual ");
}
else if !isGlobal {
// virtuality isn't supported for globals
switch (method.Virtuality) {
case .Virtual: Append("virtual ");
case .Override: Append("virtual ");
default: // ????
}
if method.Reintroduced {
Append(" HIDESBASE ")
}
}
}
if !isCtor && !isDtor{
// ctor&dtor have no result
if let returnType = method.ReturnType {
generateTypeReference(returnType)
} else {
Append("void")
}
Append(" ")
}
if let conversion = method.CallingConvention {
cppGenerateCallingConversion(conversion)
}
if isCtor {
if !header {
if let namespace = currentUnit.Namespace {
generateIdentifier(namespace.Name)
Append("::")
}
generateIdentifier(type.Name)
Append("::")
}
if let lname = method.Name, lname != "" {
generateIdentifier(uppercaseFirstLetter(lname))
}
else {
generateIdentifier(uppercaseFirstLetter(type.Name))
}
} else if isDtor {
if !header {
if let namespace = currentUnit.Namespace {
generateIdentifier(namespace.Name)
Append("::")
}
}
Append("~")
generateIdentifier(uppercaseFirstLetter(type.Name));
} else {
if !header {
if !(isGlobal && (method.Visibility == .Private)) {
if let namespace = currentUnit.Namespace {
generateIdentifier(namespace.Name)
Append("::")
}
}
if !isGlobal {
generateIdentifier(type.Name)
Append("::")
}
}
generateIdentifier(method.Name)
}
Append("(")
cppGenerateDefinitionParameters(method.Parameters, header: header)
Append(")")
if header && isInterface {
Append(" = 0")
}
if !header && isCtor {
if let classtype = type as? CGClassOrStructTypeDefinition {
if classtype.Ancestors.Count > 0 {
AppendLine();
incIndent()
Append(": ")
generateTypeReference(classtype.Ancestors[0],ignoreNullability: true)
Append("(")
var processed = false;
for s in method.Statements {
if let ctorCall = s as? CGConstructorCallStatement {
cppGenerateCallParameters(ctorCall.Parameters);
processed = true;
break
}
}
if !processed{
helpGenerateCommaSeparatedList(method.Parameters) { p in
self.generateIdentifier(p.Name)
}
/* for var p = 0; p < method.Parameters.Count; p++ {
let param = method.Parameters[p]
if p > 0 {
Append(", ")
}
generateIdentifier(param.Name)
}*/
}
Append(")")
decIndent()
}
}
}
}
override func generateMethodDefinition(_ method: CGMethodDefinition, type: CGTypeDefinition) {
// overriden in H
}
override func generateConstructorDefinition(_ ctor: CGConstructorDefinition, type: CGTypeDefinition) {
// overriden in H & CPP
}
override func generateDestructorDefinition(_ dtor: CGDestructorDefinition, type: CGTypeDefinition) {
cppGenerateMethodDefinitionHeader(dtor, type: type, header: true)
AppendLine(";")
}
override func generateFinalizerDefinition(_ finalizer: CGFinalizerDefinition, type: CGTypeDefinition) {
}
override func generateFieldDefinition(_ field: CGFieldDefinition, type: CGTypeDefinition) {
// use field as is
if let type = field.`Type` {
if field.Constant {
Append("const ")
}
generateTypeReference(type, ignoreNullability: false)
Append(" ")
generateIdentifier(field.Name)
if let value = field.Initializer {
Append(" = ")
generateExpression(value)
}
AppendLine(";")
} else {
// without type, generate as define
Append("#define ");
generateIdentifier(field.Name)
if let value = field.Initializer {
Append(" ")
generateExpression(value)
}
AppendLine();
}
}
override func generatePropertyDefinition(_ property: CGPropertyDefinition, type: CGTypeDefinition) {
// overriden in H
}
override func generateEventDefinition(_ event: CGEventDefinition, type: CGTypeDefinition) {
}
override func generateCustomOperatorDefinition(_ customOperator: CGCustomOperatorDefinition, type: CGTypeDefinition) {
}
//
// Type References
//
override func generateNamedTypeReference(_ type: CGNamedTypeReference, ignoreNamespace: Boolean, ignoreNullability: Boolean) {
if ignoreNamespace {
generateIdentifier(type.Name)
} else {
if let namespace = type.Namespace, (namespace.Name != "") {
generateIdentifier(namespace.Name)
Append("::")
}
generateIdentifier(type.Name)
}
generateGenericArguments(type.GenericArguments)
if type.IsClassType && !ignoreNullability {
Append("*")
}
}
override func generatePredefinedTypeReference(_ type: CGPredefinedTypeReference, ignoreNullability: Boolean = false) {
switch (type.Kind) {
case .Int: Append("int") //+
case .UInt: Append("unsigned int") //+
case .Int8: Append("char") //+
case .UInt8: Append("unsigned char") //+
case .Int16: Append("short int") //+
case .UInt16: Append("unsigned short int") //+
case .Int32: Append("int") //+
case .UInt32: Append("unsigned int") //+
case .Int64: if isCBuilder() {Append("__int64")} else {Append("long int")} //+
case .UInt64: Append("unsigned long int") //+
case .IntPtr: Append("IntPtr") //???????
case .UIntPtr: Append("UIntPtr") //???????
case .Single: Append("float") //+
case .Double: Append("double") //+
case .Boolean: Append("bool") //+
case .String: Append("string") //+
case .AnsiChar: Append("char") //+
case .UTF16Char: Append("wchar_t") //+
case .UTF32Char: Append("wchar_t") //+
case .Dynamic: Append("{DYNAMIC}") //??????
case .InstanceType: Append("{INSTANCETYPE}") //??????
case .Void: Append("void") //+
case .Object: Append("{OBJECT}") //??????
case .Class: Append("{CLASS}") //??????
}
}
override func generateInlineBlockTypeReference(_ type: CGInlineBlockTypeReference, ignoreNullability: Boolean = false) {
let block = type.Block
if let returnType = block.ReturnType {
generateTypeReference(returnType)
} else {
Append("void")
}
Append("(^)(")
for p in 0 ..< block.Parameters.Count {
if p > 0 {
Append(", ")
}
if let type = block.Parameters[p].`Type` {
generateTypeReference(type)
} else {
Append("id")
}
}
Append(")")
}
override func generateConstantTypeReference(_ type: CGConstantTypeReference, ignoreNullability: Boolean = false) {
generateTypeReference(type.`Type`)
Append(" const")
}
// override func generateKindOfTypeReference(_ type: CGKindOfTypeReference) {
// Append("__kindof ")
// generateTypeReference(type.`Type`)
// }
override func generateArrayTypeReference(_ type: CGArrayTypeReference, ignoreNullability: Boolean = false) {
if isCBuilder() {
if type.ArrayKind == .Dynamic {
Append("DynamicArray<")
generateTypeReference(type.`Type`)
Append(">")
return
}
}
generateTypeReference(type.`Type`)
if let bounds = type.Bounds {
var count = bounds.Count
if count == 0 {
count = 1
}
for b in 0 ..< count {
Append("[]")
}
}
}
override func generateDictionaryTypeReference(_ type: CGDictionaryTypeReference, ignoreNullability: Boolean = false) {
}
func generatePragma(_ pragma: String){
Append("#pragma ");
AppendLine(pragma);
}
func cppGenerateTypeVisibilityPrefix(_ visibility: CGTypeVisibilityKind) {
switch visibility {
case .Unspecified: break
case .Unit: break
case .Assembly: break
case .Public: Append("public ")
}
}
override func generatePointerTypeReference(_ type: CGPointerTypeReference) {
generateTypeReference(type.`Type`)
if type.Reference {
Append("&")
} else {
Append("*")
}
}
} | a45c3e8484eeeaf046fbd400e7813b48 | 27.508088 | 151 | 0.652615 | false | false | false | false |
sandym/swiftpp | refs/heads/master | examples/SimpleShapeDetector/SimpleShapeDetector/ShapeView.swift | mit | 1 | //
// ShapeView.swift
// ShapeDetect
//
// Created by Sandy Martel on 2014/07/07.
// Copyright (c) 2014年 Sandy Martel. All rights reserved.
//
import Cocoa
class ShapeView : NSView
{
var _timer : NSTimer?
var _currentPath : NSBezierPath?
var _coolPathList : [NSBezierPath] = []
@IBOutlet var _textView: NSTextView!
required init?(coder: NSCoder)
{
super.init(coder: coder)
}
override init(frame: NSRect)
{
super.init(frame: frame)
}
override func drawRect(dirtyRect: NSRect)
{
super.drawRect(dirtyRect)
// draw some instructions
NSAttributedString( string: "Draw some\nsimple shapes" ).drawAtPoint( CGPoint( x: 5, y: 5 ) );
// draw each already detected paths
NSColor.blackColor().set()
for p in _coolPathList
{
p.stroke()
}
// draw the path that the user is currently building
if let p = _currentPath
{
NSColor.redColor().set();
p.stroke()
}
}
override func mouseDown(theEvent: NSEvent)
{
// stop the timer
if let t = _timer
{
t.invalidate()
_timer = nil
}
// handle input
let pt = self.convertPoint( theEvent.locationInWindow, fromView: nil )
if _currentPath == nil
{
_currentPath = NSBezierPath()
_currentPath!.lineWidth = 10
_currentPath!.lineCapStyle = .RoundLineCapStyle
_currentPath!.lineJoinStyle = .RoundLineJoinStyle
}
_currentPath!.moveToPoint( pt )
self.needsDisplay = true
}
override func mouseDragged(theEvent: NSEvent)
{
// just append to the current path and redraw
let pt = self.convertPoint( theEvent.locationInWindow, fromView: nil )
_currentPath!.lineToPoint( pt );
self.needsDisplay = true
}
override func mouseUp(theEvent: NSEvent)
{
// just append to the current path and redraw
let pt = self.convertPoint( theEvent.locationInWindow, fromView: nil )
_currentPath!.lineToPoint( pt );
self.needsDisplay = true
// start a timer, after some time we'll try to guess what the user did.
_timer = NSTimer.scheduledTimerWithTimeInterval( 1, target:self, selector:"onTimer", userInfo:nil, repeats:false )
}
// ShapeDetector does not have the best API
// but it's there only to demonstrate subclassing C++ classes from swift.
// note: MyShapeDetector is a swift subclass to C++ ShapeDetector class !
class MyShapeDetector : ShapeDetector
{
let _view : ShapeView
init( view: ShapeView )
{
_view = view
}
// this override will be called for each shape detected by ShapeDetector
// note: it will be called from the C++ super class! name will be automatically
// converted from std::string to NSString by swiftpp builtin converter
// and path it will be converted from a C++ type to NSBezierPath
// by a user defined converter, see cxx-converter.mm
override func shapeDetected( name: String!, path: NSBezierPath! )
{
super.shapeDetected( name, path: path )
// we guessed one shape, record it!
_view._coolPathList.append( path! )
_view.report( name )
}
}
func report( name: String )
{
_textView.textStorage?.appendAttributedString( NSAttributedString( string: name + "\n" ) )
}
func onTimer()
{
// waited long enough, try to guess what the user was drawing
// 1- create a my sub class of shape detector
let shapeDetector = MyShapeDetector( view: self )
// 2- call detect: this will call the override for each shape detected
// note: _currentPath is an NSBezierPath, it will be converted to the appropriate C++
// type by a user defined converter, see cxx-converter.mm
shapeDetector.detect( _currentPath )
// clear current path and redraw
_currentPath = nil
self.needsDisplay = true // redraw
}
}
| 277efcfc97a53a75951eb835a8175c0d | 24.226027 | 116 | 0.688569 | false | false | false | false |
storehouse/Advance | refs/heads/master | Sources/Advance/Spring.swift | bsd-2-clause | 1 | import Foundation
/// Animates values using a spring function.
///
/// ```
/// let spring = Spring(value: CGPoint.zero)
/// spring.target = CGPoint(x: 300, y: 200)
///
/// ```
public final class Spring<Value: VectorConvertible> {
private let animator: Animator<Value>
private var function: SpringFunction<Value>
/// Initializes a new spring converged at the given value, using default configuration options for the spring function.
public init(initialValue: Value) {
dispatchPrecondition(condition: .onQueue(.main))
function = SpringFunction(target: initialValue)
animator = Animator(initialValue: initialValue)
}
/// Invoked every time the spring updates.
public var onChange: ((Value) -> Void)? {
get { return animator.onChange }
set { animator.onChange = newValue }
}
/// The current value of the spring.
public var value: Value {
get { return animator.value }
set {
let velocity = animator.velocity
animator.value = newValue
applyFunction(impartingVelocity: velocity)
}
}
/// The current velocity of the spring.
public var velocity: Value {
get { return animator.velocity }
set { applyFunction(impartingVelocity: newValue) }
}
/// The spring's target.
public var target: Value {
get { return function.target }
set {
function.target = newValue
applyFunction()
}
}
/// Removes any current velocity and snaps the spring directly to the given value.
/// - Parameter value: The new value that the spring will be reset to.
public func reset(to value: Value) {
function.target = value
animator.value = value
}
/// How strongly the spring will pull the value toward the target,
public var tension: Double {
get { return function.tension }
set {
function.tension = newValue
applyFunction()
}
}
/// The resistance that the spring encounters while moving the value.
public var damping: Double {
get { return function.damping }
set {
function.damping = newValue
applyFunction()
}
}
/// The minimum distance from the target value (for each component) that the
/// current value can be in order to enter a converged (settled) state.
public var threshold: Double {
get { return function.threshold }
set {
function.threshold = newValue
applyFunction()
}
}
private func applyFunction(impartingVelocity velocity: Value? = nil) {
if let velocity = velocity {
animator.simulate(using: function, initialVelocity: velocity)
} else {
animator.simulate(using: function)
}
}
}
| 5eb700c29ab9d6b17de1e83223d4f8b9 | 28.867347 | 123 | 0.603348 | false | false | false | false |
skedgo/tripkit-ios | refs/heads/main | Sources/TripKit/server/parsing/TKRoutingParser+Populate.swift | apache-2.0 | 1 | //
// TKRoutingParser+Populate.swift
// TripKit
//
// Created by Adrian Schoenig on 31/08/2016.
//
//
import Foundation
import MapKit
/// :nodoc:
extension TKRoutingParser {
@objc public static func matchingSegment(in trip: Trip, order: TKSegmentOrdering, first: Bool) -> TKSegment {
var match: TKSegment? = nil
for segment in trip.segments(with: .inDetails) {
if segment.order == order {
match = segment
if first {
break
}
}
}
return match!
}
@discardableResult
static func populate(_ request: TripRequest, using query: TKAPI.Query?) -> Bool {
populate(request, start: query?.from, end: query?.to, leaveAfter: query?.depart, arriveBy: query?.arrive)
}
/// Helper method to fill in a request wich the specified location.
///
/// Typically used on requests that were created as part of a previous call to
/// `parseAndAddResult`.
///
/// Also sets time type depending on whether `leaveAfter` and/or `arriveBy` are
/// provided. If both a provided, `arriveBy` takes precedence.
///
/// - Parameters:
/// - request: The request to populate it's from/to/time information
/// - start: New `fromLocation`. If not supplied, will be inferred from a random trip
/// - end: New `toLocation`. If not supplied, will be inferred from a random trip
/// - leaveAfter: Preferred departure time from `start`
/// - arriveBy: Preffered arrive-by time at `end`
/// - Returns: If the request did get updated successfully
@objc
@discardableResult
public static func populate(_ request: TripRequest, start: MKAnnotation?, end: MKAnnotation?, leaveAfter: Date?, arriveBy: Date?) -> Bool {
guard let trip = request.trips.first else {
return false
}
if let start = start, start.coordinate.isValid {
let named = TKNamedCoordinate.namedCoordinate(for: start)
request.fromLocation = named
} else {
let segment = matchingSegment(in: trip, order: .regular, first: true)
guard let start = segment.start?.coordinate else { return false }
request.fromLocation = TKNamedCoordinate(coordinate: start)
}
if let end = end, end.coordinate.isValid {
let named = TKNamedCoordinate.namedCoordinate(for: end)
request.toLocation = named
} else {
let segment = matchingSegment(in: trip, order: .regular, first: false)
guard let end = segment.end?.coordinate else { return false }
request.toLocation = TKNamedCoordinate(coordinate: end)
}
if let leaveAfter = leaveAfter {
request.departureTime = leaveAfter
request.type = .leaveAfter
}
if let arriveBy = arriveBy {
request.arrivalTime = arriveBy
request.type = .arriveBefore // can overwrite leave after
}
if arriveBy == nil && leaveAfter == nil {
if let trip = request.trips.first {
let firstRegular = matchingSegment(in: trip, order: .regular, first: true)
request.departureTime = firstRegular.departureTime
request.type = .leaveAfter
} else {
request.type = .leaveASAP
}
}
request.tripGroups.first?.adjustVisibleTrip()
return true
}
}
| 2f38dc516ada77472b71e66db6b83528 | 32.416667 | 141 | 0.658666 | false | false | false | false |
Ehrippura/firefox-ios | refs/heads/master | Providers/SyncStatusResolver.swift | mpl-2.0 | 7 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Sync
import XCGLogger
import Deferred
import Shared
import Storage
public enum SyncDisplayState {
case inProgress
case good
case bad(message: String?)
case warning(message: String)
func asObject() -> [String: String]? {
switch self {
case .bad(let msg):
guard let message = msg else {
return ["state": "Error"]
}
return ["state": "Error",
"message": message]
case .warning(let message):
return ["state": "Warning",
"message": message]
default:
break
}
return nil
}
}
public func ==(a: SyncDisplayState, b: SyncDisplayState) -> Bool {
switch (a, b) {
case (.inProgress, .inProgress):
return true
case (.good, .good):
return true
case (.bad(let a), .bad(let b)) where a == b:
return true
case (.warning(let a), .warning(let b)) where a == b:
return true
default:
return false
}
}
private let log = Logger.syncLogger
/*
* Translates the fine-grained SyncStatuses of each sync engine into a more coarse-grained
* display-oriented state for displaying warnings/errors to the user.
*/
public struct SyncStatusResolver {
let engineResults: Maybe<EngineResults>
public func resolveResults() -> SyncDisplayState {
guard let results = engineResults.successValue else {
switch engineResults.failureValue {
case _ as BookmarksMergeError, _ as BufferInvalidError:
return SyncDisplayState.warning(message: String(format: Strings.FirefoxSyncPartialTitle, Strings.localizedStringForSyncComponent("bookmarks") ?? ""))
default:
return SyncDisplayState.bad(message: nil)
}
}
// Run through the engine results and produce a relevant display status for each one
let displayStates: [SyncDisplayState] = results.map { (engineIdentifier, syncStatus) in
log.debug("Sync status for \(engineIdentifier): \(syncStatus)")
// Explicitly call out each of the enum cases to let us lean on the compiler when
// we add new error states
switch syncStatus {
case .notStarted(let reason):
switch reason {
case .offline:
return .bad(message: Strings.FirefoxSyncOfflineTitle)
case .noAccount:
return .warning(message: Strings.FirefoxSyncOfflineTitle)
case .backoff(_):
return .good
case .engineRemotelyNotEnabled(_):
return .good
case .engineFormatOutdated(_):
return .good
case .engineFormatTooNew(_):
return .good
case .storageFormatOutdated(_):
return .good
case .storageFormatTooNew(_):
return .good
case .stateMachineNotReady:
return .good
case .redLight:
return .good
case .unknown:
return .good
}
case .completed:
return .good
case .partial:
return .good
}
}
// TODO: Instead of finding the worst offender in a list of statuses, we should better surface
// what might have happened with a particular engine when syncing.
let aggregate: SyncDisplayState = displayStates.reduce(.good) { carried, displayState in
switch displayState {
case .bad(_):
return displayState
case .warning(_):
// If the state we're carrying is worse than the stale one, keep passing
// along the worst one
switch carried {
case .bad(_):
return carried
default:
return displayState
}
default:
// This one is good so just pass on what was being carried
return carried
}
}
log.debug("Resolved sync display state: \(aggregate)")
return aggregate
}
}
| 35459c4ceac99c0846fcb4940afbb2a7 | 32.610294 | 165 | 0.550864 | false | false | false | false |
sfaxon/PyxisServer | refs/heads/master | Sources/URLParamParser.swift | mit | 1 | //
// URLParamParser.swift
// Pyxis
//
// Created by Seth Faxon on 10/26/15.
// Copyright © 2015 SlashAndBurn. All rights reserved.
//
import Foundation
public class URLParamParser: PipelineProtocol {
private var connection: Connection
public required init(connection: Connection) {
self.connection = connection
}
public func call() -> Connection {
self.connection.urlParams = extractUrlParams(connection.request.url)
return self.connection
}
private func extractUrlParams(url: String) -> [(String, String)] {
let queryItems = url.characters.split{$0 == "?"}.map(String.init)
if queryItems.count > 1 {
let query = queryItems.last
let queryComponents = query!.characters.split{$0 == "&"}.map(String.init)
return queryComponents.map { (param:String) -> (String, String) in
let tokens = param.characters.split{$0 == "="}.map(String.init)
if tokens.count >= 2 {
let key = tokens[0]
let value = tokens[1]
return (key, value)
}
return ("","")
}
}
return []
}
}
| 74fd24cb464799e8971e5da6e432f099 | 29.5 | 85 | 0.564754 | false | false | false | false |
samuelclay/NewsBlur | refs/heads/master | clients/ios/Widget Extension/WidgetFeed.swift | mit | 1 | //
// WidgetFeed.swift
// Widget Extension
//
// Created by David Sinclair on 2019-12-23.
// Copyright © 2021 NewsBlur. All rights reserved.
//
import SwiftUI
/// A feed to display in the widget.
struct Feed: Identifiable {
/// The feed ID.
let id: String
/// The name of the feed.
let title: String
/// The left bar color.
let leftColor: Color
/// The right bar color.
let rightColor: Color
/// Keys for the dictionary representation.
struct DictionaryKeys {
static let id = "id"
static let title = "feed_title"
static let leftColor = "favicon_color"
static let rightColor = "favicon_fade"
}
/// A dictionary representation of the feed.
typealias Dictionary = [String : Any]
/// Initializer from a dictionary.
///
/// - Parameter dictionary: Dictionary representation.
init(from dictionary: Dictionary) {
let operation = WidgetDebugTimer.start("reading feed")
id = dictionary[DictionaryKeys.id] as? String ?? ""
title = dictionary[DictionaryKeys.title] as? String ?? ""
if let fadeHex = dictionary[DictionaryKeys.leftColor] as? String {
leftColor = Self.from(hexString: fadeHex)
} else {
leftColor = Self.from(hexString: "707070")
}
if let otherHex = dictionary[DictionaryKeys.rightColor] as? String {
rightColor = Self.from(hexString: otherHex)
} else {
rightColor = Self.from(hexString: "505050")
}
WidgetDebugTimer.print(operation, step: "title: \(title)")
}
/// Initializer for a sample.
///
/// - Parameter id: The identifier of the sample.
/// - Parameter title: The title of the sample.
init(sample id: String, title: String) {
self.id = id
self.title = title
let hue = Double.random(in: 0...1)
leftColor = Color(hue: hue, saturation: 0.5, brightness: 0.5)
rightColor = Color(hue: hue, saturation: 0.4, brightness: 0.5)
}
/// Given a hex string, returns the corresponding color.
///
/// - Parameter hexString: The hex string.
/// - Returns: The color equivalent.
static func from(hexString: String) -> Color {
var red: Double = 0
var green: Double = 0
var blue: Double = 0
var alpha: Double = 1
let length = hexString.count
let scanner = Scanner(string: hexString)
var hex: UInt64 = 0
scanner.scanHexInt64(&hex)
if length == 8 {
red = Double((hex & 0xFF000000) >> 24) / 255
green = Double((hex & 0x00FF0000) >> 16) / 255
blue = Double((hex & 0x0000FF00) >> 8) / 255
alpha = Double( hex & 0x000000FF) / 255
} else if length == 6 {
red = Double((hex & 0xFF0000) >> 16) / 255
green = Double((hex & 0x00FF00) >> 8) / 255
blue = Double( hex & 0x0000FF) / 255
}
NSLog("Reading color from '\(hexString)': red: \(red), green: \(green), blue: \(blue), alpha: \(alpha)")
return Color(.sRGB, red: red, green: green, blue: blue, opacity: alpha)
}
}
extension Feed: Equatable {
static func ==(lhs: Feed, rhs: Feed) -> Bool {
return lhs.id == rhs.id
}
}
extension Feed: CustomStringConvertible {
var description: String {
return "Feed \(title) (\(id))"
}
}
| a8b5e98f8a63f1d40b427f9c122d5008 | 29.439655 | 112 | 0.563863 | false | false | false | false |
ReactKit/SwiftState | refs/heads/swift/5.0 | Tests/SwiftStateTests/StateMachineEventTests.swift | mit | 1 | //
// StateMachineEventTests.swift
// SwiftState
//
// Created by Yasuhiro Inami on 2014/08/05.
// Copyright (c) 2014年 Yasuhiro Inami. All rights reserved.
//
import SwiftState
import XCTest
class StateMachineEventTests: _TestCase
{
func testCanTryEvent()
{
let machine = StateMachine<MyState, MyEvent>(state: .state0)
// add 0 => 1 & 1 => 2
// (NOTE: this is not chaining e.g. 0 => 1 => 2)
machine.addRoutes(event: .event0, transitions: [
.state0 => .state1,
.state1 => .state2,
])
XCTAssertTrue(machine.canTryEvent(.event0) != nil)
}
//--------------------------------------------------
// MARK: - tryEvent a.k.a `<-!`
//--------------------------------------------------
func testTryEvent()
{
let machine = StateMachine<MyState, MyEvent>(state: .state0)
// add 0 => 1 => 2
machine.addRoutes(event: .event0, transitions: [
.state0 => .state1,
.state1 => .state2,
])
// tryEvent
machine <-! .event0
XCTAssertEqual(machine.state, MyState.state1)
// tryEvent
machine <-! .event0
XCTAssertEqual(machine.state, MyState.state2)
// tryEvent
machine <-! .event0
XCTAssertEqual(machine.state, MyState.state2, "Event0 doesn't have 2 => Any")
}
func testTryEvent_string()
{
let machine = StateMachine<MyState, String>(state: .state0)
// add 0 => 1 => 2
machine.addRoutes(event: "Run", transitions: [
.state0 => .state1,
.state1 => .state2,
])
// tryEvent
machine <-! "Run"
XCTAssertEqual(machine.state, MyState.state1)
// tryEvent
machine <-! "Run"
XCTAssertEqual(machine.state, MyState.state2)
// tryEvent
machine <-! "Run"
XCTAssertEqual(machine.state, MyState.state2, "Event=Run doesn't have 2 => Any")
}
// https://github.com/ReactKit/SwiftState/issues/20
func testTryEvent_issue20()
{
let machine = StateMachine<MyState, MyEvent>(state: MyState.state2) { machine in
machine.addRoutes(event: .event0, transitions: [.any => .state0])
}
// tryEvent
machine <-! .event0
XCTAssertEqual(machine.state, MyState.state0)
}
// https://github.com/ReactKit/SwiftState/issues/28
func testTryEvent_issue28()
{
var eventCount = 0
let machine = StateMachine<MyState, MyEvent>(state: .state0) { machine in
machine.addRoute(.state0 => .state1)
machine.addRoutes(event: .event0, transitions: [.any => .any]) { _ in
eventCount += 1
}
}
XCTAssertEqual(eventCount, 0)
// tryEvent
machine <-! .event0
XCTAssertEqual(eventCount, 1)
XCTAssertEqual(machine.state, MyState.state0, "State should NOT be changed")
// tryEvent
machine <- .state1
XCTAssertEqual(machine.state, MyState.state1, "State should be changed")
// tryEvent
machine <-! .event0
XCTAssertEqual(eventCount, 2)
XCTAssertEqual(machine.state, MyState.state1, "State should NOT be changed")
}
// Fix for transitioning of routes w/ multiple from-states
// https://github.com/ReactKit/SwiftState/pull/32
func testTryEvent_issue32()
{
let machine = StateMachine<MyState, MyEvent>(state: .state0) { machine in
machine.addRoutes(event: .event0, transitions: [ .state0 => .state1 ])
machine.addRoutes(event: .event1, routes: [ [ .state1, .state2 ] => .state3 ])
}
XCTAssertEqual(machine.state, MyState.state0)
// tryEvent
machine <-! .event0
XCTAssertEqual(machine.state, MyState.state1)
// tryEvent
machine <-! .event1
XCTAssertEqual(machine.state, MyState.state3)
}
// MARK: hasRoute + event
func testHasRoute_anyEvent()
{
({
let machine = StateMachine<MyState, MyEvent>(state: .state0) { machine in
machine.addRoute(.state0 => .state1)
machine.addRoutes(event: .any, transitions: [.state0 => .state1])
}
let hasRoute = machine.hasRoute(event: .event0, transition: .state0 => .state1)
XCTAssertTrue(hasRoute)
})()
({
let machine = StateMachine<MyState, MyEvent>(state: .state0) { machine in
machine.addRoute(.state0 => .state1)
machine.addRoutes(event: .any, transitions: [.state2 => .state3])
}
let hasRoute = machine.hasRoute(event: .event0, transition: .state0 => .state1)
XCTAssertFalse(hasRoute)
})()
}
// Fix hasRoute() bug when there are routes for no-event & with-event.
// https://github.com/ReactKit/SwiftState/pull/19
func testHasRoute_issue19()
{
let machine = StateMachine<MyState, MyEvent>(state: .state0) { machine in
machine.addRoute(.state0 => .state1) // no-event
machine.addRoutes(event: .event0, transitions: [.state1 => .state2]) // with-event
}
let hasRoute = machine.hasRoute(event: .event0, transition: .state1 => .state2)
XCTAssertTrue(hasRoute)
}
//--------------------------------------------------
// MARK: - add/removeRoute
//--------------------------------------------------
func testAddRoute_tryState()
{
let machine = StateMachine<MyState, MyEvent>(state: .state0) { machine in
// add 0 => 1 & 1 => 2
// (NOTE: this is not chaining e.g. 0 => 1 => 2)
machine.addRoutes(event: .event0, transitions: [
.state0 => .state1,
.state1 => .state2,
])
}
// tryState 0 => 1
machine <- .state1
XCTAssertEqual(machine.state, MyState.state1)
// tryState 1 => 2
machine <- .state2
XCTAssertEqual(machine.state, MyState.state2)
// tryState 2 => 3
machine <- .state3
XCTAssertEqual(machine.state, MyState.state2, "2 => 3 is not registered.")
}
func testAddRoute_multiple()
{
let machine = StateMachine<MyState, MyEvent>(state: .state0) { machine in
// add 0 => 1 => 2
machine.addRoutes(event: .event0, transitions: [
.state0 => .state1,
.state1 => .state2,
])
// add 2 => 1 => 0
machine.addRoutes(event: .event1, transitions: [
.state2 => .state1,
.state1 => .state0,
])
}
// initial
XCTAssertEqual(machine.state, MyState.state0)
// tryEvent
machine <-! .event1
XCTAssertEqual(machine.state, MyState.state0, "Event1 doesn't have 0 => Any.")
// tryEvent
machine <-! .event0
XCTAssertEqual(machine.state, MyState.state1)
// tryEvent
machine <-! .event0
XCTAssertEqual(machine.state, MyState.state2)
// tryEvent
machine <-! .event0
XCTAssertEqual(machine.state, MyState.state2, "Event0 doesn't have 2 => Any.")
// tryEvent
machine <-! .event1
XCTAssertEqual(machine.state, MyState.state1)
// tryEvent
machine <-! .event1
XCTAssertEqual(machine.state, MyState.state0)
}
func testAddRoute_handler()
{
var invokeCount = 0
let machine = StateMachine<MyState, MyEvent>(state: .state0) { machine in
// add 0 => 1 => 2
machine.addRoutes(event: .event0, transitions: [
.state0 => .state1,
.state1 => .state2,
], handler: { context in
invokeCount += 1
return
})
}
// tryEvent
machine <-! .event0
XCTAssertEqual(machine.state, MyState.state1)
// tryEvent
machine <-! .event0
XCTAssertEqual(machine.state, MyState.state2)
XCTAssertEqual(invokeCount, 2)
}
func testRemoveRoute()
{
var invokeCount = 0
let machine = StateMachine<MyState, MyEvent>(state: .state0) { machine in
// add 0 => 1 => 2
let routeDisposable = machine.addRoutes(event: .event0, transitions: [
.state0 => .state1,
.state1 => .state2,
])
machine.addHandler(event: .event0) { context in
invokeCount += 1
return
}
// removeRoute
routeDisposable.dispose()
}
// initial
XCTAssertEqual(machine.state, MyState.state0)
// tryEvent
machine <-! .event0
XCTAssertEqual(machine.state, MyState.state0, "Route should be removed.")
XCTAssertEqual(invokeCount, 0, "Handler should NOT be performed")
}
//--------------------------------------------------
// MARK: - add/removeHandler
//--------------------------------------------------
func testAddHandler()
{
var invokeCount = 0
let machine = StateMachine<MyState, MyEvent>(state: .state0) { machine in
// add 0 => 1 => 2
machine.addRoutes(event: .event0, transitions: [
.state0 => .state1,
.state1 => .state2,
])
machine.addHandler(event: .event0) { context in
invokeCount += 1
return
}
}
// tryEvent
machine <-! .event0
XCTAssertEqual(machine.state, MyState.state1)
// tryEvent
machine <-! .event0
XCTAssertEqual(machine.state, MyState.state2)
XCTAssertEqual(invokeCount, 2)
}
func testRemoveHandler()
{
var invokeCount = 0
let machine = StateMachine<MyState, MyEvent>(state: .state0) { machine in
// add 0 => 1 => 2
machine.addRoutes(event: .event0, transitions: [
.state0 => .state1,
.state1 => .state2,
])
let handlerDisposable = machine.addHandler(event: .event0) { context in
invokeCount += 1
return
}
// remove handler
handlerDisposable.dispose()
}
// tryEvent
machine <-! .event0
XCTAssertEqual(machine.state, MyState.state1, "0 => 1 should be succesful")
// tryEvent
machine <-! .event0
XCTAssertEqual(machine.state, MyState.state2, "1 => 2 should be succesful")
XCTAssertEqual(invokeCount, 0, "Handler should NOT be performed")
}
//--------------------------------------------------
// MARK: - addAnyHandler
//--------------------------------------------------
func testAddAnyHandler()
{
var invokeCounts = [0, 0, 0, 0, 0, 0]
let machine = StateMachine<MyState, MyEvent>(state: .state0) { machine in
// add 0 => 1 => 2 (event-based)
machine.addRoutes(event: .event0, transitions: [
.state0 => .state1,
.state1 => .state2,
])
// add 2 => 3 (state-based)
machine.addRoute(.state2 => .state3)
//
// addAnyHandler (for both event-based & state-based)
//
machine.addAnyHandler(.state0 => .state1) { context in
invokeCounts[0] += 1
}
machine.addAnyHandler(.state1 => .state2) { context in
invokeCounts[1] += 1
}
machine.addAnyHandler(.state2 => .state3) { context in
invokeCounts[2] += 1
}
machine.addAnyHandler(.any => .state3) { context in
invokeCounts[3] += 1
}
machine.addAnyHandler(.state0 => .any) { context in
invokeCounts[4] += 1
}
machine.addAnyHandler(.any => .any) { context in
invokeCounts[5] += 1
}
}
// initial
XCTAssertEqual(machine.state, MyState.state0)
XCTAssertEqual(invokeCounts, [0, 0, 0, 0, 0, 0])
// tryEvent
machine <-! .event0
XCTAssertEqual(machine.state, MyState.state1)
XCTAssertEqual(invokeCounts, [1, 0, 0, 0, 1, 1])
// tryEvent
machine <-! .event0
XCTAssertEqual(machine.state, MyState.state2)
XCTAssertEqual(invokeCounts, [1, 1, 0, 0, 1, 2])
// tryState
machine <- .state3
XCTAssertEqual(machine.state, MyState.state3)
XCTAssertEqual(invokeCounts, [1, 1, 1, 1, 1, 3])
}
}
| 87a821d33a588f3dd06e9ff14eb6bb31 | 27.671875 | 96 | 0.521448 | false | false | false | false |
curiosityio/Mac | refs/heads/master | Mac/Classes/Manager/BaseMacDataManager.swift | mit | 1 | //
// BaseMacDataManager.swift
// Pods
//
// Created by Levi Bostian on 4/4/17.
//
//
import Foundation
import RealmSwift
import RxSwift
import iOSBoilerplate
open class BaseMacDataManager {
public init() {
}
public func performRealmTransaction(changeData: @escaping ((Realm) -> Void), tempRealmInstance: Bool = false) {
if Thread.isMainThread {
fatalError("Cannot perform transaction from UI thread.")
}
let realm = getRealmInstance(tempInstance: tempRealmInstance)
try! realm.writeIfNotAlready {
changeData(realm)
}
}
private func getRealmInstance(tempInstance: Bool) -> Realm {
return tempInstance ? RealmInstanceManager.sharedInstance.getTempInstance() : RealmInstanceManager.sharedInstance.getInstance()
}
public func performRealmTransactionCompletable(changeData: @escaping ((Realm) -> Void), tempRealmInstance: Bool = false) -> Completable {
return Completable.create(subscribe: { (observer) -> Disposable in
if Thread.isMainThread {
fatalError("Cannot perform transaction from UI thread.")
}
let realm = self.getRealmInstance(tempInstance: tempRealmInstance)
try! realm.write {
changeData(realm)
}
observer(CompletableEvent.completed)
return Disposables.create()
}).subscribeOn(ConcurrentDispatchQueueScheduler(qos: .background))
}
public func getNewRealmId() -> String {
return UUID().uuidString
}
public func createData<MODEL, PENDING_API_TASK>(realm: Realm, data: inout MODEL, makeAdditionalRealmChanges: (MODEL) -> Void, pendingApiTasks: [PENDING_API_TASK]) where MODEL: OfflineCapableModel, PENDING_API_TASK: PendingApiTask {
realm.add(data as! Object, update: false) // we don't want to update. We want the call to FAIL. Why? Because we should be calling updateData() instead of create if you already have data with the same primary key in the realm.
makeAdditionalRealmChanges(data)
pendingApiTasks.forEach { (task: PENDING_API_TASK) in
realm.add(task as! Object)
}
data.numberPendingApiSyncs += 1
}
// in future, make the pendingApiTask have have an interface for updating. We want to make sure that
// only create, update, delete pending API models are calling the appropriate methods.
public func updateData<MODEL, PENDING_API_TASK>(realm: Realm, modelClass: MODEL.Type, realmId: String, updateValues: (MODEL) -> Void, pendingApiTask: PENDING_API_TASK) where MODEL: Object, MODEL: OfflineCapableModel, PENDING_API_TASK: Object, PENDING_API_TASK: PendingApiTask {
guard var modelToUpdateValues = realm.objects(modelClass).filter(NSPredicate(format: "realmId == %@", realmId)).first else {
fatalError("\(modelClass.className()) model to update is null. Cannot find it in Realm.")
}
updateValues(modelToUpdateValues)
let existingPendingApiTask = pendingApiTask.queryForExistingTask(realm: realm)
if existingPendingApiTask == nil {
modelToUpdateValues.numberPendingApiSyncs += 1
}
realm.add(pendingApiTask, update: true) // updates created_at value which tells pending API task runner to run *another* update on the model.
}
//
// // in future, make the pendingApiTask have have an interface for updating. We want to make sure that
// // only create, update, delete pending API models are calling the appropriate methods.
// public func updateData<MODEL, PENDING_API_TASK>(realm: Realm, modelClass: MODEL.Type, realmId: String, updateValues: (MODEL) -> Void, pendingApiTasks: [PENDING_API_TASK]) where MODEL: OfflineCapableModel, PENDING_API_TASK: Object, PENDING_API_TASK: PendingApiTask {
// guard modelClass is Object.Type else {
// fatalError("modelClass param must be instance of Object")
// }
//
// guard var modelToUpdateValues = (realm.objects(modelClass as! Object.Type).filter(NSPredicate(format: "realmId == %@", realmId)).first as? MODEL?) else {
// fatalError("\((modelClass as! Object.Type).className()) model to update is null. Cannot find it in Realm.")
// }
//
// updateValues(modelToUpdateValues!)
//
// pendingApiTasks.forEach { (task: PENDING_API_TASK) in
// let existingPendingApiTask = task.queryForExistingTask(realm: realm)
// if existingPendingApiTask == nil {
// modelToUpdateValues!.numberPendingApiSyncs += 1
// }
// realm.add(task, update: true) // updates created_at value which tells pending API task runner to run *another* update on the model.
// }
// }
public func deleteData<MODEL, PENDING_API_TASK>(realm: Realm, modelClass: MODEL.Type, realmId: String, updateValues: ((MODEL) -> Void), pendingApiTask: PENDING_API_TASK? = nil) where MODEL: Object, MODEL: OfflineCapableModel, PENDING_API_TASK: Object, PENDING_API_TASK: PendingApiTask {
guard var modelToUpdateValues = realm.objects(modelClass).filter(NSPredicate(format: "realmId == %@", realmId)).first else {
fatalError("\(modelClass.className()) model to update is null. Cannot find it in Realm.")
}
modelToUpdateValues.deleted = true
updateValues(modelToUpdateValues)
if let pendingApiTask = pendingApiTask {
if let _ = pendingApiTask.queryForExistingTask(realm: realm) {
modelToUpdateValues.numberPendingApiSyncs += 1
}
realm.add(pendingApiTask, update: true) // updates created_at value which tells pending API task runner to run *another* update on the model.
}
}
public func undoDeleteData<MODEL>(realm: Realm, modelClass: MODEL.Type, realmId: String, updateValues: (MODEL) -> Void) where MODEL: Object, MODEL: OfflineCapableModel {
guard var modelToUpdateValues = realm.objects(modelClass).filter(NSPredicate(format: "realmId == %@", realmId)).first else {
fatalError("\(modelClass.className()) model to update is null. Cannot find it in Realm.")
}
modelToUpdateValues.deleted = false
updateValues(modelToUpdateValues)
}
}
| 8cb530b0fd5c7d4e672622c81a2fc1c5 | 49.289063 | 290 | 0.663974 | false | false | false | false |
polenoso/TMDBiOS | refs/heads/master | theiostmdb/theiostmdb/BaseViewController.swift | mit | 1 | //
// BaseViewController.swift
// theiostmdb
//
// Created by aitor pagan on 14/3/17.
//
//
import UIKit
@objc
protocol CenterViewControllerDelegate {
@objc optional func toggleLeftPanel()
@objc optional func showViewController(vc: UIViewController)
}
class BaseViewController: UIViewController {
var delegate: CenterViewControllerDelegate?
var alertController: UIAlertController? = nil
let alertHeight:CGFloat = 100.0
let alertWidth:CGFloat = 300.0
let ai: UIActivityIndicatorView? = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge)
override func viewDidLoad() {
super.viewDidLoad()
ai?.frame = CGRect(x: 0.0, y: 300, width: self.view.frame.size.width, height: 100)
let menuButton: UIBarButtonItem = UIBarButtonItem(title: "Menu", style: .plain, target: self, action: #selector(BaseViewController.toggleMenu(sender:)))
self.navigationItem.setLeftBarButton(menuButton, animated: false)
self.navigationItem.title = "TMDB"
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(BaseViewController.dismissKeyboard))
view.addGestureRecognizer(tap)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func showErrorAlert(with message: String){
self.alertController = UIAlertController.init(title: "Error", message: message, preferredStyle: .alert)
self.alertController?.addAction(UIAlertAction(title: "Dismiss", style: .default,handler: nil))
self.present(self.alertController!, animated: true, completion: nil)
}
func startActivityIndicator(){
self.view.addSubview(ai!)
ai?.color = UIColor.black
ai!.startAnimating()
}
func stopActivityIndicator(){
self.ai!.stopAnimating()
self.ai!.removeFromSuperview()
}
func toggleMenu(sender: UIBarButtonItem){
dismissKeyboard()
delegate?.toggleLeftPanel!()
}
func dismissKeyboard(){
self.view.endEditing(true)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
extension BaseViewController: SidePanelViewControllerDelegate{
func optionSelected(vc: UIViewController) {
if(self.ai?.isAnimating)!{
self.stopActivityIndicator()
NetworkService.shared.stopRequests();
}
delegate?.showViewController!(vc: vc)
delegate?.toggleLeftPanel!()
}
}
| 0ac55ff05bf07c795ab6c5a0c062127b | 32.258427 | 160 | 0.685473 | false | false | false | false |
Eonil/Editor | refs/heads/develop | Editor4/StateAssertions.swift | mit | 1 | //
// StateAssertions.swift
// Editor4
//
// Created by Hoon H. on 2016/05/26.
// Copyright © 2016 Eonil. All rights reserved.
//
extension State {
func assertConsistency() {
runOnlyInUnoptimizedBuild {
for (_, workspaceState) in workspaces {
workspaceState.assertConsistency()
}
}
}
}
private extension WorkspaceState {
private func assertConsistency() {
runOnlyInUnoptimizedBuild {
assert(location == nil || location!.fileURL)
let allFileIDs = files.map({ $0.0 })
let uniqueFileIDs = Set(allFileIDs)
assert(allFileIDs.count == uniqueFileIDs.count)
let a = Array(files).map({ $0.0 })
if let currentFileID = window.navigatorPane.file.selection.current {
assert(a.contains(currentFileID) == true)
}
assert(window.navigatorPane.file.selection.items.version == window.navigatorPane.file.selection.items.accessibleVersion)
for selectedFileID in window.navigatorPane.file.selection.items {
let a = Array(files).map({ $0.0 })
assert(a.contains(selectedFileID) == true)
}
files.assertConsistency()
}
}
}
private extension FileTree2 {
private func assertConsistency() {
runOnlyInUnoptimizedBuild {
/// Top-down link tests.
for (fileID, fileState) in self {
for subfileID in fileState.subfileIDs {
assert(self[subfileID].superfileID != nil, "A subfile `\(subfileID)` does not have link to superfile `\(fileID)`, but reverse does exist.")
assert(self[subfileID].superfileID == fileID, "A subfile `\(subfileID)` link to suprfile is wrong. It must be `\(fileID)`, but it is now `\(self[subfileID].superfileID)`.")
}
guard let superfileID = self[fileID].superfileID else { continue }
assert(self[superfileID].subfileIDs.contains(fileID), "A superfile `\(superfileID)` does not contain subfile `\(fileID)`, but reverse does exist.")
}
/// Bottom-up link tests.
for (fileID, _) in self {
guard let superfileID = self[fileID].superfileID else { continue }
assert(self[superfileID].subfileIDs.contains(fileID), "A superfile `\(superfileID)` does not contain subfile `\(fileID)`.")
}
}
}
}
private func runOnlyInUnoptimizedBuild(@noescape f: ()->()) {
assert({
f()
return true
}())
} | 15586d3c50cec73c65b63192a687ac46 | 38.953846 | 192 | 0.589753 | false | false | false | false |
boolkybear/ChromaProjectApp | refs/heads/master | ChromaProjectApp/ChromaProjectApp/ContainerController.swift | mit | 1 | //
// ContainerController.swift
// ChromaProjectApp
//
// Created by Boolky Bear on 25/12/14.
// Copyright (c) 2014 ByBDesigns. All rights reserved.
//
import UIKit
private enum Segue: String
{
case DocumentEmbedSegue = "documentEmbedSegue"
case SettingsEmbedSegue = "settingsEmbedSegue"
}
class ContainerController: UIViewController {
@IBOutlet var settingsContainer: UIView!
@IBOutlet var settingsButton: UIBarButtonItem!
var iCloudManager: ICloudManager? = nil
var documentSelectionController: DocumentSelectionController? = nil
var settingsController: SettingsController? = nil
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.iCloudManager = ICloudManager() {
ubiquityToken in
let saveSettings = NSUserDefaults.saveSettings()
if saveSettings == .SaveInCloud
{
let currentToken: AnyObject? = NSUserDefaults.ubiquityToken()
switch (currentToken, ubiquityToken)
{
case (nil, nil):
break
case (nil, .Some):
let unwrappedUbiquityToken = ubiquityToken! as protocol<NSCoding, NSCopying, NSObjectProtocol>
NSUserDefaults.setUbiquityToken(unwrappedUbiquityToken)
self.documentSelectionController?.reloadDocuments(saveSettings)
case (.Some, nil):
NSUserDefaults.setUbiquityToken(nil)
self.settingsContainer.hidden = false
self.settingsController?.enableiCloud(false)
let alertController = UIAlertController(title: NSLocalizedString("No iCloud", comment: ""),
message: NSLocalizedString("Connect to iCloud again to keep saving in iCloud", comment: ""),
preferredStyle: .Alert)
let action = UIAlertAction(title: NSLocalizedString("Ok", comment: ""), style: .Cancel) { action in }
alertController.addAction(action)
self.presentViewController(alertController, animated: true, completion: nil)
case (.Some, .Some):
let unwrappedCurrentToken: AnyObject = currentToken!
let unwrappedUbiquityToken: AnyObject = ubiquityToken!
if unwrappedCurrentToken.isEqual(unwrappedUbiquityToken) == false
{
self.settingsContainer.hidden = false
self.settingsController?.enableiCloud(true)
let alertController = UIAlertController(title: NSLocalizedString("iCloud account changed", comment: ""),
message: NSLocalizedString("Changing iCloud account will reload your documents, please confirm", comment: ""),
preferredStyle: .Alert)
let action = UIAlertAction(title: NSLocalizedString("Ok", comment: ""), style: .Destructive) { action in }
alertController.addAction(action)
self.presentViewController(alertController, animated: true, completion: nil)
}
default:
break
}
}
else if saveSettings == .NotConfigured
{
self.settingsContainer.hidden = false
self.settingsController?.enableiCloud(ubiquityToken != nil)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
switch(segue.identifier!)
{
case Segue.DocumentEmbedSegue.rawValue:
self.documentSelectionController = segue.destinationViewController as? DocumentSelectionController
self.setupControllers(self.settingsController, selectionController: self.documentSelectionController)
case Segue.SettingsEmbedSegue.rawValue:
self.settingsController = segue.destinationViewController as? SettingsController
let iCloudToken = NSFileManager.defaultManager().ubiquityIdentityToken
self.settingsController?.enableiCloud(iCloudToken != nil)
self.setupControllers(self.settingsController, selectionController: self.documentSelectionController)
default:
break
}
}
}
// MARK: - Actions
extension ContainerController
{
@IBAction func settingsButtonClicked(sender: UIBarButtonItem) {
self.settingsContainer.hidden = (self.settingsContainer.hidden == false)
}
@IBAction func addDocumentButtonClicked(sender: UIBarButtonItem) {
let document = self.documentSelectionController?.addNewDocument(NSUserDefaults.saveSettings())
if let createdDocument = document
{
// TODO: push document for edition
}
}
}
private extension ContainerController
{
func setupControllers(settingsController: SettingsController?, selectionController: DocumentSelectionController?)
{
ifNotNil(selectionController, settingsController) {
selectionController, settingsController in
settingsController.settingsChange = {
settings in
selectionController.reloadDocuments(settings)
UIView.animateWithDuration(0.3, animations: {
self.settingsContainer.alpha = 0.0 }) {
isFinished in
self.settingsContainer.hidden = true
self.settingsContainer.alpha = 1.0
}
}
}
}
} | f10f869b7a803d901a43bee90ffc2140 | 32.140127 | 117 | 0.736063 | false | false | false | false |
PureSwift/Bluetooth | refs/heads/master | Sources/BluetoothGATT/GATTAnaerobicHeartRateLowerLimit.swift | mit | 1 | //
// GATTAnaerobicHeartRateLowerLimit.swift
// Bluetooth
//
// Created by Carlos Duclos on 6/15/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
import Foundation
/**
Anaerobic Heart Rate Lower Limit
Lower limit of the heart rate where the user enhances his anaerobic tolerance while exercising.
- SeeAlso: [Anaerobic Heart Rate Lower Limit](https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.anaerobic_heart_rate_lower_limit.xml)
*/
@frozen
public struct GATTAnaerobicHeartRateLowerLimit: GATTCharacteristic, Equatable, Hashable {
public typealias BeatsPerMinute = GATTBeatsPerMinute.Byte
internal static let length = MemoryLayout<UInt8>.size
public static var uuid: BluetoothUUID { return .anaerobicHeartRateLowerLimit }
public var beats: BeatsPerMinute
public init(beats: BeatsPerMinute) {
self.beats = beats
}
public init?(data: Data) {
guard data.count == type(of: self).length
else { return nil }
let beats = BeatsPerMinute(rawValue: data[0])
self.init(beats: beats)
}
public var data: Data {
return Data([beats.rawValue])
}
}
extension GATTAnaerobicHeartRateLowerLimit: CustomStringConvertible {
public var description: String {
return beats.description
}
}
| 5b54eeb71b2eb55e02568fed64010595 | 24.368421 | 183 | 0.672199 | false | false | false | false |
ABTSoftware/SciChartiOSTutorial | refs/heads/master | v2.x/Examples/SciChartSwiftDemo/SciChartSwiftDemo/Views/ManipulateSeries/AddRemoveSeries/AddRemoveSeriesChartView.swift | mit | 1 | //******************************************************************************
// SCICHART® Copyright SciChart Ltd. 2011-2018. All rights reserved.
//
// Web: http://www.scichart.com
// Support: [email protected]
// Sales: [email protected]
//
// AddRemoveSeriesChartView.swift is part of the SCICHART® Examples. Permission is hereby granted
// to modify, create derivative works, distribute and publish any part of this source
// code whether for commercial, private or personal use.
//
// The SCICHART® examples are distributed in the hope that they will be useful, but
// without any warranty. It is provided "AS IS" without warranty of any kind, either
// expressed or implied.
//******************************************************************************
class AddRemoveSeriesChartView: AddRemoveSeriesChartLayout {
override func commonInit() {
weak var wSelf = self
self.addSeries = { wSelf?.add() }
self.removeSeries = { wSelf?.remove() }
self.clearSeries = { wSelf?.clear() }
}
override func initExample() {
let xAxis = SCINumericAxis()
xAxis.autoRange = .always
xAxis.visibleRange = SCIDoubleRange(min: SCIGeneric(0.0), max: SCIGeneric(150.0))
xAxis.axisTitle = "X Axis"
let yAxis = SCINumericAxis()
yAxis.autoRange = .always
yAxis.axisTitle = "Y Axis"
self.surface.xAxes.add(xAxis)
self.surface.yAxes.add(yAxis)
surface.chartModifiers = SCIChartModifierCollection(childModifiers: [SCIPinchZoomModifier(), SCIZoomPanModifier(), SCIZoomExtentsModifier()])
}
fileprivate func add() {
SCIUpdateSuspender.usingWithSuspendable(surface) {
let randomDoubleSeries = DataManager.getRandomDoubleSeries(withCount: 150)
let dataSeries = SCIXyDataSeries.init(xType: .double, yType: .double)
dataSeries.appendRangeX(randomDoubleSeries!.xValues, y: randomDoubleSeries!.yValues, count: randomDoubleSeries!.size)
let mountainRenderSeries = SCIFastMountainRenderableSeries()
mountainRenderSeries.dataSeries = dataSeries
mountainRenderSeries.areaStyle = SCISolidBrushStyle.init(color: UIColor.init(red: CGFloat(arc4random_uniform(255)), green: CGFloat(arc4random_uniform(255)), blue: CGFloat(arc4random_uniform(255)), alpha: 1.0))
mountainRenderSeries.strokeStyle = SCISolidPenStyle.init(color: UIColor.init(red: CGFloat(arc4random_uniform(255)), green: CGFloat(arc4random_uniform(255)), blue: CGFloat(arc4random_uniform(255)), alpha: 1.0), withThickness: 1.0)
self.surface.renderableSeries.add(mountainRenderSeries)
}
}
fileprivate func remove() {
SCIUpdateSuspender.usingWithSuspendable(surface) {
if (self.surface.renderableSeries.count() > 0) {
self.surface.renderableSeries.remove(at: 0)
}
}
}
fileprivate func clear() {
SCIUpdateSuspender.usingWithSuspendable(surface) {
self.surface.renderableSeries.clear()
}
}
}
| 8e76165cb3288ed8b451228120a2cbcb | 43.2 | 241 | 0.650291 | false | false | false | false |
noppoMan/aws-sdk-swift | refs/heads/main | Sources/Soto/Services/AppMesh/AppMesh_Paginator.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import SotoCore
// MARK: Paginators
extension AppMesh {
/// Returns a list of existing gateway routes that are associated to a virtual
/// gateway.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listGatewayRoutesPaginator<Result>(
_ input: ListGatewayRoutesInput,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListGatewayRoutesOutput, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listGatewayRoutes,
tokenKey: \ListGatewayRoutesOutput.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listGatewayRoutesPaginator(
_ input: ListGatewayRoutesInput,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListGatewayRoutesOutput, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listGatewayRoutes,
tokenKey: \ListGatewayRoutesOutput.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Returns a list of existing service meshes.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listMeshesPaginator<Result>(
_ input: ListMeshesInput,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListMeshesOutput, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listMeshes,
tokenKey: \ListMeshesOutput.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listMeshesPaginator(
_ input: ListMeshesInput,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListMeshesOutput, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listMeshes,
tokenKey: \ListMeshesOutput.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Returns a list of existing routes in a service mesh.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listRoutesPaginator<Result>(
_ input: ListRoutesInput,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListRoutesOutput, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listRoutes,
tokenKey: \ListRoutesOutput.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listRoutesPaginator(
_ input: ListRoutesInput,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListRoutesOutput, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listRoutes,
tokenKey: \ListRoutesOutput.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// List the tags for an App Mesh resource.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listTagsForResourcePaginator<Result>(
_ input: ListTagsForResourceInput,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListTagsForResourceOutput, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listTagsForResource,
tokenKey: \ListTagsForResourceOutput.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listTagsForResourcePaginator(
_ input: ListTagsForResourceInput,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListTagsForResourceOutput, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listTagsForResource,
tokenKey: \ListTagsForResourceOutput.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Returns a list of existing virtual gateways in a service mesh.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listVirtualGatewaysPaginator<Result>(
_ input: ListVirtualGatewaysInput,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListVirtualGatewaysOutput, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listVirtualGateways,
tokenKey: \ListVirtualGatewaysOutput.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listVirtualGatewaysPaginator(
_ input: ListVirtualGatewaysInput,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListVirtualGatewaysOutput, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listVirtualGateways,
tokenKey: \ListVirtualGatewaysOutput.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Returns a list of existing virtual nodes.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listVirtualNodesPaginator<Result>(
_ input: ListVirtualNodesInput,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListVirtualNodesOutput, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listVirtualNodes,
tokenKey: \ListVirtualNodesOutput.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listVirtualNodesPaginator(
_ input: ListVirtualNodesInput,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListVirtualNodesOutput, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listVirtualNodes,
tokenKey: \ListVirtualNodesOutput.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Returns a list of existing virtual routers in a service mesh.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listVirtualRoutersPaginator<Result>(
_ input: ListVirtualRoutersInput,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListVirtualRoutersOutput, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listVirtualRouters,
tokenKey: \ListVirtualRoutersOutput.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listVirtualRoutersPaginator(
_ input: ListVirtualRoutersInput,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListVirtualRoutersOutput, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listVirtualRouters,
tokenKey: \ListVirtualRoutersOutput.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Returns a list of existing virtual services in a service mesh.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listVirtualServicesPaginator<Result>(
_ input: ListVirtualServicesInput,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListVirtualServicesOutput, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listVirtualServices,
tokenKey: \ListVirtualServicesOutput.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listVirtualServicesPaginator(
_ input: ListVirtualServicesInput,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListVirtualServicesOutput, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listVirtualServices,
tokenKey: \ListVirtualServicesOutput.nextToken,
on: eventLoop,
onPage: onPage
)
}
}
extension AppMesh.ListGatewayRoutesInput: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> AppMesh.ListGatewayRoutesInput {
return .init(
limit: self.limit,
meshName: self.meshName,
meshOwner: self.meshOwner,
nextToken: token,
virtualGatewayName: self.virtualGatewayName
)
}
}
extension AppMesh.ListMeshesInput: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> AppMesh.ListMeshesInput {
return .init(
limit: self.limit,
nextToken: token
)
}
}
extension AppMesh.ListRoutesInput: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> AppMesh.ListRoutesInput {
return .init(
limit: self.limit,
meshName: self.meshName,
meshOwner: self.meshOwner,
nextToken: token,
virtualRouterName: self.virtualRouterName
)
}
}
extension AppMesh.ListTagsForResourceInput: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> AppMesh.ListTagsForResourceInput {
return .init(
limit: self.limit,
nextToken: token,
resourceArn: self.resourceArn
)
}
}
extension AppMesh.ListVirtualGatewaysInput: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> AppMesh.ListVirtualGatewaysInput {
return .init(
limit: self.limit,
meshName: self.meshName,
meshOwner: self.meshOwner,
nextToken: token
)
}
}
extension AppMesh.ListVirtualNodesInput: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> AppMesh.ListVirtualNodesInput {
return .init(
limit: self.limit,
meshName: self.meshName,
meshOwner: self.meshOwner,
nextToken: token
)
}
}
extension AppMesh.ListVirtualRoutersInput: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> AppMesh.ListVirtualRoutersInput {
return .init(
limit: self.limit,
meshName: self.meshName,
meshOwner: self.meshOwner,
nextToken: token
)
}
}
extension AppMesh.ListVirtualServicesInput: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> AppMesh.ListVirtualServicesInput {
return .init(
limit: self.limit,
meshName: self.meshName,
meshOwner: self.meshOwner,
nextToken: token
)
}
}
| 6d26d02d2c3859aa48c279a5e6a25bda | 40.94971 | 168 | 0.635513 | false | false | false | false |
overtake/TelegramSwift | refs/heads/master | Telegram-Mac/ForumTopicEmojiSelectRowItem.swift | gpl-2.0 | 1 | //
// ForumTopicEmojiSelectRowItem.swift
// Telegram
//
// Created by Mike Renoir on 27.09.2022.
// Copyright © 2022 Telegram. All rights reserved.
//
import Foundation
import TGUIKit
final class ForumTopicEmojiSelectRowItem : GeneralRowItem {
let getView: ()->NSView
let context: AccountContext
init(_ initialSize: NSSize, stableId: AnyHashable, context: AccountContext, getView: @escaping()->NSView, viewType: GeneralViewType) {
self.getView = getView
self.context = context
super.init(initialSize, stableId: stableId, viewType: viewType)
}
override func viewClass() -> AnyClass {
return ForumTopicEmojiSelectRowView.self
}
override var height: CGFloat {
if let table = self.table {
var height: CGFloat = 0
table.enumerateItems(with: { item in
if item != self {
height += item.height
}
return true
})
return table.frame.height - height
}
return 250
}
override var instantlyResize: Bool {
return true
}
override var reloadOnTableHeightChanged: Bool {
return true
}
}
private final class ForumTopicEmojiSelectRowView: GeneralContainableRowView {
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
}
override func layout() {
super.layout()
guard let item = item as? ForumTopicEmojiSelectRowItem else {
return
}
let view = item.getView()
view.frame = self.containerView.bounds
}
override func set(item: TableRowItem, animated: Bool = false) {
super.set(item: item, animated: animated)
guard let item = item as? ForumTopicEmojiSelectRowItem else {
return
}
let view = item.getView()
addSubview(view)
needsLayout = true
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| d49cc808f642736c2df720d131eb1a73 | 25.551282 | 138 | 0.60309 | false | false | false | false |
Dreezydraig/actor-platform | refs/heads/master | actor-apps/app-ios/ActorApp/Controllers/Compose/GroupMembersController.swift | mit | 24 | //
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import UIKit
class GroupMembersController: ContactsBaseViewController/*, CLTokenInputViewDelegate*/ {
private var groupTitle: String!
private var groupImage: UIImage?
private var tableView = UITableView()
private var tokenView = CLTokenInputView()
private var tokenViewHeight: CGFloat = 48
private var selected = [TokenRef]()
init(title: String, image: UIImage?) {
super.init(contentSection: 0, nibName: nil, bundle: nil)
self.groupTitle = title
self.groupImage = image
navigationItem.title = localized("CreateGroupMembersTitle")
navigationItem.rightBarButtonItem = UIBarButtonItem(title: localized("NavigationDone"), style: UIBarButtonItemStyle.Done, target: self, action: "doNext")
self.extendedLayoutIncludesOpaqueBars = true
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
view.backgroundColor = MainAppTheme.list.backyardColor
tokenView.delegate = self
tokenView.backgroundColor = MainAppTheme.list.backyardColor
tokenView.fieldName = ""
tokenView.placeholderText = localized("CreateGroupMembersPlaceholders")
tableView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
self.view.addSubview(tableView)
self.view.addSubview(tokenView)
bindTable(tableView, fade: true)
super.viewDidLoad()
}
func doNext() {
var res = IOSIntArray(length: UInt(selected.count))
for i in 0..<selected.count {
res.replaceIntAtIndex(UInt(i), withInt: selected[i].contact.getUid())
}
execute(Actor.createGroupCommandWithTitle(groupTitle, withAvatar: nil, withUids: res), successBlock: { (val) -> Void in
var gid = (val as! JavaLangInteger).intValue
if self.groupImage != nil {
Actor.changeGroupAvatar(gid, image: self.groupImage!)
}
self.navigateNext(ConversationViewController(peer: ACPeer.groupWithInt(gid)), removeCurrent: true)
}) { (val) -> Void in
}
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
var contact = objectAtIndexPath(indexPath) as! ACContact
for i in 0..<selected.count {
var n = selected[i]
if (n.contact.getUid() == contact.getUid()) {
selected.removeAtIndex(i)
tokenView.removeToken(n.token)
return
}
}
var token = CLToken(displayText: contact.getName(), context: nil)
tokenView.addToken(token)
selected.append(TokenRef(contact: contact, token: token))
filter("")
}
func tokenInputView(view: CLTokenInputView!, didChangeText text: String!) {
filter(text)
}
func tokenInputView(view: CLTokenInputView!, didChangeHeightTo height: CGFloat) {
tokenViewHeight = height
self.view.setNeedsLayout()
}
func tokenInputView(view: CLTokenInputView!, didRemoveToken token: CLToken!) {
for i in 0..<selected.count {
var n = selected[i]
if (n.token == token) {
selected.removeAtIndex(i)
return
}
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
tokenView.frame = CGRectMake(0, 64, view.frame.width, tokenViewHeight)
tableView.frame = CGRectMake(0, tokenViewHeight, view.frame.width, view.frame.height - tokenViewHeight)
}
}
private class TokenRef {
var contact: ACContact
var token: CLToken
init(contact: ACContact, token: CLToken) {
self.contact = contact
self.token = token
}
}
| 1a385b8fa31160f5551f80001dcb4a29 | 32.024194 | 161 | 0.622222 | false | false | false | false |
aliceatlas/hexagen | refs/heads/master | Hexagen/Swift/Promise.swift | mit | 1 | /*****\\\\
/ \\\\ Swift/Promise.swift
/ /\ /\ \\\\ (part of Hexagen)
\ \_X_/ ////
\ //// Copyright © 2015 Alice Atlas (see LICENSE.md)
\*****////
public class Promiselike<T> {
private var handlers: SynchronizedQueue<T -> Void>? = SynchronizedQueue()
private var shouldDischargeHandlers = DispatchOnce()
internal var value: T? {
fatalError("not implemented")
}
public func map<U>(fn: T -> U) -> MappedPromise<T, U> {
return MappedPromise(parent: self, mapping: fn)
}
public func addHandler(fn: T -> Void) {
handlers?.push(fn) ?? fn(value!)
}
private func dischargeHandlers() {
var alreadyRan = true
shouldDischargeHandlers.perform {
alreadyRan = false
let value = self.value!
let handlers = self.handlers!
self.handlers = nil
for handler in handlers.unroll() {
handler(value)
}
}
if alreadyRan {
fatalError("promise being asked to discharge handlers for a second time")
}
}
}
public class Promise<T>: Promiselike<T> {
private var shouldFulfill = DispatchOnce()
private var _value: T?
override internal var value: T? { return _value }
internal override init() {}
public init(@noescape _ fn: (T -> Void) -> Void) {
super.init()
fn(_fulfill)
}
internal func _fulfill(value: T) {
var alreadyRan = true
shouldFulfill.perform {
alreadyRan = false
printo("FULFILL \(self.sn)")
self._value = value
self.dischargeHandlers()
}
if alreadyRan {
fatalError("promise was already fulfilled")
}
}
}
public class MappedPromise<T, U>: Promiselike<U> {
private let parent: Promiselike<T>
private let mapping: T -> U
private var shouldAddParentHandler = DispatchOnce()
private var cachedValue: U?
override internal var value: U? {
if cachedValue == nil && parent.value != nil {
cachedValue = mapping(parent.value!)
}
return cachedValue
}
private init(parent: Promiselike<T>, mapping: T -> U) {
self.parent = parent
self.mapping = mapping
}
private func _parentHandler(value: T) {
dischargeHandlers()
}
public override func addHandler(handler: U -> Void) {
super.addHandler(handler)
shouldAddParentHandler.perform {
self.parent.addHandler(self._parentHandler)
}
}
}
}
| 06c5fa287fee72cde8062b43a348fa6c | 26.082474 | 85 | 0.559193 | false | false | false | false |
demmys/treeswift | refs/heads/master | src/Parser/GrammarParser.swift | bsd-2-clause | 1 | import AST
class GrammarParser {
let integerLiteral = TokenKind.IntegerLiteral(0, decimalDigits: true)
let floatingPointLiteral = TokenKind.FloatingPointLiteral(0)
let booleanLiteral = TokenKind.BooleanLiteral(true)
let stringLiteral = TokenKind.StringLiteral("")
let identifier = TokenKind.Identifier("")
let implicitParameterName = TokenKind.ImplicitParameterName(0)
let prefixOperator = TokenKind.PrefixOperator("")
let binaryOperator = TokenKind.BinaryOperator("")
let postfixOperator = TokenKind.PostfixOperator("")
let modifier = TokenKind.Modifier(.Convenience)
let ts: TokenStream
init(_ ts: TokenStream) {
self.ts = ts
}
func find(candidates: [TokenKind], startIndex: Int = 0) -> (Int, TokenKind) {
var i = startIndex
var kind = ts.look(i, skipLineFeed: false).kind
while kind != .EndOfFile {
for c in candidates {
if kind == c {
return (i, kind)
}
}
kind = ts.look(++i, skipLineFeed: false).kind
}
return (i, .EndOfFile)
}
func findInsideOfBrackets(
candidates: [TokenKind], startIndex: Int = 0
) -> (Int, TokenKind) {
var i = startIndex
var nest = 0
while true {
let kind = ts.look(i).kind
switch kind {
case .EndOfFile:
return (i, .EndOfFile)
case .LeftBracket:
++nest
case .RightBracket:
if nest == 0 {
return (i, .RightBracket)
}
--nest
default:
for c in candidates {
if kind == c {
return (i, kind)
}
}
++i
}
}
}
func findParenthesisClose(startIndex: Int = 0) -> Int? {
var i = startIndex
var nest = 0
while true {
let kind = ts.look(i).kind
switch kind {
case .EndOfFile:
return nil
case .LeftParenthesis:
++nest
case .RightParenthesis:
if nest == 0 {
return i
}
--nest
default:
++i
}
}
}
func findRightParenthesisBefore(
candidates: [TokenKind], startIndex: Int = 0
) -> Int? {
var i = startIndex
var nest = 0
while true {
let kind = ts.look(i).kind
switch kind {
case .EndOfFile:
return nil
case .LeftParenthesis:
++nest
case .RightParenthesis:
if nest == 0 {
return i
}
--nest
default:
for c in candidates {
if kind == c {
return nil
}
}
++i
}
}
}
func disjointModifiers(
var mods: [Modifier]
) throws -> (AccessLevel?, [Modifier]) {
var accessLevel: AccessLevel?
for var i = 0; i < mods.count; ++i {
switch mods[i] {
case let .AccessLevelModifier(al):
if accessLevel != nil {
try ts.error(.DuplicateAccessLevelModifier)
}
accessLevel = al
mods.removeAtIndex(i--)
default:
break
}
}
return (accessLevel, mods)
}
func isEnum(name: String) -> Bool {
return true
}
}
| c0245b02e00e874b2094806954f479f3 | 27.112782 | 81 | 0.457342 | false | false | false | false |
ManueGE/AlamofireActivityLogger | refs/heads/master | watchos Extension/InterfaceController.swift | mit | 1 | //
// InterfaceController.swift
// watchOS Extension
//
// Created by Manuel García-Estañ on 19/10/16.
// Copyright © 2016 manuege. All rights reserved.
//
import WatchKit
import Foundation
import Alamofire
import AlamofireActivityLogger
class InterfaceController: WKInterfaceController {
var prettyPrint = true
var addSeparator = true
var selectedLevel = LogLevel.all
@IBOutlet var levelPicker: WKInterfacePicker!
@IBOutlet var prettyPrintSwitch: WKInterfaceSwitch!
@IBOutlet var separatorSwitch: WKInterfaceSwitch!
override func awake(withContext context: Any?) {
super.awake(withContext: context)
prettyPrintSwitch.setOn(prettyPrint)
separatorSwitch.setOn(addSeparator)
let items: [WKPickerItem] = Constants.levelsAndNames.map { (value) in
let item = WKPickerItem()
item.title = value.1
return item;
}
levelPicker.setItems(items)
levelPicker.setSelectedItemIndex(1)
}
override func willActivate() {
super.willActivate()
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
@IBAction func didChangePrettySwitch(_ value: Bool) {
prettyPrint = value
}
@IBAction func didChangeSeparatorSwitch(_ value: Bool) {
addSeparator = value
}
@IBAction func didChangeLevelPicker(_ value: Int) {
selectedLevel = Constants.levelsAndNames[value].0
}
@IBAction func didPressSuccess() {
performRequest(success: true)
}
@IBAction func didPressFail() {
performRequest(success: false)
}
private func performRequest(success: Bool) {
// Build options
var options: [LogOption] = []
if prettyPrint {
options.append(.jsonPrettyPrint)
}
if addSeparator {
options.append(.includeSeparator)
}
Helper.performRequest(success: success,
level: selectedLevel,
options: options) {
}
}
}
| 2cb45feac2194f60784579585763d527 | 23.382979 | 80 | 0.596859 | false | false | false | false |
SwiftFS/Swift-FS-China | refs/heads/master | Sources/SwiftFSChina/configuration/Routes.swift | mit | 1 | //
// Routes.swift
// Perfect-App-Template
//
// Created by Jonathan Guthrie on 2017-02-20.
// Copyright (C) 2017 PerfectlySoft, Inc.
//
//===----------------------------------------------------------------------===//
//
// This source file is part of the Perfect.org open source project
//
// Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors
// Licensed under Apache License v2.0
//
// See http://perfect.org/licensing.html for license information
//
//===----------------------------------------------------------------------===//
//
import PerfectHTTPServer
import PerfectLib
import PerfectHTTP
import OAuth2
func mainRoutes() -> [[String: Any]] {
let dic = ApplicationConfiguration()
GitHubConfig.appid = dic.appid
GitHubConfig.secret = dic.secret
GitHubConfig.endpointAfterAuth = dic.endpointAfterAuth
GitHubConfig.redirectAfterAuth = dic.redirectAfterAuth
var routes: [[String: Any]] = [[String: Any]]()
routes.append(["method":"get", "uri":"/**", "handler":PerfectHTTPServer.HTTPHandler.staticFiles,
"documentRoot":"./webroot",
"allowRequestFilter":false,
"allowResponseFilters":true])
//github
routes.append(["method":"get", "uri":"/to/github", "handler":OAuth.sendToProvider])
//
routes.append(["method":"get", "uri":"/auth/response/github", "handler":OAuth.authResponse])
//Handler for home page
routes.append(["method":"get", "uri":"/", "handler":Handlers.index])
routes.append(["method":"get", "uri":"/index", "handler":Handlers.index])
routes.append(["method":"get", "uri":"/share", "handler":Handlers.share])
routes.append(["method":"get", "uri":"/ask", "handler":Handlers.ask])
routes.append(["method":"get", "uri":"/settings", "handler":Handlers.settings])
routes.append(["method":"get", "uri":"/about", "handler":Handlers.about])
routes.append(["method":"get", "uri":"/login", "handler":Handlers.login])
routes.append(["method":"get", "uri":"/register", "handler":Handlers.register])
routes.append(["method":"get", "uri":"/notification/**", "handler":Notification.index])
//wiki
routes.append(["method":"get", "uri":"/wiki/{path}", "handler":Wiki.index])
routes.append(["method":"get", "uri":"/wiki", "handler":Wiki.index])
routes.append(["method":"get", "uri":"/wiki/", "handler":Wiki.index])
//wiki-api
routes.append(["method":"post", "uri":"/wiki/new", "handler":Wiki.newWiki])
//user
routes.append(["method":"get", "uri":"/user/{username}/index", "handler":User.index])
routes.append(["method":"get", "uri":"/user/{username}/hot_topics", "handler":User.hotTopics])
routes.append(["method":"get", "uri":"/user/{username}/like_topics", "handler":User.likeTopics])
routes.append(["method":"get", "uri":"/user/{username}/topics", "handler":User.topics])
routes.append(["method":"get", "uri":"/user/{username}/comments", "handler":User.comments])
routes.append(["method":"get", "uri":"/user/{username}/collects", "handler":User.collects])
routes.append(["method":"get", "uri":"/user/{username}/follows", "handler":User.follows])
routes.append(["method":"post", "uri":"/user/follow", "handler":User.follow])
routes.append(["method":"post", "uri":"/user/cancel_follow", "handler":User.cancelFollow])
routes.append(["method":"get", "uri":"/user/{username}/fans", "handler":User.fans])
routes.append(["method":"post", "uri":"/user/edit", "handler":User.edit])
routes.append(["method":"post", "uri":"/user/change_pwd", "handler":User.changePwd])
//notification
routes.append(["method":"get", "uri":"/notification/all", "handler":Notification.requiredDate])
//topic
routes.append(["method":"get", "uri":"topic/{topic_id}/view", "handler":Topic.get])
routes.append(["method":"get", "uri":"topic/new", "handler":Topic.new])
routes.append(["method":"post", "uri":"topic/new", "handler":Topic.newTopic])
routes.append(["method":"post", "uri":"topic/edit", "handler":Topic.edit])
routes.append(["method":"get", "uri":"topic/{topic_id}/query", "handler":Topic.getQuery])
routes.append(["method":"get", "uri":"topic/{topic_id}/edit", "handler":Topic.editTopic])
routes.append(["method":"get", "uri":"topic/{topic_id}/delete", "handler":Topic.deleteTopic])
routes.append(["method":"post", "uri":"topic/collect", "handler":Topic.collect])
routes.append(["method":"post", "uri":"topic/like", "handler":Topic.like])
routes.append(["method":"get", "uri":"topic/cancel_like", "handler":Topic.cancleLike])
routes.append(["method":"post", "uri":"topic/cancel_collect", "handler":Topic.cancelCollect])
//comments
routes.append(["method":"get", "uri":"comments/all", "handler":Comments.getComments])
routes.append(["method":"post", "uri":"comment/new", "handler":Comments.newComment])
routes.append(["method":"get", "uri":"comment/{comment_id}/delete", "handler":Comments.delete])
//auth
routes.append(["method":"post", "uri":"/auth/sign_up", "handler":Auth.signUp])
routes.append(["method":"post", "uri":"/auth/login", "handler":Auth.login])
routes.append(["method":"get", "uri":"/auth/logout", "handler":Auth.logout])
routes.append(["method":"get", "uri":"/topics/all", "handler":Topics.topics])
//upload
routes.append(["method":"post", "uri":"/upload/avatar", "handler":Upload.avatar])
routes.append(["method":"post", "uri":"/upload/file", "handler":Upload.file])
//notification
routes.append(["method":"post", "uri":"notification/delete_all", "handler":Notification.deleteAll])
routes.append(["method":"post", "uri":"notification/mark", "handler":Notification.mark])
routes.append(["method":"post", "uri":"notification/{id}/delete", "handler":Notification.delete])
//search
routes.append(["method":"get", "uri":"search/*", "handler":Search.query])
//email
routes.append(["method":"get", "uri":"verification/{secret}", "handler":EmailAuth.verification])
routes.append(["method":"get", "uri":"email-verification", "handler":EmailAuth.emailVerification])
routes.append(["method":"post", "uri":"send-verification-mail", "handler":EmailAuth.sendVerificationMail])
return routes
}
| 225ab839ee82fb27bdc1c97fc3dad852 | 47.121212 | 110 | 0.627361 | false | false | false | false |
LedgerHQ/ledger-wallet-ios | refs/heads/master | ledger-wallet-ios/Extensions/NSDate+Utils.swift | mit | 1 | //
// NSDate+Utils.swift
// ledger-wallet-ios
//
// Created by Nicolas Bigot on 20/07/15.
// Copyright (c) 2015 Ledger. All rights reserved.
//
import Foundation
extension NSDate {
func firstMomentDate() -> NSDate {
let calendar = NSCalendar.currentCalendar()
let comps = calendar.components([.Year, .Month, .Day, .Hour, .Minute, .Second], fromDate: self)
comps.hour = 0
comps.minute = 0
comps.second = 0
return calendar.dateFromComponents(comps)!
}
} | 75a89b37419596eea94b08119d3fc50e | 22.173913 | 103 | 0.612782 | false | false | false | false |
inacioferrarini/glasgow | refs/heads/master | Example/Tests/UIKit/Controller/DataBasedViewControllerSpec.swift | mit | 1 | // The MIT License (MIT)
//
// Copyright (c) 2017 Inácio Ferrarini
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import Quick
import Nimble
@testable import Glasgow
class DataBasedViewControllerSpec: QuickSpec {
// swiftlint:disable function_body_length
override func spec() {
var dataBasedViewController: TestDataBasedViewController?
var onPerformDataSyncBlockWasCalled: Bool?
var onWillSyncDataBlockWasCalled: Bool?
var onSyncDataBlockWasCalled: Bool?
var onDidSyncDataBlockWasCalled: Bool?
var courtainView: UIView?
describe("Initialiation") {
var onPerformDataSyncBlockWasCalled = false
beforeEach {
// Given
dataBasedViewController = TestDataBasedViewController()
dataBasedViewController?.onPerformDataSync = {
onPerformDataSyncBlockWasCalled = true
}
}
it("viewWillAppear must call performDataSync") {
// When
dataBasedViewController?.viewWillAppear(false)
// Then
expect(onPerformDataSyncBlockWasCalled).to(beTruthy())
}
}
describe("Data Synchronization") {
beforeEach {
// Given
onPerformDataSyncBlockWasCalled = false
onWillSyncDataBlockWasCalled = false
onSyncDataBlockWasCalled = false
onDidSyncDataBlockWasCalled = false
dataBasedViewController = TestDataBasedViewController()
dataBasedViewController?.onPerformDataSync = {
onPerformDataSyncBlockWasCalled = true
}
dataBasedViewController?.onWillSyncData = {
onWillSyncDataBlockWasCalled = true
}
dataBasedViewController?.onSyncData = {
onSyncDataBlockWasCalled = true
}
dataBasedViewController?.onDidSyncData = {
onDidSyncDataBlockWasCalled = true
}
}
it("performDataSync, when shouldSyncData is true, must call all methods ") {
// Given
dataBasedViewController?.onShouldSyncData = {
return true
}
// When
dataBasedViewController?.performDataSync()
// Then
expect(onPerformDataSyncBlockWasCalled).to(beTruthy())
expect(onWillSyncDataBlockWasCalled).toEventually(beTruthy())
expect(onSyncDataBlockWasCalled).to(beTruthy())
expect(onDidSyncDataBlockWasCalled).to(beTruthy())
}
it("performDataSync, when shouldSyncData is false, must call only didSyncData") {
// Given
dataBasedViewController?.onShouldSyncData = {
return false
}
// When
dataBasedViewController?.performDataSync()
// Then
expect(onPerformDataSyncBlockWasCalled).to(beTruthy())
expect(onWillSyncDataBlockWasCalled).to(beFalsy())
expect(onSyncDataBlockWasCalled).to(beFalsy())
expect(onDidSyncDataBlockWasCalled).to(beTruthy())
}
}
describe("Courtain Methods") {
beforeEach {
// Given
courtainView = UIView()
dataBasedViewController = TestDataBasedViewController()
dataBasedViewController?.courtainView = courtainView
}
it("showCourtainView must show courtain") {
// Given
courtainView?.isHidden = true
// When
dataBasedViewController?.showCourtainView()
// Then
expect(courtainView?.isHidden).toEventually(beFalsy())
}
it("hideCourtainView must hide courtain") {
// Given
courtainView?.isHidden = false
// When
dataBasedViewController?.hideCourtainView()
// Then
expect(courtainView?.isHidden).toEventually(beTruthy())
}
}
}
// swiftlint:enable body_length
}
| d59e0ceddef4d51be51c46fbde0e859c | 33.3625 | 93 | 0.588396 | false | false | false | false |
luoziyong/firefox-ios | refs/heads/master | Client/Frontend/Settings/FxAContentViewController.swift | mpl-2.0 | 1 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import SnapKit
import UIKit
import WebKit
import SwiftyJSON
protocol FxAContentViewControllerDelegate: class {
func contentViewControllerDidSignIn(_ viewController: FxAContentViewController, withFlags: FxALoginFlags)
func contentViewControllerDidCancel(_ viewController: FxAContentViewController)
}
/**
* A controller that manages a single web view connected to the Firefox
* Accounts (Desktop) Sync postMessage interface.
*
* The postMessage interface is not really documented, but it is simple
* enough. I reverse engineered it from the Desktop Firefox code and the
* fxa-content-server git repository.
*/
class FxAContentViewController: SettingsContentViewController, WKScriptMessageHandler {
fileprivate enum RemoteCommand: String {
case canLinkAccount = "can_link_account"
case loaded = "loaded"
case login = "login"
case sessionStatus = "session_status"
case signOut = "sign_out"
}
weak var delegate: FxAContentViewControllerDelegate?
let profile: Profile
init(profile: Profile, fxaOptions: FxALaunchParams? = nil) {
self.profile = profile
super.init(backgroundColor: UIColor(red: 242 / 255.0, green: 242 / 255.0, blue: 242 / 255.0, alpha: 1.0), title: NSAttributedString(string: "Firefox Accounts"))
if AppConstants.MOZ_FXA_DEEP_LINK_FORM_FILL {
self.url = self.createFxAURLWith(fxaOptions, profile: profile)
} else {
self.url = profile.accountConfiguration.signInURL
}
NotificationCenter.default.addObserver(self, selector: #selector(FxAContentViewController.userDidVerify(_:)), name: NotificationFirefoxAccountVerified, object: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
NotificationCenter.default.removeObserver(self, name: NotificationFirefoxAccountVerified, object: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func makeWebView() -> WKWebView {
// Inject our setup code after the page loads.
let source = getJS()
let userScript = WKUserScript(
source: source,
injectionTime: WKUserScriptInjectionTime.atDocumentEnd,
forMainFrameOnly: true
)
// Handle messages from the content server (via our user script).
let contentController = WKUserContentController()
contentController.addUserScript(userScript)
contentController.add(LeakAvoider(delegate:self), name: "accountsCommandHandler")
let config = WKWebViewConfiguration()
config.userContentController = contentController
let webView = WKWebView(
frame: CGRect(x: 0, y: 0, width: 1, height: 1),
configuration: config
)
webView.allowsLinkPreview = false
webView.navigationDelegate = self
webView.accessibilityLabel = NSLocalizedString("Web content", comment: "Accessibility label for the main web content view")
// Don't allow overscrolling.
webView.scrollView.bounces = false
return webView
}
// Send a message to the content server.
func injectData(_ type: String, content: [String: Any]) {
let data = [
"type": type,
"content": content,
] as [String : Any]
let json = JSON(data).stringValue() ?? ""
let script = "window.postMessage(\(json), '\(self.url.absoluteString)');"
webView.evaluateJavaScript(script, completionHandler: nil)
}
fileprivate func onCanLinkAccount(_ data: JSON) {
// // We need to confirm a relink - see shouldAllowRelink for more
// let ok = shouldAllowRelink(accountData.email);
let ok = true
injectData("message", content: ["status": "can_link_account", "data": ["ok": ok]])
}
// We're not signed in to a Firefox Account at this time, which we signal by returning an error.
fileprivate func onSessionStatus(_ data: JSON) {
injectData("message", content: ["status": "error"])
}
// We're not signed in to a Firefox Account at this time. We should never get a sign out message!
fileprivate func onSignOut(_ data: JSON) {
injectData("message", content: ["status": "error"])
}
// The user has signed in to a Firefox Account. We're done!
fileprivate func onLogin(_ data: JSON) {
injectData("message", content: ["status": "login"])
let app = UIApplication.shared
let helper = FxALoginHelper.sharedInstance
helper.delegate = self
helper.application(app, didReceiveAccountJSON: data)
LeanplumIntegration.sharedInstance.setUserAttributes(attributes: [UserAttributeKeyName.signedInSync.rawValue : profile.hasAccount()])
}
@objc fileprivate func userDidVerify(_ notification: Notification) {
guard let account = profile.getAccount() else {
return
}
// We can't verify against the actionNeeded of the account,
// because of potential race conditions.
// However, we restrict visibility of this method, and make sure
// we only Notify via the FxALoginStateMachine.
let flags = FxALoginFlags(pushEnabled: account.pushRegistration != nil,
verified: true)
DispatchQueue.main.async {
self.delegate?.contentViewControllerDidSignIn(self, withFlags: flags)
}
}
// The content server page is ready to be shown.
fileprivate func onLoaded() {
self.timer?.invalidate()
self.timer = nil
self.isLoaded = true
}
// Handle a message coming from the content server.
func handleRemoteCommand(_ rawValue: String, data: JSON) {
if let command = RemoteCommand(rawValue: rawValue) {
if !isLoaded && command != .loaded {
// Work around https://github.com/mozilla/fxa-content-server/issues/2137
onLoaded()
}
switch command {
case .loaded:
onLoaded()
case .login:
onLogin(data)
case .canLinkAccount:
onCanLinkAccount(data)
case .sessionStatus:
onSessionStatus(data)
case .signOut:
onSignOut(data)
}
}
}
// Dispatch webkit messages originating from our child webview.
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
// Make sure we're communicating with a trusted page. That is, ensure the origin of the
// message is the same as the origin of the URL we initially loaded in this web view.
// Note that this exploit wouldn't be possible if we were using WebChannels; see
// https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/WebChannel.jsm
let origin = message.frameInfo.securityOrigin
guard origin.`protocol` == url.scheme && origin.host == url.host && origin.port == (url.port ?? 0) else {
print("Ignoring message - \(origin) does not match expected origin: \(url.origin ?? "nil")")
return
}
if message.name == "accountsCommandHandler" {
let body = JSON(message.body)
let detail = body["detail"]
handleRemoteCommand(detail["command"].stringValue, data: detail["data"])
}
}
// Configure the FxA signin url based on any passed options.
public func createFxAURLWith(_ fxaOptions: FxALaunchParams?, profile: Profile) -> URL {
let profileUrl = profile.accountConfiguration.signInURL
guard let launchParams = fxaOptions else {
return profileUrl
}
// Only append `signin`, `entrypoint` and `utm_*` parameters. Note that you can't
// override the service and context params.
var params = launchParams.query
params.removeValue(forKey: "service")
params.removeValue(forKey: "context")
let queryURL = params.filter { $0.key == "signin" || $0.key == "entrypoint" || $0.key.range(of: "utm_") != nil }.map({
return "\($0.key)=\($0.value)"
}).joined(separator: "&")
return URL(string: "\(profileUrl)&\(queryURL)") ?? profileUrl
}
fileprivate func getJS() -> String {
let fileRoot = Bundle.main.path(forResource: "FxASignIn", ofType: "js")
return (try! NSString(contentsOfFile: fileRoot!, encoding: String.Encoding.utf8.rawValue)) as String
}
override func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
// Ignore for now.
}
override func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
// Ignore for now.
}
}
extension FxAContentViewController: FxAPushLoginDelegate {
func accountLoginDidSucceed(withFlags flags: FxALoginFlags) {
DispatchQueue.main.async {
self.delegate?.contentViewControllerDidSignIn(self, withFlags: flags)
}
}
func accountLoginDidFail() {
DispatchQueue.main.async {
self.delegate?.contentViewControllerDidCancel(self)
}
}
}
/*
LeakAvoider prevents leaks with WKUserContentController
http://stackoverflow.com/questions/26383031/wkwebview-causes-my-view-controller-to-leak
*/
class LeakAvoider: NSObject, WKScriptMessageHandler {
weak var delegate: WKScriptMessageHandler?
init(delegate: WKScriptMessageHandler) {
self.delegate = delegate
super.init()
}
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
self.delegate?.userContentController(userContentController, didReceive: message)
}
}
| 60108a959b50b1b247dc6285ecfaa7bd | 37.881679 | 172 | 0.651909 | false | false | false | false |
raymondshadow/SwiftDemo | refs/heads/master | SwiftApp/Pods/RxGesture/Pod/Classes/RxGestureRecognizerDelegate.swift | apache-2.0 | 1 | // Copyright (c) RxSwiftCommunity
// 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.
#if os(iOS)
import UIKit
#elseif os(OSX)
import AppKit
#endif
import RxSwift
import RxCocoa
public struct GestureRecognizerDelegatePolicy<PolicyInput> {
public typealias PolicyBody = (PolicyInput) -> Bool
private let policy: PolicyBody
private init(policy: @escaping PolicyBody) {
self.policy = policy
}
public static func custom(_ policy: @escaping PolicyBody)
-> GestureRecognizerDelegatePolicy<PolicyInput> {
return .init(policy: policy)
}
public static var always: GestureRecognizerDelegatePolicy<PolicyInput> {
return .init { _ in true }
}
public static var never: GestureRecognizerDelegatePolicy<PolicyInput> {
return .init { _ in false }
}
fileprivate func isPolicyPassing(with args: PolicyInput) -> Bool {
return policy(args)
}
}
public final class RxGestureRecognizerDelegate: NSObject, GestureRecognizerDelegate {
public var beginPolicy: GestureRecognizerDelegatePolicy<GestureRecognizer> = .always
public var touchReceptionPolicy: GestureRecognizerDelegatePolicy<(GestureRecognizer, Touch)> = .always
public var selfFailureRequirementPolicy: GestureRecognizerDelegatePolicy<(GestureRecognizer, GestureRecognizer)> = .never
public var otherFailureRequirementPolicy: GestureRecognizerDelegatePolicy<(GestureRecognizer, GestureRecognizer)> = .never
public var simultaneousRecognitionPolicy: GestureRecognizerDelegatePolicy<(GestureRecognizer, GestureRecognizer)> = .always
#if os(iOS)
// Workaround because we can't have stored properties with @available annotation
private var _pressReceptionPolicy: Any?
@available(iOS 9.0, *)
public var pressReceptionPolicy: GestureRecognizerDelegatePolicy<(GestureRecognizer, UIPress)> {
get {
if let policy = _pressReceptionPolicy as? GestureRecognizerDelegatePolicy<(GestureRecognizer, UIPress)> {
return policy
}
return GestureRecognizerDelegatePolicy<(GestureRecognizer, UIPress)>.always
}
set {
_pressReceptionPolicy = newValue
}
}
#endif
#if os(OSX)
public var eventRecognitionAttemptPolicy: GestureRecognizerDelegatePolicy<(GestureRecognizer, NSEvent)> = .always
#endif
public func gestureRecognizerShouldBegin(
_ gestureRecognizer: GestureRecognizer
) -> Bool {
return beginPolicy.isPolicyPassing(with: gestureRecognizer)
}
public func gestureRecognizer(
_ gestureRecognizer: GestureRecognizer,
shouldReceive touch: Touch
) -> Bool {
return touchReceptionPolicy.isPolicyPassing(
with: (gestureRecognizer, touch)
)
}
public func gestureRecognizer(
_ gestureRecognizer: GestureRecognizer,
shouldRequireFailureOf otherGestureRecognizer: GestureRecognizer
) -> Bool {
return otherFailureRequirementPolicy.isPolicyPassing(
with: (gestureRecognizer, otherGestureRecognizer)
)
}
public func gestureRecognizer(
_ gestureRecognizer: GestureRecognizer,
shouldBeRequiredToFailBy otherGestureRecognizer: GestureRecognizer
) -> Bool {
return selfFailureRequirementPolicy.isPolicyPassing(
with: (gestureRecognizer, otherGestureRecognizer)
)
}
public func gestureRecognizer(
_ gestureRecognizer: GestureRecognizer,
shouldRecognizeSimultaneouslyWith otherGestureRecognizer: GestureRecognizer
) -> Bool {
return simultaneousRecognitionPolicy.isPolicyPassing(
with: (gestureRecognizer, otherGestureRecognizer)
)
}
#if os(iOS)
@available(iOS 9.0, *)
public func gestureRecognizer(
_ gestureRecognizer: UIGestureRecognizer,
shouldReceive press: UIPress
) -> Bool {
return pressReceptionPolicy.isPolicyPassing(
with: (gestureRecognizer, press)
)
}
#endif
#if os(OSX)
public func gestureRecognizer(
_ gestureRecognizer: NSGestureRecognizer,
shouldAttemptToRecognizeWith event: NSEvent
) -> Bool {
return eventRecognitionAttemptPolicy.isPolicyPassing(
with: (gestureRecognizer, event)
)
}
#endif
}
| e2f643a7796987195d3fbec98c3b0822 | 33.144654 | 127 | 0.708786 | false | false | false | false |
jshin47/swift-reactive-viper-example | refs/heads/master | swift-reactive-viper-sample/swift-reactive-viper-sample/GlobalReactiveUiKitFunctions.swift | mit | 1 | //
// GlobalReactiveUiKitFunctions.swift
// swift-reactive-viper-sample
//
// Created by Justin Shin on 8/21/15.
// Copyright © 2015 EmergingMed. All rights reserved.
//
import Foundation
import ObjectiveC
import UIKit
import ReactiveCocoa
func lazyAssociatedProperty<T: AnyObject>(host: AnyObject,
key: UnsafePointer<Void>, factory: ()->T) -> T {
var associatedProperty = objc_getAssociatedObject(host, key) as? T
if associatedProperty == nil {
associatedProperty = factory()
objc_setAssociatedObject(host, key, associatedProperty,
.OBJC_ASSOCIATION_RETAIN)
}
return associatedProperty!
}
func lazyMutableProperty<T>(host: AnyObject, _ key: UnsafePointer<Void>,
setter: T -> (), getter: () -> T) -> MutableProperty<T> {
return lazyAssociatedProperty(host, key: key) {
let property = MutableProperty<T>(getter())
property.producer
.start(next: {
newValue in
setter(newValue)
})
return property
}
} | 9d01c66b613f7bac025218e51a6be3e8 | 29.216216 | 74 | 0.608774 | false | false | false | false |
ajthom90/FontAwesome.swift | refs/heads/master | FontAwesome/FontAwesomeSegmentedControl.swift | mit | 1 | // FontAwesomeSegmentedControl.swift
//
// Copyright (c) 2017 Maik639
//
// 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
@IBDesignable public class FontAwesomeSegmentedControl: UISegmentedControl {
@IBInspectable public var isFontAwesomeCSSCode: Bool = true
@IBInspectable public var size: CGFloat = 22.0
public override func awakeFromNib() {
super.awakeFromNib()
useFontAwesome()
}
public override func prepareForInterfaceBuilder() {
useFontAwesome()
}
private func useFontAwesome() {
updateText {
for i in 0 ..< numberOfSegments {
if let cssCode = titleForSegment(at: i) {
setTitle(String.fontAwesomeIcon(code: cssCode), forSegmentAt: i)
}
}
}
updateFontAttributes { (state, font) in
var attributes = titleTextAttributes(for: state) ?? [:]
attributes[NSAttributedString.Key.font] = font
setTitleTextAttributes(attributes, for: state)
}
}
}
extension FontAwesomeSegmentedControl: FontAwesomeTextRepresentable {
var isTextCSSCode: Bool {
return isFontAwesomeCSSCode
}
var textSize: CGFloat {
return size
}
static func supportedStates() -> [UIControl.State] {
if #available(iOS 9.0, *) {
return [.normal, .highlighted, .disabled, .focused, .selected, .application, .reserved]
} else {
return [.normal, .highlighted, .disabled, .selected, .application, .reserved]
}
}
}
| 4ed165252de1e4dee1e89358a9aa78f9 | 34.202703 | 99 | 0.680998 | false | false | false | false |
jordanebelanger/SwiftyBluetooth | refs/heads/master | Sources/CentralProxy.swift | mit | 2 | //
// CentralProxy.swift
//
// Copyright (c) 2016 Jordane Belanger
//
// 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 CoreBluetooth
final class CentralProxy: NSObject {
fileprivate lazy var asyncStateCallbacks: [AsyncCentralStateCallback] = []
fileprivate var scanRequest: PeripheralScanRequest?
fileprivate lazy var connectRequests: [UUID: ConnectPeripheralRequest] = [:]
fileprivate lazy var disconnectRequests: [UUID: DisconnectPeripheralRequest] = [:]
var centralManager: CBCentralManager!
override init() {
super.init()
self.centralManager = CBCentralManager(delegate: self, queue: nil)
}
init(stateRestoreIdentifier: String) {
super.init()
self.centralManager = CBCentralManager(delegate: self, queue: nil, options: [CBCentralManagerOptionRestoreIdentifierKey: stateRestoreIdentifier])
}
fileprivate func postCentralEvent(_ event: NSNotification.Name, userInfo: [AnyHashable: Any]? = nil) {
NotificationCenter.default.post(
name: event,
object: Central.sharedInstance,
userInfo: userInfo)
}
}
// MARK: Initialize Bluetooth requests
extension CentralProxy {
func asyncState(_ completion: @escaping AsyncCentralStateCallback) {
switch centralManager.state {
case .unknown:
self.asyncStateCallbacks.append(completion)
case .resetting:
self.asyncStateCallbacks.append(completion)
case .unsupported:
completion(.unsupported)
case .unauthorized:
completion(.unauthorized)
case .poweredOff:
completion(.poweredOff)
case .poweredOn:
completion(.poweredOn)
@unknown default:
completion(.unknown)
}
}
func initializeBluetooth(_ completion: @escaping InitializeBluetoothCallback) {
self.asyncState { (state) in
switch state {
case .unsupported:
completion(.bluetoothUnavailable(reason: .unsupported))
case .unauthorized:
completion(.bluetoothUnavailable(reason: .unauthorized))
case .poweredOff:
completion(.bluetoothUnavailable(reason: .poweredOff))
case .poweredOn:
completion(nil)
case .unknown:
completion(.bluetoothUnavailable(reason: .unknown))
}
}
}
func callAsyncCentralStateCallback(_ state: AsyncCentralState) {
let callbacks = self.asyncStateCallbacks
self.asyncStateCallbacks.removeAll()
for callback in callbacks {
callback(state)
}
}
}
// MARK: Scan requests
private final class PeripheralScanRequest {
let callback: PeripheralScanCallback
var peripherals: [Peripheral] = []
init(callback: @escaping PeripheralScanCallback) {
self.callback = callback
}
}
extension CentralProxy {
func scanWithTimeout(_ timeout: TimeInterval, serviceUUIDs: [CBUUID]?, options: [String : Any]?, _ callback: @escaping PeripheralScanCallback) {
initializeBluetooth { [unowned self] (error) in
if let error = error {
callback(PeripheralScanResult.scanStopped(peripherals: [], error: error))
} else {
if self.scanRequest != nil {
self.centralManager.stopScan()
}
let scanRequest = PeripheralScanRequest(callback: callback)
self.scanRequest = scanRequest
scanRequest.callback(.scanStarted)
self.centralManager.scanForPeripherals(withServices: serviceUUIDs, options: options)
Timer.scheduledTimer(
timeInterval: timeout,
target: self,
selector: #selector(self.onScanTimerTick),
userInfo: Weak(value: scanRequest),
repeats: false)
}
}
}
func stopScan(error: SBError? = nil) {
// avoid an API MISUSE warning on the console if bluetooth is powered off or unsupported
if self.centralManager.state != .poweredOff, self.centralManager.state != .unsupported {
self.centralManager.stopScan()
}
if let scanRequest = self.scanRequest {
self.scanRequest = nil
scanRequest.callback(.scanStopped(peripherals: scanRequest.peripherals, error: error))
}
}
@objc fileprivate func onScanTimerTick(_ timer: Timer) {
defer {
if timer.isValid { timer.invalidate() }
}
let weakRequest = timer.userInfo as! Weak<PeripheralScanRequest>
if weakRequest.value != nil {
self.stopScan()
}
}
}
// MARK: Connect Peripheral requests
private final class ConnectPeripheralRequest {
var callbacks: [ConnectPeripheralCallback] = []
let peripheral: CBPeripheral
init(peripheral: CBPeripheral, callback: @escaping ConnectPeripheralCallback) {
self.callbacks.append(callback)
self.peripheral = peripheral
}
func invokeCallbacks(error: Error?) {
let result: Result<Void, Error> = {
if let error = error {
return .failure(error)
} else {
return .success(())
}
}()
for callback in callbacks {
callback(result)
}
}
}
extension CentralProxy {
func connect(peripheral: CBPeripheral, timeout: TimeInterval, _ callback: @escaping ConnectPeripheralCallback) {
initializeBluetooth { [unowned self] (error) in
if let error = error {
callback(.failure(error))
return
}
let uuid = peripheral.identifier
if let cbPeripheral = self.centralManager.retrievePeripherals(withIdentifiers: [uuid]).first , cbPeripheral.state == .connected {
callback(.success(()))
return
}
if let request = self.connectRequests[uuid] {
request.callbacks.append(callback)
} else {
let request = ConnectPeripheralRequest(peripheral: peripheral, callback: callback)
self.connectRequests[uuid] = request
self.centralManager.connect(peripheral, options: nil)
Timer.scheduledTimer(
timeInterval: timeout,
target: self,
selector: #selector(self.onConnectTimerTick),
userInfo: Weak(value: request),
repeats: false)
}
}
}
@objc fileprivate func onConnectTimerTick(_ timer: Timer) {
defer {
if timer.isValid { timer.invalidate() }
}
let weakRequest = timer.userInfo as! Weak<ConnectPeripheralRequest>
guard let request = weakRequest.value else {
return
}
let uuid = request.peripheral.identifier
self.connectRequests[uuid] = nil
self.centralManager.cancelPeripheralConnection(request.peripheral)
request.invokeCallbacks(error: SBError.operationTimedOut(operation: .connectPeripheral))
}
}
// MARK: Disconnect Peripheral requests
private final class DisconnectPeripheralRequest {
var callbacks: [ConnectPeripheralCallback] = []
let peripheral: CBPeripheral
init(peripheral: CBPeripheral, callback: @escaping DisconnectPeripheralCallback) {
self.callbacks.append(callback)
self.peripheral = peripheral
}
func invokeCallbacks(error: Error?) {
let result: Result<Void, Error> = {
if let error = error {
return .failure(error)
} else {
return .success(())
}
}()
for callback in callbacks {
callback(result)
}
}
}
extension CentralProxy {
func disconnect(peripheral: CBPeripheral, timeout: TimeInterval, _ callback: @escaping DisconnectPeripheralCallback) {
initializeBluetooth { [unowned self] (error) in
if let error = error {
callback(.failure(error))
return
}
let uuid = peripheral.identifier
if let cbPeripheral = self.centralManager.retrievePeripherals(withIdentifiers: [uuid]).first,
(cbPeripheral.state == .disconnected || cbPeripheral.state == .disconnecting) {
callback(.success(()))
return
}
if let request = self.disconnectRequests[uuid] {
request.callbacks.append(callback)
} else {
let request = DisconnectPeripheralRequest(peripheral: peripheral, callback: callback)
self.disconnectRequests[uuid] = request
self.centralManager.cancelPeripheralConnection(peripheral)
Timer.scheduledTimer(
timeInterval: timeout,
target: self,
selector: #selector(self.onDisconnectTimerTick),
userInfo: Weak(value: request),
repeats: false)
}
}
}
@objc fileprivate func onDisconnectTimerTick(_ timer: Timer) {
defer {
if timer.isValid { timer.invalidate() }
}
let weakRequest = timer.userInfo as! Weak<DisconnectPeripheralRequest>
guard let request = weakRequest.value else {
return
}
let uuid = request.peripheral.identifier
self.disconnectRequests[uuid] = nil
request.invokeCallbacks(error: SBError.operationTimedOut(operation: .disconnectPeripheral))
}
}
extension CentralProxy: CBCentralManagerDelegate {
func centralManagerDidUpdateState(_ central: CBCentralManager) {
postCentralEvent(Central.CentralStateChange, userInfo: ["state": central.state])
switch central.state.rawValue {
case 0: // .unknown
self.stopScan(error: .scanningEndedUnexpectedly)
case 1: // .resetting
self.stopScan(error: .scanningEndedUnexpectedly)
case 2: // .unsupported
self.callAsyncCentralStateCallback(.unsupported)
self.stopScan(error: .scanningEndedUnexpectedly)
case 3: // .unauthorized
self.callAsyncCentralStateCallback(.unauthorized)
self.stopScan(error: .scanningEndedUnexpectedly)
case 4: // .poweredOff
self.callAsyncCentralStateCallback(.poweredOff)
self.stopScan(error: .scanningEndedUnexpectedly)
case 5: // .poweredOn
self.callAsyncCentralStateCallback(.poweredOn)
default:
fatalError("Unsupported BLE CentralState")
}
}
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
let uuid = peripheral.identifier
guard let request = connectRequests[uuid] else {
return
}
connectRequests[uuid] = nil
request.invokeCallbacks(error: nil)
}
func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
let uuid = peripheral.identifier
var userInfo: [AnyHashable: Any] = ["identifier": uuid]
if let error = error {
userInfo["error"] = error
}
postCentralEvent(Central.CentralCBPeripheralDisconnected, userInfo: userInfo)
guard let request = disconnectRequests[uuid] else {
return
}
disconnectRequests[uuid] = nil
request.invokeCallbacks(error: error)
}
func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
let uuid = peripheral.identifier
guard let request = connectRequests[uuid] else {
return
}
let resolvedError: Error = error ?? SBError.peripheralFailedToConnectReasonUnknown
connectRequests[uuid] = nil
request.invokeCallbacks(error: resolvedError)
}
func centralManager(_ central: CBCentralManager,
didDiscover peripheral: CBPeripheral,
advertisementData: [String: Any],
rssi RSSI: NSNumber)
{
guard let scanRequest = scanRequest else {
return
}
let peripheral = Peripheral(peripheral: peripheral)
scanRequest.peripherals.append(peripheral)
var rssiOptional: Int? = Int(truncating: RSSI)
if let rssi = rssiOptional, rssi == 127 {
rssiOptional = nil
}
scanRequest.callback(.scanResult(peripheral: peripheral, advertisementData: advertisementData, RSSI: rssiOptional))
}
func centralManager(_ central: CBCentralManager, willRestoreState dict: [String: Any]) {
let peripherals = ((dict[CBCentralManagerRestoredStatePeripheralsKey] as? [CBPeripheral]) ?? []).map { Peripheral(peripheral: $0) }
postCentralEvent(Central.CentralManagerWillRestoreState, userInfo: ["peripherals": peripherals])
}
}
| 138c52c75cfa9a73838d7cc483ddc377 | 34.381295 | 153 | 0.604175 | false | false | false | false |
geekaurora/ReactiveListViewKit | refs/heads/master | ReactiveListViewKit/Supported Files/CZUtils/Sources/CZUtils/Extensions/UIView+.swift | mit | 1 | //
// UIView+Extension.swift
//
// Created by Cheng Zhang on 1/12/16.
// Copyright © 2016 Cheng Zhang. All rights reserved.
//
import UIKit
/// Constants for UIView extensions
public enum UIViewConstants {
public static let fadeInDuration: TimeInterval = 0.4
public static let fadeInAnimationName = "com.tony.animation.fadein"
}
// MARK: - Corner/Border
public extension UIView {
func roundToCircle() {
let width = self.bounds.size.width
layer.cornerRadius = width / 2
layer.masksToBounds = true
}
func roundCorner(_ cornerRadius: CGFloat = 2,
boarderWidth: CGFloat = 0,
boarderColor: UIColor = .clear,
shadowColor: UIColor = .clear,
shadowOffset: CGSize = .zero,
shadowRadius: CGFloat = 2,
shadowOpacity: Float = 1) {
layer.masksToBounds = true
layer.cornerRadius = cornerRadius
layer.borderColor = boarderColor.cgColor
layer.borderWidth = boarderWidth
layer.shadowColor = shadowColor.cgColor
layer.shadowOffset = shadowOffset
layer.shadowRadius = shadowRadius
}
}
// MARK: - Animations
public extension UIView {
func fadeIn(animationName: String = UIViewConstants.fadeInAnimationName,
duration: TimeInterval = UIViewConstants.fadeInDuration) {
let transition = CATransition()
transition.duration = duration
transition.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
transition.type = CATransitionType.fade
layer.add(transition, forKey: animationName)
}
}
| c7c846fbaaba7d7c4e3021b16dd0af5a | 29.77193 | 104 | 0.627138 | false | false | false | false |
somegeekintn/SimDirs | refs/heads/main | SimDirs/Model/SimModel.swift | mit | 1 | //
// SimModel.swift
// SimDirs
//
// Created by Casey Fleser on 5/24/22.
//
import Foundation
import Combine
enum SimError: Error {
case deviceParsingFailure
case invalidApp
}
struct SimDevicesUpdates {
let runtime : SimRuntime
var additions : [SimDevice]
var removals : [SimDevice]
}
class SimModel {
var deviceTypes : [SimDeviceType]
var runtimes : [SimRuntime]
var monitor : Cancellable?
let updateInterval = 2.0
var devices : [SimDevice] { runtimes.flatMap { $0.devices } }
var apps : [SimApp] { devices.flatMap { $0.apps } }
var deviceUpdates = PassthroughSubject<SimDevicesUpdates, Never>()
init() {
let simctl = SimCtl()
do {
let runtimeDevs : [String : [SimDevice]]
deviceTypes = try simctl.readAllDeviceTypes()
runtimes = try simctl.readAllRuntimes()
runtimeDevs = try simctl.readAllRuntimeDevices()
for (runtimeID, devices) in runtimeDevs {
do {
let runtimeIdx = try runtimes.indexOfMatchedOrCreated(identifier: runtimeID)
runtimes[runtimeIdx].setDevices(devices, from: deviceTypes)
}
catch {
print("Warning: Unable to create placeholder runtime from \(runtimeID)")
}
}
runtimes.sort()
devices.completeSetup(with: deviceTypes)
if !ProcessInfo.processInfo.isPreviewing {
beginMonitor()
}
}
catch {
fatalError("Failed to initialize data model:\n\(error)")
}
}
func beginMonitor() {
monitor = Timer.publish(every: updateInterval, on: .main, in: .default)
.autoconnect()
.receive(on: DispatchQueue.global(qos: .background))
.flatMap { _ in
Just((try? SimCtl().readAllRuntimeDevices()) ?? [String : [SimDevice]]())
}
.receive(on: DispatchQueue.main)
.sink { [weak self] runtimeDevs in
guard let this = self else { return }
for (runtimeID, curDevices) in runtimeDevs {
guard let runtime = this.runtimes.first(where: { $0.identifier == runtimeID }) else { print("missing runtime: \(runtimeID)"); continue }
let curDevIDs = curDevices.map { $0.udid }
let lastDevID = runtime.devices.map { $0.udid }
let updates = SimDevicesUpdates(
runtime: runtime,
additions: curDevices.filter { !lastDevID.contains($0.udid) },
removals: runtime.devices.filter { !curDevIDs.contains($0.udid) })
if !updates.removals.isEmpty || !updates.additions.isEmpty {
let idsToRemove = updates.removals.map { $0.udid }
updates.additions.completeSetup(with: this.deviceTypes)
runtime.devices.removeAll(where: { idsToRemove.contains($0.udid) })
runtime.devices.append(contentsOf: updates.additions)
this.deviceUpdates.send(updates)
}
for srcDevice in curDevices {
guard let dstDevice = runtime.devices.first(where: { $0.udid == srcDevice.udid }) else { print("missing device: \(srcDevice.udid)"); continue }
if dstDevice.updateDevice(from: srcDevice) {
print("\(dstDevice.udid) updated: \(dstDevice.state)")
}
}
}
}
}
}
| cf44200a5b5c07a118f8269a969a57f6 | 37.442308 | 167 | 0.503002 | false | false | false | false |
VladasZ/iOSTools | refs/heads/master | Sources/iOS/IBDesignable/IBDesignableView.swift | mit | 1 | //
// IBDesignableView.swift
// iOSTools
//
// Created by Vladas Zakrevskis on 7/7/17.
// Copyright © 2017 VladasZ. All rights reserved.
//
import UIKit
fileprivate func viewWithSize<T>(_ size: CGSize) -> T where T: IBDesignableView {
return T(frame: CGRect(0, 0, size.width, size.height))
}
@IBDesignable
open class IBDesignableView : UIView {
open class var defaultSize: CGSize { return CGSize(width: 100, height: 100) }
public class func fromNib() -> Self { return viewWithSize(defaultSize) }
private static var identifier: String { return String(describing: self) }
private var identifier: String { return type(of: self).identifier }
//MARK: - Initialization
public required override init(frame: CGRect) {
super.init(frame: frame)
addSubview(loadFromXib())
setup()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
addSubview(loadFromXib())
setup()
}
private func loadFromXib() -> UIView {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: identifier, bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
view.frame = self.bounds
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
return view
}
open func setup() {
}
}
| e7eabe562a8051ff0cc25dfd2b842eca | 25.867925 | 81 | 0.630618 | false | false | false | false |
borisyurkevich/Wallet | refs/heads/master | Wallet/User Interface/CarouselViewController.swift | gpl-3.0 | 1 | //
// CarouselViewController.swift
// Wallet
//
// Created by Boris Yurkevich on 30/09/2017.
// Copyright © 2017 Boris Yurkevich. All rights reserved.
//
import UIKit
enum State: Int {
case first
case second
case third
}
protocol CarouselViewControllerDelegate: class {
func updateState(newState: State)
}
class CarouselViewController: UIViewController {
weak var delegate: CarouselViewControllerDelegate?
private var animator: UIViewPropertyAnimator!
private var state = State.first
@IBOutlet weak var mainLabel: UILabel!
@IBOutlet weak var leftLabel: UILabel!
@IBOutlet weak var rightLabel: UILabel!
@IBOutlet weak var pageControl: UIPageControl!
@IBOutlet weak var leftView: UIView!
@IBOutlet weak var rightView: UIView!
@IBOutlet weak var mainView: UIView!
@IBAction func pan(_ sender: UIPanGestureRecognizer) {
switch sender.state {
case .began:
let velocity = sender.velocity(in: self.view)
if velocity.x > 0 {
// Moving forward.
animator = UIViewPropertyAnimator(duration: 1.0, controlPoint1:
mainLabel.center, controlPoint2: leftLabel.center) {
switch self.state {
case .first:
self.mainLabel.center = self.rightView.center
self.leftLabel.center = self.mainView.center
self.rightLabel.center = self.leftView.center
self.mainLabel.transform = CGAffineTransform.init(scaleX: 0.5, y: 0.5)
self.leftLabel.transform = CGAffineTransform.init(scaleX: 1.0, y: 1.0)
case .second:
self.mainLabel.center = self.leftView.center
self.leftLabel.center = self.rightView.center
self.rightLabel.center = self.mainView.center
self.rightLabel.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
self.leftLabel.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
case .third:
self.mainLabel.center = self.mainView.center
self.leftLabel.center = self.leftView.center
self.rightLabel.center = self.rightView.center
self.mainLabel.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
self.rightLabel.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
}
}
} else {
// Moving backward
animator = UIViewPropertyAnimator(duration: 1.0, controlPoint1:
mainLabel.center, controlPoint2: leftLabel.center) {
switch self.state {
case .first:
self.mainLabel.center = self.leftView.center
self.leftLabel.center = self.rightView.center
self.rightLabel.center = self.mainView.center
self.rightLabel.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
self.mainLabel.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
case .second:
self.mainLabel.center = self.mainView.center
self.leftLabel.center = self.leftView.center
self.rightLabel.center = self.rightView.center
self.leftLabel.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
self.mainLabel.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
case .third:
self.mainLabel.center = self.rightView.center
self.leftLabel.center = self.mainView.center
self.rightLabel.center = self.leftView.center
self.rightLabel.transform = CGAffineTransform.init(scaleX: 0.5, y: 0.5)
self.leftLabel.transform = CGAffineTransform.init(scaleX: 1.0, y: 1.0)
}
}
}
case .changed:
// begam
let translation = sender.translation(in: self.view)
animator.fractionComplete = abs(translation.x) / 100
case .ended:
animator.continueAnimation(withTimingParameters: nil, durationFactor: 0)
let velocity = sender.velocity(in: self.view)
if velocity.x > 0 {
// Going forward
switch self.state {
case .first:
self.state = .second
self.pageControl.currentPage = 1
case .second:
self.state = .third
self.pageControl.currentPage = 2
case .third:
self.state = .first
self.pageControl.currentPage = 0
}
} else {
// Going backward.
switch self.state {
case .first:
self.state = .third
self.pageControl.currentPage = 2
case .second:
self.state = .first
self.pageControl.currentPage = 0
case .third:
self.state = .second
self.pageControl.currentPage = 1
}
}
self.delegate?.updateState(newState: self.state)
default:
break
}
}
override func viewDidLoad() {
super.viewDidLoad()
mainLabel.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
rightLabel.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
leftLabel.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
}
}
| f22626e3f5ba3f27d7a1af07102cb645 | 39.398693 | 95 | 0.508008 | false | false | false | false |
coodly/SpriteKitUI | refs/heads/master | Sources/iOS/Shadowed.swift | apache-2.0 | 1 | /*
* Copyright 2017 Coodly LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
internal protocol ShadowingView {
var attached: View? { get set }
func extraOffset() -> CGPoint
}
internal extension ShadowingView where Self: PlatformView {
func positionAttached() {
guard let parent = superview, let attached = attached else {
return
}
let parentFrame = parent.bounds
var myPosition = CGPoint.zero
myPosition.x = frame.origin.x
myPosition.y = InFlippedEnv ? frame.minY : parentFrame.height - frame.maxY + extraOffset().y
attached.position = myPosition
attached.size = bounds.size
attached.positionChildren()
attached.revealHidded()
for sub in subviews {
sub.setNeedsLayout()
}
}
func extraOffset() -> CGPoint {
return .zero
}
}
internal class ShadowView: UIView, ShadowingView {
weak var attached: View?
override func layoutSubviews() {
super.layoutSubviews()
positionAttached()
}
}
internal class ShadowButton: UIButton, ShadowingView {
weak var attached: View?
override func layoutSubviews() {
super.layoutSubviews()
positionAttached()
}
}
internal class ShadowScrollView: UIScrollView, ShadowingView {
weak var attached: View?
override func layoutSubviews() {
super.layoutSubviews()
positionAttached()
}
func extraOffset() -> CGPoint {
return contentOffset
}
}
internal class ShadowStackView: UIStackView, ShadowingView {
weak var attached: View?
override func layoutSubviews() {
super.layoutSubviews()
positionAttached()
}
}
| 9159c252c380db921f8dcf57b6a91b06 | 24.152174 | 100 | 0.643042 | false | false | false | false |
openboy2012/FlickerNumber | refs/heads/master | Swift/FlickerNumber-Swift/ViewController.swift | mit | 1 | //
// ViewController.swift
// FlickerNumber
//
// Created by DeJohn Dong on 15/10/23.
// Copyright © 2015年 DDKit. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var label : UILabel!
@IBOutlet weak var fnSwitch : UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// label?.fn_setNumber(1234.1234)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.valueChanged(self.fnSwitch)
}
@IBAction func valueChanged(_ sender : UISwitch) {
if sender.isOn {
if self.title == "Flicker An Integer Number" {
label?.fn_setNumber(1234442218, formatter: nil)
} else if self.title == "Flicker A Float Number" {
label?.fn_setNumber(123456789.123456, formatter: nil)
} else if self.title == "Flicker A Format Number" {
label?.fn_setNumber(1234512, format:"$%@", formatter: nil)
} else if self.title == "Flicker An Attribute Number" {
let colorDict = [NSAttributedStringKey.foregroundColor: UIColor.red]
let range = NSRange(location: 2, length: 2)
let attribute = NSDictionary.fn_dictionary(colorDict, range: range)
label?.fn_setNumber(12345.212, formatter: nil, attributes: attribute)
} else {
let colorDict = [NSAttributedStringKey.foregroundColor: UIColor.red]
let colorRange = NSRange(location: 1, length: 2)
let colorAttribute = NSDictionary.fn_dictionary(colorDict, range: colorRange)
let fontDict = [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 12)]
let fontRange = NSRange(location: 3, length: 4)
let fontAttribute = NSDictionary.fn_dictionary(fontDict, range: fontRange)
let attributes = [colorAttribute, fontAttribute]
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .currency
numberFormatter.formatterBehavior = .behavior10_4
label?.fn_setNumber(123456.789, format:"%@", formatter:numberFormatter, attributes: attributes)
}
} else {
if self.title == "Flicker An Integer Number" {
label?.fn_setNumber(1235566321)
} else if self.title == "Flicker A Float Number" {
label?.fn_setNumber(123456789.123456)
} else if self.title == "Flicker A Format Number" {
label?.fn_setNumber(91, format:"$%.2f")
} else if self.title == "Flicker An Attribute Number" {
let colorDict = [NSAttributedStringKey.foregroundColor: UIColor.red]
let range = NSRange(location: 2, length: 2)
let attribute = NSDictionary.fn_dictionary(colorDict, range: range)
label?.fn_setNumber(48273.38, attributes: attribute)
} else {
let colorDict = [NSAttributedStringKey.foregroundColor: UIColor.red]
let colorRange = NSRange(location: 1, length: 2)
let colorAttribute = NSDictionary.fn_dictionary(colorDict, range: colorRange)
let fontDict = [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 12)]
let fontRange = NSRange(location: 3, length: 4)
let fontAttribute = NSDictionary.fn_dictionary(fontDict, range: fontRange)
let attributes = [colorAttribute, fontAttribute]
label?.fn_setNumber(987654.321, format:"¥%.3f", attributes: attributes)
}
}
}
}
| 0b5da6d15a3ad3e42a64640741bd5fee | 47.525641 | 111 | 0.606341 | false | false | false | false |
austinzheng/swift | refs/heads/master | stdlib/public/core/VarArgs.swift | apache-2.0 | 2 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A type whose instances can be encoded, and appropriately passed, as
/// elements of a C `va_list`.
///
/// You use this protocol to present a native Swift interface to a C "varargs"
/// API. For example, a program can import a C API like the one defined here:
///
/// ~~~c
/// int c_api(int, va_list arguments)
/// ~~~
///
/// To create a wrapper for the `c_api` function, write a function that takes
/// `CVarArg` arguments, and then call the imported C function using the
/// `withVaList(_:_:)` function:
///
/// func swiftAPI(_ x: Int, arguments: CVarArg...) -> Int {
/// return withVaList(arguments) { c_api(x, $0) }
/// }
///
/// Swift only imports C variadic functions that use a `va_list` for their
/// arguments. C functions that use the `...` syntax for variadic arguments
/// are not imported, and therefore can't be called using `CVarArg` arguments.
///
/// If you need to pass an optional pointer as a `CVarArg` argument, use the
/// `Int(bitPattern:)` initializer to interpret the optional pointer as an
/// `Int` value, which has the same C variadic calling conventions as a pointer
/// on all supported platforms.
///
/// - Note: Declaring conformance to the `CVarArg` protocol for types defined
/// outside the standard library is not supported.
public protocol CVarArg {
// Note: the protocol is public, but its requirement is stdlib-private.
// That's because there are APIs operating on CVarArg instances, but
// defining conformances to CVarArg outside of the standard library is
// not supported.
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
var _cVarArgEncoding: [Int] { get }
}
/// Floating point types need to be passed differently on x86_64
/// systems. CoreGraphics uses this to make CGFloat work properly.
public // SPI(CoreGraphics)
protocol _CVarArgPassedAsDouble : CVarArg {}
/// Some types require alignment greater than Int on some architectures.
public // SPI(CoreGraphics)
protocol _CVarArgAligned : CVarArg {
/// Returns the required alignment in bytes of
/// the value returned by `_cVarArgEncoding`.
var _cVarArgAlignment: Int { get }
}
#if arch(x86_64)
@usableFromInline
internal let _countGPRegisters = 6
// Note to future visitors concerning the following SSE register count.
//
// AMD64-ABI section 3.5.7 says -- as recently as v0.99.7, Nov 2014 -- to make
// room in the va_list register-save area for 16 SSE registers (XMM0..15). This
// may seem surprising, because the calling convention of that ABI only uses the
// first 8 SSE registers for argument-passing; why save the other 8?
//
// According to a comment in X86_64ABIInfo::EmitVAArg, in clang's TargetInfo,
// the AMD64-ABI spec is itself in error on this point ("NOTE: 304 is a typo").
// This comment (and calculation) in clang has been there since varargs support
// was added in 2009, in rev be9eb093; so if you're about to change this value
// from 8 to 16 based on reading the spec, probably the bug you're looking for
// is elsewhere.
@usableFromInline
internal let _countFPRegisters = 8
@usableFromInline
internal let _fpRegisterWords = 2
@usableFromInline
internal let _registerSaveWords = _countGPRegisters + _countFPRegisters * _fpRegisterWords
#elseif arch(s390x)
@usableFromInline
internal let _countGPRegisters = 16
@usableFromInline
internal let _registerSaveWords = _countGPRegisters
#elseif arch(arm64) && os(Linux)
// ARM Procedure Call Standard for aarch64. (IHI0055B)
// The va_list type may refer to any parameter in a parameter list may be in one
// of three memory locations depending on its type and position in the argument
// list :
// 1. GP register save area x0 - x7
// 2. 128-bit FP/SIMD register save area q0 - q7
// 3. Stack argument area
@usableFromInline
internal let _countGPRegisters = 8
@usableFromInline
internal let _countFPRegisters = 8
@usableFromInline
internal let _fpRegisterWords = 16 / MemoryLayout<Int>.size
@usableFromInline
internal let _registerSaveWords = _countGPRegisters + (_countFPRegisters * _fpRegisterWords)
#endif
#if arch(s390x)
@usableFromInline
internal typealias _VAUInt = CUnsignedLongLong
@usableFromInline
internal typealias _VAInt = Int64
#else
@usableFromInline
internal typealias _VAUInt = CUnsignedInt
@usableFromInline
internal typealias _VAInt = Int32
#endif
/// Invokes the given closure with a C `va_list` argument derived from the
/// given array of arguments.
///
/// The pointer passed as an argument to `body` is valid only during the
/// execution of `withVaList(_:_:)`. Do not store or return the pointer for
/// later use.
///
/// If you need to pass an optional pointer as a `CVarArg` argument, use the
/// `Int(bitPattern:)` initializer to interpret the optional pointer as an
/// `Int` value, which has the same C variadic calling conventions as a pointer
/// on all supported platforms.
///
/// - Parameters:
/// - args: An array of arguments to convert to a C `va_list` pointer.
/// - body: A closure with a `CVaListPointer` parameter that references the
/// arguments passed as `args`. If `body` has a return value, that value
/// is also used as the return value for the `withVaList(_:)` function.
/// The pointer argument is valid only for the duration of the function's
/// execution.
/// - Returns: The return value, if any, of the `body` closure parameter.
@inlinable // c-abi
public func withVaList<R>(_ args: [CVarArg],
_ body: (CVaListPointer) -> R) -> R {
let builder = __VaListBuilder()
for a in args {
builder.append(a)
}
return _withVaList(builder, body)
}
/// Invoke `body` with a C `va_list` argument derived from `builder`.
@inlinable // c-abi
internal func _withVaList<R>(
_ builder: __VaListBuilder,
_ body: (CVaListPointer) -> R
) -> R {
let result = body(builder.va_list())
_fixLifetime(builder)
return result
}
#if _runtime(_ObjC)
// Excluded due to use of dynamic casting and Builtin.autorelease, neither
// of which correctly work without the ObjC Runtime right now.
// See rdar://problem/18801510
/// Returns a `CVaListPointer` that is backed by autoreleased storage, built
/// from the given array of arguments.
///
/// You should prefer `withVaList(_:_:)` instead of this function. In some
/// uses, such as in a `class` initializer, you may find that the language
/// rules do not allow you to use `withVaList(_:_:)` as intended.
///
/// If you need to pass an optional pointer as a `CVarArg` argument, use the
/// `Int(bitPattern:)` initializer to interpret the optional pointer as an
/// `Int` value, which has the same C variadic calling conventions as a pointer
/// on all supported platforms.
///
/// - Parameter args: An array of arguments to convert to a C `va_list`
/// pointer.
/// - Returns: A pointer that can be used with C functions that take a
/// `va_list` argument.
@inlinable // c-abi
public func getVaList(_ args: [CVarArg]) -> CVaListPointer {
let builder = __VaListBuilder()
for a in args {
builder.append(a)
}
// FIXME: Use some Swift equivalent of NS_RETURNS_INNER_POINTER if we get one.
Builtin.retain(builder)
Builtin.autorelease(builder)
return builder.va_list()
}
#endif
@inlinable // c-abi
public func _encodeBitsAsWords<T>(_ x: T) -> [Int] {
let result = [Int](
repeating: 0,
count: (MemoryLayout<T>.size + MemoryLayout<Int>.size - 1) / MemoryLayout<Int>.size)
_internalInvariant(result.count > 0)
var tmp = x
// FIXME: use UnsafeMutablePointer.assign(from:) instead of memcpy.
_memcpy(dest: UnsafeMutablePointer(result._baseAddressIfContiguous!),
src: UnsafeMutablePointer(Builtin.addressof(&tmp)),
size: UInt(MemoryLayout<T>.size))
return result
}
// CVarArg conformances for the integer types. Everything smaller
// than an Int32 must be promoted to Int32 or CUnsignedInt before
// encoding.
// Signed types
extension Int : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@inlinable // c-abi
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
}
extension Bool : CVarArg {
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(_VAInt(self ? 1:0))
}
}
extension Int64 : CVarArg, _CVarArgAligned {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@inlinable // c-abi
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
/// Returns the required alignment in bytes of
/// the value returned by `_cVarArgEncoding`.
@inlinable // c-abi
public var _cVarArgAlignment: Int {
// FIXME: alignof differs from the ABI alignment on some architectures
return MemoryLayout.alignment(ofValue: self)
}
}
extension Int32 : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@inlinable // c-abi
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(_VAInt(self))
}
}
extension Int16 : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@inlinable // c-abi
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(_VAInt(self))
}
}
extension Int8 : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@inlinable // c-abi
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(_VAInt(self))
}
}
// Unsigned types
extension UInt : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@inlinable // c-abi
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
}
extension UInt64 : CVarArg, _CVarArgAligned {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@inlinable // c-abi
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
/// Returns the required alignment in bytes of
/// the value returned by `_cVarArgEncoding`.
@inlinable // c-abi
public var _cVarArgAlignment: Int {
// FIXME: alignof differs from the ABI alignment on some architectures
return MemoryLayout.alignment(ofValue: self)
}
}
extension UInt32 : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@inlinable // c-abi
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(_VAUInt(self))
}
}
extension UInt16 : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@inlinable // c-abi
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(_VAUInt(self))
}
}
extension UInt8 : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@inlinable // c-abi
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(_VAUInt(self))
}
}
extension OpaquePointer : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@inlinable // c-abi
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
}
extension UnsafePointer : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@inlinable // c-abi
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
}
extension UnsafeMutablePointer : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@inlinable // c-abi
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
}
#if _runtime(_ObjC)
extension AutoreleasingUnsafeMutablePointer : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@inlinable
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
}
#endif
extension Float : _CVarArgPassedAsDouble, _CVarArgAligned {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@inlinable // c-abi
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(Double(self))
}
/// Returns the required alignment in bytes of
/// the value returned by `_cVarArgEncoding`.
@inlinable // c-abi
public var _cVarArgAlignment: Int {
// FIXME: alignof differs from the ABI alignment on some architectures
return MemoryLayout.alignment(ofValue: Double(self))
}
}
extension Double : _CVarArgPassedAsDouble, _CVarArgAligned {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@inlinable // c-abi
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
/// Returns the required alignment in bytes of
/// the value returned by `_cVarArgEncoding`.
@inlinable // c-abi
public var _cVarArgAlignment: Int {
// FIXME: alignof differs from the ABI alignment on some architectures
return MemoryLayout.alignment(ofValue: self)
}
}
#if !os(Windows) && (arch(i386) || arch(x86_64))
extension Float80 : CVarArg, _CVarArgAligned {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@inlinable // FIXME(sil-serialize-all)
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
/// Returns the required alignment in bytes of
/// the value returned by `_cVarArgEncoding`.
@inlinable // FIXME(sil-serialize-all)
public var _cVarArgAlignment: Int {
// FIXME: alignof differs from the ABI alignment on some architectures
return MemoryLayout.alignment(ofValue: self)
}
}
#endif
#if arch(x86_64) || arch(s390x)
/// An object that can manage the lifetime of storage backing a
/// `CVaListPointer`.
// NOTE: older runtimes called this _VaListBuilder. The two must
// coexist, so it was renamed. The old name must not be used in the new
// runtime.
@_fixed_layout
@usableFromInline // c-abi
final internal class __VaListBuilder {
@_fixed_layout // c-abi
@usableFromInline
internal struct Header {
@inlinable // c-abi
internal init() {}
@usableFromInline // c-abi
internal var gp_offset = CUnsignedInt(0)
@usableFromInline // c-abi
internal var fp_offset =
CUnsignedInt(_countGPRegisters * MemoryLayout<Int>.stride)
@usableFromInline // c-abi
internal var overflow_arg_area: UnsafeMutablePointer<Int>?
@usableFromInline // c-abi
internal var reg_save_area: UnsafeMutablePointer<Int>?
}
@usableFromInline // c-abi
internal var gpRegistersUsed = 0
@usableFromInline // c-abi
internal var fpRegistersUsed = 0
@usableFromInline // c-abi
final // Property must be final since it is used by Builtin.addressof.
internal var header = Header()
@usableFromInline // c-abi
internal var storage: ContiguousArray<Int>
@inlinable // c-abi
internal init() {
// prepare the register save area
storage = ContiguousArray(repeating: 0, count: _registerSaveWords)
}
@inlinable // c-abi
deinit {}
@inlinable // c-abi
internal func append(_ arg: CVarArg) {
var encoded = arg._cVarArgEncoding
#if arch(x86_64)
let isDouble = arg is _CVarArgPassedAsDouble
if isDouble && fpRegistersUsed < _countFPRegisters {
var startIndex = _countGPRegisters
+ (fpRegistersUsed * _fpRegisterWords)
for w in encoded {
storage[startIndex] = w
startIndex += 1
}
fpRegistersUsed += 1
}
else if encoded.count == 1
&& !isDouble
&& gpRegistersUsed < _countGPRegisters {
storage[gpRegistersUsed] = encoded[0]
gpRegistersUsed += 1
}
else {
for w in encoded {
storage.append(w)
}
}
#elseif arch(s390x)
if gpRegistersUsed < _countGPRegisters {
for w in encoded {
storage[gpRegistersUsed] = w
gpRegistersUsed += 1
}
} else {
for w in encoded {
storage.append(w)
}
}
#endif
}
@inlinable // c-abi
internal func va_list() -> CVaListPointer {
header.reg_save_area = storage._baseAddress
header.overflow_arg_area
= storage._baseAddress + _registerSaveWords
return CVaListPointer(
_fromUnsafeMutablePointer: UnsafeMutableRawPointer(
Builtin.addressof(&self.header)))
}
}
#elseif arch(arm64) && os(Linux)
// NOTE: older runtimes called this _VaListBuilder. The two must
// coexist, so it was renamed. The old name must not be used in the new
// runtime.
@_fixed_layout // FIXME(sil-serialize-all)
@usableFromInline // FIXME(sil-serialize-all)
final internal class __VaListBuilder {
@usableFromInline // FIXME(sil-serialize-all)
internal init() {
// Prepare the register save area.
allocated = _registerSaveWords
storage = allocStorage(wordCount: allocated)
// Append stack arguments after register save area.
count = allocated
}
@usableFromInline // FIXME(sil-serialize-all)
deinit {
if let allocatedStorage = storage {
deallocStorage(wordCount: allocated, storage: allocatedStorage)
}
}
@usableFromInline // FIXME(sil-serialize-all)
internal func append(_ arg: CVarArg) {
var encoded = arg._cVarArgEncoding
if arg is _CVarArgPassedAsDouble
&& fpRegistersUsed < _countFPRegisters {
var startIndex = (fpRegistersUsed * _fpRegisterWords)
for w in encoded {
storage[startIndex] = w
startIndex += 1
}
fpRegistersUsed += 1
} else if encoded.count == 1
&& !(arg is _CVarArgPassedAsDouble)
&& gpRegistersUsed < _countGPRegisters {
var startIndex = ( _fpRegisterWords * _countFPRegisters) + gpRegistersUsed
storage[startIndex] = encoded[0]
gpRegistersUsed += 1
} else {
// Arguments in stack slot.
appendWords(encoded)
}
}
@usableFromInline // FIXME(sil-serialize-all)
internal func va_list() -> CVaListPointer {
let vr_top = storage + (_fpRegisterWords * _countFPRegisters)
let gr_top = vr_top + _countGPRegisters
return CVaListPointer(__stack: gr_top, __gr_top: gr_top,
__vr_top: vr_top, __gr_off: -64, __vr_off: -128)
}
@usableFromInline // FIXME(sil-serialize-all)
internal func appendWords(_ words: [Int]) {
let newCount = count + words.count
if newCount > allocated {
let oldAllocated = allocated
let oldStorage = storage
let oldCount = count
allocated = max(newCount, allocated * 2)
let newStorage = allocStorage(wordCount: allocated)
storage = newStorage
// Count is updated below.
if let allocatedOldStorage = oldStorage {
newStorage.moveInitialize(from: allocatedOldStorage, count: oldCount)
deallocStorage(wordCount: oldAllocated, storage: allocatedOldStorage)
}
}
let allocatedStorage = storage!
for word in words {
allocatedStorage[count] = word
count += 1
}
}
@usableFromInline // FIXME(sil-serialize-all)
internal func rawSizeAndAlignment(
_ wordCount: Int
) -> (Builtin.Word, Builtin.Word) {
return ((wordCount * MemoryLayout<Int>.stride)._builtinWordValue,
requiredAlignmentInBytes._builtinWordValue)
}
@usableFromInline // FIXME(sil-serialize-all)
internal func allocStorage(wordCount: Int) -> UnsafeMutablePointer<Int> {
let (rawSize, rawAlignment) = rawSizeAndAlignment(wordCount)
let rawStorage = Builtin.allocRaw(rawSize, rawAlignment)
return UnsafeMutablePointer<Int>(rawStorage)
}
@usableFromInline // FIXME(sil-serialize-all)
internal func deallocStorage(
wordCount: Int, storage: UnsafeMutablePointer<Int>
) {
let (rawSize, rawAlignment) = rawSizeAndAlignment(wordCount)
Builtin.deallocRaw(storage._rawValue, rawSize, rawAlignment)
}
@usableFromInline // FIXME(sil-serialize-all)
internal let requiredAlignmentInBytes = MemoryLayout<Double>.alignment
@usableFromInline // FIXME(sil-serialize-all)
internal var count = 0
@usableFromInline // FIXME(sil-serialize-all)
internal var allocated = 0
@usableFromInline // FIXME(sil-serialize-all)
internal var storage: UnsafeMutablePointer<Int>!
@usableFromInline // FIXME(sil-serialize-all)
internal var gpRegistersUsed = 0
@usableFromInline // FIXME(sil-serialize-all)
internal var fpRegistersUsed = 0
@usableFromInline // FIXME(sil-serialize-all)
internal var overflowWordsUsed = 0
}
#else
/// An object that can manage the lifetime of storage backing a
/// `CVaListPointer`.
// NOTE: older runtimes called this _VaListBuilder. The two must
// coexist, so it was renamed. The old name must not be used in the new
// runtime.
@_fixed_layout
@usableFromInline // c-abi
final internal class __VaListBuilder {
@inlinable // c-abi
internal init() {}
@inlinable // c-abi
internal func append(_ arg: CVarArg) {
// Write alignment padding if necessary.
// This is needed on architectures where the ABI alignment of some
// supported vararg type is greater than the alignment of Int, such
// as non-iOS ARM. Note that we can't use alignof because it
// differs from ABI alignment on some architectures.
#if arch(arm) && !os(iOS)
if let arg = arg as? _CVarArgAligned {
let alignmentInWords = arg._cVarArgAlignment / MemoryLayout<Int>.size
let misalignmentInWords = count % alignmentInWords
if misalignmentInWords != 0 {
let paddingInWords = alignmentInWords - misalignmentInWords
appendWords([Int](repeating: -1, count: paddingInWords))
}
}
#endif
// Write the argument's value itself.
appendWords(arg._cVarArgEncoding)
}
// NB: This function *cannot* be @inlinable because it expects to project
// and escape the physical storage of `__VaListBuilder.alignedStorageForEmptyVaLists`.
// Marking it inlinable will cause it to resiliently use accessors to
// project `__VaListBuilder.alignedStorageForEmptyVaLists` as a computed
// property.
@usableFromInline // c-abi
internal func va_list() -> CVaListPointer {
// Use Builtin.addressof to emphasize that we are deliberately escaping this
// pointer and assuming it is safe to do so.
let emptyAddr = UnsafeMutablePointer<Int>(
Builtin.addressof(&__VaListBuilder.alignedStorageForEmptyVaLists))
return CVaListPointer(_fromUnsafeMutablePointer: storage ?? emptyAddr)
}
// Manage storage that is accessed as Words
// but possibly more aligned than that.
// FIXME: this should be packaged into a better storage type
@inlinable // c-abi
internal func appendWords(_ words: [Int]) {
let newCount = count + words.count
if newCount > allocated {
let oldAllocated = allocated
let oldStorage = storage
let oldCount = count
allocated = max(newCount, allocated * 2)
let newStorage = allocStorage(wordCount: allocated)
storage = newStorage
// count is updated below
if let allocatedOldStorage = oldStorage {
newStorage.moveInitialize(from: allocatedOldStorage, count: oldCount)
deallocStorage(wordCount: oldAllocated, storage: allocatedOldStorage)
}
}
let allocatedStorage = storage!
for word in words {
allocatedStorage[count] = word
count += 1
}
}
@inlinable // c-abi
internal func rawSizeAndAlignment(
_ wordCount: Int
) -> (Builtin.Word, Builtin.Word) {
return ((wordCount * MemoryLayout<Int>.stride)._builtinWordValue,
requiredAlignmentInBytes._builtinWordValue)
}
@inlinable // c-abi
internal func allocStorage(wordCount: Int) -> UnsafeMutablePointer<Int> {
let (rawSize, rawAlignment) = rawSizeAndAlignment(wordCount)
let rawStorage = Builtin.allocRaw(rawSize, rawAlignment)
return UnsafeMutablePointer<Int>(rawStorage)
}
@usableFromInline // c-abi
internal func deallocStorage(
wordCount: Int,
storage: UnsafeMutablePointer<Int>
) {
let (rawSize, rawAlignment) = rawSizeAndAlignment(wordCount)
Builtin.deallocRaw(storage._rawValue, rawSize, rawAlignment)
}
@inlinable // c-abi
deinit {
if let allocatedStorage = storage {
deallocStorage(wordCount: allocated, storage: allocatedStorage)
}
}
// FIXME: alignof differs from the ABI alignment on some architectures
@usableFromInline // c-abi
internal let requiredAlignmentInBytes = MemoryLayout<Double>.alignment
@usableFromInline // c-abi
internal var count = 0
@usableFromInline // c-abi
internal var allocated = 0
@usableFromInline // c-abi
internal var storage: UnsafeMutablePointer<Int>?
internal static var alignedStorageForEmptyVaLists: Double = 0
}
#endif
| a4a1b707aa4087f5ad4e43187cd1f07f | 32 | 92 | 0.698265 | false | false | false | false |
mrommel/TreasureDungeons | refs/heads/master | TreasureDungeons/Source/OpenGL/Camera.swift | apache-2.0 | 1 | //
// Camera.swift
// TreasureDungeons
//
// Created by Michael Rommel on 26.06.17.
// Copyright © 2017 BurtK. All rights reserved.
//
import Foundation
import GLKit
protocol CameraChangeListener {
func moveCameraTo(x: Float, andY y: Float, withYaw yaw: Float)
}
class Camera {
fileprivate var pitch: Float = 0
fileprivate var yaw: Float = 0
//fileprivate var roll: Float = 0
var x: Float = -2
var y: Float = -2
fileprivate var changeListeners: [CameraChangeListener] = []
init() {
}
var viewMatrix: GLKMatrix4 {
get {
var viewMatrix: GLKMatrix4 = GLKMatrix4Identity
viewMatrix = GLKMatrix4RotateX(viewMatrix, GLKMathDegreesToRadians(self.pitch))
viewMatrix = GLKMatrix4RotateY(viewMatrix, GLKMathDegreesToRadians(self.yaw))
//viewMatrix = GLKMatrix4RotateZ(viewMatrix, GLKMathDegreesToRadians(self.roll))
viewMatrix = GLKMatrix4Translate(viewMatrix, self.x, 0, self.y)
return viewMatrix
}
}
var positionOnMap: Point {
get {
return Point(x: -Int((self.x - 1.0) / 2.0) , y: -Int((self.y - 1.0) / 2.0))
}
}
var predictedPositionOnMap: Point {
get {
let newX = self.x - sin(GLKMathDegreesToRadians(self.yaw)) * 0.5
let newY = self.y + cos(GLKMathDegreesToRadians(self.yaw)) * 0.5
return Point(x: -Int((newX - 1.0) / 2.0) , y: -Int((newY - 1.0) / 2.0))
}
}
func moveForward() {
self.x = self.x - sin(GLKMathDegreesToRadians(self.yaw)) * 0.5
self.y = self.y + cos(GLKMathDegreesToRadians(self.yaw)) * 0.5
for changeListener in self.changeListeners {
changeListener.moveCameraTo(x: self.x, andY: self.y, withYaw: self.yaw)
}
}
func turn(leftAndRight value: Float) {
self.yaw -= value
for changeListener in self.changeListeners {
changeListener.moveCameraTo(x: self.x, andY: self.y, withYaw: self.yaw)
}
}
func reset() {
self.pitch = self.pitch * 0.95
}
func addChangeListener(changeListener: CameraChangeListener) {
self.changeListeners.append(changeListener)
}
}
| 99a24982b0579a63c41fc993fd76aee9 | 27.170732 | 92 | 0.591775 | false | false | false | false |
jkusnier/WorkoutMerge | refs/heads/master | WorkoutMerge/SyncAllTableViewController.swift | mit | 1 | //
// SyncAllTableViewController.swift
// WorkoutMerge
//
// Created by Jason Kusnier on 9/12/15.
// Copyright (c) 2015 Jason Kusnier. All rights reserved.
//
import UIKit
import HealthKit
import CoreData
class SyncAllTableViewController: UITableViewController {
var workoutSyncAPI: WorkoutSyncAPI?
let hkStore = HKHealthStore()
typealias WorkoutRecord = (startDate: NSDate, durationLabel: String, workoutTypeLabel: String, checked: Bool, workoutDetails: WorkoutSyncAPI.WorkoutDetails?)
typealias Workout = [WorkoutRecord]
var workouts: Workout = []
let managedContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext!
var syncButton: UIBarButtonItem?
override func viewDidLoad() {
super.viewDidLoad()
self.syncButton = UIBarButtonItem(title: "Sync All", style: .Plain, target: self, action: "syncItems")
self.syncButton?.possibleTitles = ["Sync All", "Sync Selected"];
navigationItem.rightBarButtonItem = self.syncButton
if !HKHealthStore.isHealthDataAvailable() {
print("HealthKit Not Available")
// self.healthKitAvailable = false
// self.refreshControl.removeFromSuperview()
} else {
let readTypes = Set(arrayLiteral:
HKObjectType.workoutType(),
HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)!
)
hkStore.requestAuthorizationToShareTypes(nil, readTypes: readTypes, completion: { (success: Bool, err: NSError?) -> () in
let actInd : UIActivityIndicatorView = UIActivityIndicatorView(frame: CGRectMake(0,0, 50, 50)) as UIActivityIndicatorView
actInd.center = self.view.center
actInd.hidesWhenStopped = true
actInd.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
self.view.addSubview(actInd)
actInd.startAnimating()
if success {
self.readWorkOuts({(results: [AnyObject]!, error: NSError!) -> () in
if let results = results as? [HKWorkout] {
dispatch_async(dispatch_get_main_queue()) {
self.workouts = []
var queue = results.count
for workout in results {
queue--
if let _ = self.managedObject(workout) {
// Verify the workout hasn't already been synced
// If the last item was already synced, we will stop the progress
// FIXME this should be done with a timer
if queue == 0 {
// TODO Check the timer status, cancel if needed
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
actInd.stopAnimating()
}
}
} else {
let totalDistance: Double? = (workout.totalDistance != nil) ? workout.totalDistance!.doubleValueForUnit(HKUnit.meterUnit()) : nil
let totalEnergyBurned: Double? = workout.totalEnergyBurned != nil ? workout.totalEnergyBurned!.doubleValueForUnit(HKUnit.kilocalorieUnit()) : nil
let activityType = self.workoutSyncAPI?.activityType(workout.workoutActivityType)
var workoutRecord = (workout.UUID, type: activityType, startTime: workout.startDate, totalDistance: totalDistance, duration: workout.duration, averageHeartRate: nil, totalCalories: totalEnergyBurned, notes: nil, otherType: nil, activityName: nil) as WorkoutSyncAPI.WorkoutDetails
let queue = queue
self.averageHeartRateForWorkout(workout, success: { d in
if let d = d {
workoutRecord.averageHeartRate = Int(d)
}
self.workouts.append((startDate: workout.startDate, durationLabel: self.stringFromTimeInterval(workout.duration), workoutTypeLabel: HKWorkoutActivityType.hkDescription(workout.workoutActivityType), checked: false, workoutDetails: workoutRecord) as WorkoutRecord)
if queue == 0 {
// TODO Check timer, cancel and reset
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
actInd.stopAnimating()
}
}
}, tryAgain: true)
}
}
}
}
})
} else {
actInd.stopAnimating()
}
})
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.workouts.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCellWithIdentifier("syncAllCell") as? WorkoutTableViewCell {
let workout = self.workouts[indexPath.row]
let startDate = workout.startDate.relativeDateFormat()
if workout.checked {
cell.accessoryType = .Checkmark
} else {
cell.accessoryType = .None
}
cell.startTimeLabel?.text = startDate
cell.durationLabel?.text = workout.durationLabel
cell.workoutTypeLabel?.text = workout.workoutTypeLabel
return cell
} else {
return tableView.dequeueReusableCellWithIdentifier("syncAllCell")!
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var workout = self.workouts[indexPath.row]
workout.checked = !workout.checked
self.workouts[indexPath.row] = workout
self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade)
self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
let anyTrue = self.workouts
.map { return $0.checked }
.reduce(false) { (sum, next) in return sum || next }
if anyTrue {
self.navigationItem.rightBarButtonItem?.title = "Sync Selected"
} else {
self.navigationItem.rightBarButtonItem?.title = "Sync All"
}
}
func readWorkOuts(completion: (([AnyObject]!, NSError!) -> Void)!) {
let sortDescriptor = NSSortDescriptor(key:HKSampleSortIdentifierStartDate, ascending: false)
let sampleQuery = HKSampleQuery(sampleType: HKWorkoutType.workoutType(), predicate: nil, limit: 0, sortDescriptors: [sortDescriptor])
{ (sampleQuery, results, error ) -> Void in
if let queryError = error {
print( "There was an error while reading the samples: \(queryError.localizedDescription)")
}
completion(results, error)
}
hkStore.executeQuery(sampleQuery)
}
func managedObject(workout: HKWorkout) -> NSManagedObject? {
let uuid = workout.UUID.UUIDString
let servicesPredicate: String
if let _ = self.workoutSyncAPI as? RunKeeperAPI {
servicesPredicate = "uuid = %@ AND syncToRunKeeper != nil"
} else if let _ = self.workoutSyncAPI as? StravaAPI {
servicesPredicate = "uuid = %@ AND syncToStrava != nil"
} else {
return nil
}
let fetchRequest = NSFetchRequest(entityName: "SyncLog")
let predicate = NSPredicate(format: servicesPredicate, uuid)
fetchRequest.predicate = predicate
let fetchedEntities = try? self.managedContext.executeFetchRequest(fetchRequest)
if let syncLog = fetchedEntities?.first as? NSManagedObject {
return syncLog
}
return nil
}
func stringFromTimeInterval(interval:NSTimeInterval) -> String {
let ti = NSInteger(interval)
let seconds = ti % 60
let minutes = (ti / 60) % 60
let hours = (ti / 3600)
return String(format: "%0.2d:%0.2d:%0.2d",hours,minutes,seconds)
}
func syncItems() {
let workoutsToSync: Workout
let anyTrue = self.workouts
.map { return $0.checked }
.reduce(false) { (sum, next) in return sum || next }
if anyTrue {
workoutsToSync = self.workouts.filter({$0.checked})
} else {
workoutsToSync = self.workouts
}
let vcu = ViewControllerUtils()
vcu.showActivityIndicator(self.view)
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext!
if let runKeeper = self.workoutSyncAPI as? RunKeeperAPI {
// Loop over workoutsToSync
workoutsToSync.forEach { workout in
if let workoutDetail = workout.workoutDetails {
runKeeper.postActivity(workoutDetail, failure: { (error, msg) in
dispatch_async(dispatch_get_main_queue()) {
vcu.hideActivityIndicator(self.view)
let errorMessage: String
if let error = error {
errorMessage = "\(error.localizedDescription) - \(msg)"
} else {
errorMessage = "An error occurred while saving workout. Please verify that WorkoutMerge is still authorized through RunKeeper - \(msg)"
}
let alert = UIAlertController(title: "Error", message: errorMessage, preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
},
success: { (savedKey) in
if let uuid = workout.workoutDetails?.UUID?.UUIDString {
if let syncLog = self.syncLog(uuid) {
syncLog.setValue(NSDate(), forKey: "syncToRunKeeper")
syncLog.setValue(savedKey, forKey: "savedKeyRunKeeper")
if let workoutType = workout.workoutDetails?.type {
syncLog.setValue(workoutType, forKey: "workoutType")
}
} else {
let entity = NSEntityDescription.entityForName("SyncLog", inManagedObjectContext: managedContext)
let syncLog = NSManagedObject(entity: entity!, insertIntoManagedObjectContext:managedContext)
syncLog.setValue(uuid, forKey: "uuid")
syncLog.setValue(NSDate(), forKey: "syncToRunKeeper")
syncLog.setValue(savedKey, forKey: "savedKeyRunKeeper")
if let workoutType = workout.workoutDetails?.type {
syncLog.setValue(workoutType, forKey: "workoutType")
}
}
var error: NSError?
do {
try managedContext.save()
} catch let error1 as NSError {
error = error1
print("Could not save \(error)")
} catch {
fatalError()
}
}
dispatch_async(dispatch_get_main_queue()) {
// TODO reload data in table - remove workouts synced
vcu.hideActivityIndicator(self.view)
}
})
}
}
} else if let strava = self.workoutSyncAPI as? StravaAPI {
// Loop over workoutsToSync
workoutsToSync.forEach { workout in
// strava
if let workoutDetail = workout.workoutDetails {
strava.postActivity(workoutDetail, failure: { (error, msg) in
dispatch_async(dispatch_get_main_queue()) {
vcu.hideActivityIndicator(self.view)
let errorMessage: String
if let error = error {
errorMessage = "\(error.localizedDescription) - \(msg)"
} else {
errorMessage = "An error occurred while saving workout. Please verify that WorkoutMerge is still authorized through Strava - \(msg)"
}
let alert = UIAlertController(title: "Error", message: errorMessage, preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
},
success: { (savedKey) in
if let uuid = workout.workoutDetails?.UUID?.UUIDString {
if let syncLog = self.syncLog(uuid) {
syncLog.setValue(NSDate(), forKey: "syncToRunKeeper")
syncLog.setValue(savedKey, forKey: "savedKeyRunKeeper")
if let workoutType = workout.workoutDetails?.type {
syncLog.setValue(workoutType, forKey: "workoutType")
}
} else {
let entity = NSEntityDescription.entityForName("SyncLog", inManagedObjectContext: managedContext)
let syncLog = NSManagedObject(entity: entity!, insertIntoManagedObjectContext:managedContext)
syncLog.setValue(uuid, forKey: "uuid")
syncLog.setValue(NSDate(), forKey: "syncToRunKeeper")
syncLog.setValue(savedKey, forKey: "savedKeyRunKeeper")
if let workoutType = workout.workoutDetails?.type {
syncLog.setValue(workoutType, forKey: "workoutType")
}
}
var error: NSError?
do {
try managedContext.save()
} catch let error1 as NSError {
error = error1
print("Could not save \(error)")
} catch {
fatalError()
}
}
dispatch_async(dispatch_get_main_queue()) {
// TODO reload data in table - remove workouts synced
vcu.hideActivityIndicator(self.view)
}
})
}
}
}
}
func averageHeartRateForWorkout(workout: HKWorkout, success: (Double?) -> (), tryAgain: Bool) {
let quantityType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)
let workoutPredicate = HKQuery.predicateForSamplesWithStartDate(workout.startDate, endDate: workout.endDate, options: .None)
// let startDateSort = NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: true)
let query = HKStatisticsQuery(quantityType: quantityType!, quantitySamplePredicate: workoutPredicate, options: .DiscreteAverage) {
(query, results, error) -> Void in
if error != nil {
print("\(error)")
if tryAgain {
self.averageHeartRateForWorkout(workout, success: success, tryAgain: false)
} else {
print("failed to retrieve heart rate data")
success(nil)
}
} else {
if results!.averageQuantity() != nil {
let avgHeartRate = results!.averageQuantity()!.doubleValueForUnit(HKUnit(fromString: "count/min"));
success(avgHeartRate)
} else if tryAgain {
print("averageQuantity unexpectedly found nil")
self.averageHeartRateForWorkout(workout, success: success, tryAgain: false)
} else {
print("failed to retrieve heart rate data")
success(nil)
}
}
}
hkStore.executeQuery(query)
}
func syncLog(uuid: String) -> NSManagedObject? {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext!
let fetchRequest = NSFetchRequest(entityName: "SyncLog")
let predicate = NSPredicate(format: "uuid = %@", uuid)
fetchRequest.predicate = predicate
let fetchedEntities = try? managedContext.executeFetchRequest(fetchRequest)
if let syncLog = fetchedEntities?.first as? NSManagedObject {
return syncLog
}
return nil
}
}
| 213d54243f26eabc6f718134a67b35c9 | 47.681704 | 319 | 0.506075 | false | false | false | false |
Longhanks/qlift | refs/heads/master | Sources/Qlift/QVBoxLayout.swift | mit | 1 | import CQlift
open class QVBoxLayout: QBoxLayout {
public init(parent: QWidget? = nil) {
super.init(ptr: QVBoxLayout_new(parent?.ptr), parent: parent)
}
override init(ptr: UnsafeMutableRawPointer, parent: QWidget? = nil) {
super.init(ptr: ptr, parent: parent)
}
deinit {
if self.ptr != nil {
if QObject_parent(self.ptr) == nil {
QVBoxLayout_delete(self.ptr)
}
self.ptr = nil
}
}
}
| 8021bb9bf39f7a0bce5a7de41431edfe | 20.521739 | 73 | 0.551515 | false | false | false | false |
noprom/Cocktail-Pro | refs/heads/master | smartmixer/smartmixer/Ingridients/Ingredients.swift | apache-2.0 | 1 | //
// Materials.swift
// smartmixer
//
// Created by 姚俊光 on 14-8-20.
// Copyright (c) 2014年 Smart Group. All rights reserved.
//
import UIKit
import CoreData
class Ingredients: UIViewController , NSFetchedResultsControllerDelegate,UISearchBarDelegate{
@IBOutlet var itableView:UITableView!
@IBOutlet var searchbar:UISearchBar!
//用户修正TableView的上端距离
@IBOutlet var hCondition: NSLayoutConstraint!
var ingredientCollection:IngredientCollection! = nil
var numberOfitems:Int = 0
class func IngredientsRoot()->UIViewController{
let ingridientController = UIStoryboard(name:"Ingredients"+deviceDefine,bundle:nil).instantiateInitialViewController() as! Ingredients
return ingridientController
}
override func viewDidLoad() {
super.viewDidLoad()
if(deviceDefine != ""){//ipad
ingredientCollection = IngredientCollection.IngredientCollectionInit()
ingredientCollection.NavigationController = self.navigationController
ingredientCollection.view.frame = CGRect(x: 1024-770, y: 60, width: 760, height: self.view.frame.height)
self.view.addSubview(ingredientCollection.view)
let index = NSIndexPath(forRow: 0, inSection: 0)
itableView!.selectRowAtIndexPath(index, animated: false, scrollPosition: UITableViewScrollPosition.Top)
}
itableView.separatorStyle = UITableViewCellSeparatorStyle.None
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
rootController.showOrhideToolbar(true)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if(deviceDefine==""){
itableView.contentSize = CGSize(width: 320, height:200+numberOfitems*60)
}else{
itableView.contentSize = CGSize(width: 250, height:250+numberOfitems*80)
}
if(osVersion>=8 && self.hCondition != nil){
self.hCondition.constant = -60
}
self.view.layoutIfNeeded()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//@MARK:搜索框的处理
func searchBarShouldBeginEditing(searchBar: UISearchBar) -> Bool {
searchBar.setShowsCancelButton(true, animated: true)
return true
}
//取消按钮
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
searchBar.resignFirstResponder()
searchBar.text=""
searchBar.setShowsCancelButton(false, animated: true)
}
//搜索按钮按下
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
searchBar.resignFirstResponder()
if(deviceDefine==""){
ingredientCollection = IngredientCollection.IngredientCollectionInit()
ingredientCollection.NavigationController = self.navigationController
ingredientCollection.CatagoryId = -1
ingredientCollection.catagoryName = searchBar.text!
self.navigationController?.pushViewController(ingredientCollection!, animated: true)
rootController.showOrhideToolbar(false)
}else{
ingredientCollection.CatagoryId = -1
ingredientCollection.catagoryName = searchBar.text!
ingredientCollection.reloadData()
}
}
//告知窗口现在有多少个item需要添加
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int
{
let sectionInfo = self.fetchedResultsController.sections!
let item = sectionInfo[section]
numberOfitems = item.numberOfObjects + 1
return numberOfitems
}
//处理单个View的添加
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!
{
let tableCell:IngredientCategory = tableView.dequeueReusableCellWithIdentifier("categoryCell") as! IngredientCategory
if(indexPath.row==0){
tableCell.title.text = "器具"
tableCell.title_eng.text = "Appliances"
tableCell.tag = 0
tableCell.thumb.image = UIImage(named: "C_Appliances.jpg")
}else{
let index = NSIndexPath(forRow: indexPath.row - 1, inSection: indexPath.section)
let item = self.fetchedResultsController.objectAtIndexPath(index) as! Category
tableCell.title.text = item.name
tableCell.title_eng.text = item.nameEng
tableCell.tag = item.id.integerValue
tableCell.thumb.image = UIImage(named: item.thumb)
}
tableCell.selectedBackgroundView = UIView(frame: tableCell.frame)
tableCell.selectedBackgroundView!.backgroundColor = UIColor.whiteColor()
tableCell.title.highlightedTextColor = UIColor.redColor()
tableCell.title_eng.highlightedTextColor = UIColor.redColor()
return tableCell
}
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!)
{
let cell = tableView.cellForRowAtIndexPath(indexPath) as! IngredientCategory
if(deviceDefine==""){
ingredientCollection = IngredientCollection.IngredientCollectionInit()
ingredientCollection.NavigationController = self.navigationController
ingredientCollection.CatagoryId = cell.tag
ingredientCollection.catagoryName = cell.title.text!
self.navigationController?.pushViewController(ingredientCollection, animated: true)
rootController.showOrhideToolbar(false)
}else{
ingredientCollection.CatagoryId = cell.tag
ingredientCollection.reloadData()
}
}
var fetchedResultsController: NSFetchedResultsController {
if _fetchedResultsController != nil {
return _fetchedResultsController!
}
let fetchRequest = NSFetchRequest()
fetchRequest.entity = NSEntityDescription.entityForName("Category", inManagedObjectContext: managedObjectContext)
fetchRequest.fetchBatchSize = 30
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "order", ascending: true),NSSortDescriptor(key: "id", ascending: true)]
fetchRequest.predicate = NSPredicate(format: "type == 1")
let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: managedObjectContext, sectionNameKeyPath: nil, cacheName: nil)
aFetchedResultsController.delegate = self
_fetchedResultsController = aFetchedResultsController
do {
try self._fetchedResultsController!.performFetch()
}catch{
abort()
}
return _fetchedResultsController!
}
var _fetchedResultsController: NSFetchedResultsController? = nil
}
| bac55dfd8209c461c1806de3550e2b83 | 39.814371 | 179 | 0.681338 | false | false | false | false |
javibm/fastlane | refs/heads/master | fastlane/swift/SocketClient.swift | mit | 1 | //
// SocketClient.swift
// FastlaneSwiftRunner
//
// Created by Joshua Liebowitz on 7/30/17.
// Copyright © 2017 Joshua Liebowitz. All rights reserved.
//
import Foundation
public enum SocketClientResponse: Error {
case alreadyClosedSockets
case malformedRequest
case malformedResponse
case serverError
case commandTimeout(seconds: Int)
case connectionFailure
case success(returnedObject: String?, closureArgumentValue: String?)
}
class SocketClient: NSObject {
enum SocketStatus {
case ready
case closed
}
static let connectTimeoutSeconds = 2
static let defaultCommandTimeoutSeconds = 3_600 // Hopefully 1 hr is enough ¯\_(ツ)_/¯
static let doneToken = "done"
fileprivate var inputStream: InputStream!
fileprivate var outputStream: OutputStream!
fileprivate var cleaningUpAfterDone = false
fileprivate let dispatchGroup: DispatchGroup = DispatchGroup()
fileprivate let commandTimeoutSeconds: Int
private let streamQueue: DispatchQueue
private let host: String
private let port: UInt32
let maxReadLength = 65_536 // max for ipc on 10.12 is kern.ipc.maxsockbuf: 8388608 ($sysctl kern.ipc.maxsockbuf)
weak private(set) var socketDelegate: SocketClientDelegateProtocol?
public private(set) var socketStatus: SocketStatus
// localhost only, this prevents other computers from connecting
init(host: String = "localhost", port: UInt32 = 2000, commandTimeoutSeconds: Int = defaultCommandTimeoutSeconds, socketDelegate: SocketClientDelegateProtocol) {
self.host = host
self.port = port
self.commandTimeoutSeconds = commandTimeoutSeconds
self.streamQueue = DispatchQueue(label: "streamQueue")
self.socketStatus = .closed
self.socketDelegate = socketDelegate
super.init()
}
func connectAndOpenStreams() {
var readStream: Unmanaged<CFReadStream>?
var writeStream: Unmanaged<CFWriteStream>?
self.streamQueue.async {
CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, self.host as CFString, self.port, &readStream, &writeStream)
self.inputStream = readStream!.takeRetainedValue()
self.outputStream = writeStream!.takeRetainedValue()
self.inputStream.delegate = self
self.outputStream.delegate = self
self.inputStream.schedule(in: .main, forMode: .defaultRunLoopMode)
self.outputStream.schedule(in: .main, forMode: .defaultRunLoopMode)
}
self.dispatchGroup.enter()
self.streamQueue.async {
self.inputStream.open()
}
self.dispatchGroup.enter()
self.streamQueue.async {
self.outputStream.open()
}
let secondsToWait = DispatchTimeInterval.seconds(SocketClient.connectTimeoutSeconds)
let connectTimeout = DispatchTime.now() + secondsToWait
let timeoutResult = self.dispatchGroup.wait(timeout: connectTimeout)
let failureMessage = "Couldn't connect to ruby process within: \(SocketClient.connectTimeoutSeconds) seconds"
let success = testDispatchTimeoutResult(timeoutResult, failureMessage: failureMessage, timeToWait: secondsToWait)
guard success else {
self.socketDelegate?.commandExecuted(serverResponse: .connectionFailure)
return
}
self.socketStatus = .ready
self.socketDelegate?.connectionsOpened()
}
public func send(rubyCommand: RubyCommandable) {
verbose(message: "sending: \(rubyCommand.json)")
send(string: rubyCommand.json)
}
public func sendComplete() {
sendAbort()
}
private func testDispatchTimeoutResult(_ timeoutResult: DispatchTimeoutResult, failureMessage: String, timeToWait: DispatchTimeInterval) -> Bool {
switch timeoutResult {
case .success:
return true
case .timedOut:
log(message: "Timeout: \(failureMessage)")
if case .seconds(let seconds) = timeToWait {
socketDelegate?.commandExecuted(serverResponse: .commandTimeout(seconds: seconds))
}
return false
}
}
private func stopInputSession() {
inputStream.close()
}
private func stopOutputSession() {
outputStream.close()
}
private func send(string: String) {
guard !self.cleaningUpAfterDone else {
// This will happen after we abort if there are commands waiting to be executed
// Need to check state of SocketClient in command runner to make sure we can accept `send`
socketDelegate?.commandExecuted(serverResponse: .alreadyClosedSockets)
return
}
if string == SocketClient.doneToken {
self.cleaningUpAfterDone = true
}
self.dispatchGroup.enter()
streamQueue.async {
let data = string.data(using: .utf8)!
_ = data.withUnsafeBytes { self.outputStream.write($0, maxLength: data.count) }
}
let timeoutSeconds = self.cleaningUpAfterDone ? 1 : self.commandTimeoutSeconds
let timeToWait = DispatchTimeInterval.seconds(timeoutSeconds)
let commandTimeout = DispatchTime.now() + timeToWait
let timeoutResult = self.dispatchGroup.wait(timeout: commandTimeout)
_ = testDispatchTimeoutResult(timeoutResult, failureMessage: "Ruby process didn't return after: \(SocketClient.connectTimeoutSeconds) seconds", timeToWait: timeToWait)
}
func sendAbort() {
self.socketStatus = .closed
stopInputSession()
// and error occured, let's try to send the "done" message
send(string: SocketClient.doneToken)
stopOutputSession()
self.socketDelegate?.connectionsClosed()
}
}
extension SocketClient: StreamDelegate {
func stream(_ aStream: Stream, handle eventCode: Stream.Event) {
guard !self.cleaningUpAfterDone else {
// Still getting response from server eventhough we are done.
// No big deal, we're closing the streams anyway.
// That being said, we need to balance out the dispatchGroups
self.dispatchGroup.leave()
return
}
if aStream === self.inputStream {
switch eventCode {
case Stream.Event.openCompleted:
self.dispatchGroup.leave()
case Stream.Event.errorOccurred:
verbose(message: "input stream error occurred")
sendAbort()
case Stream.Event.hasBytesAvailable:
read()
case Stream.Event.endEncountered:
// nothing special here
break
case Stream.Event.hasSpaceAvailable:
// we don't care about this
break
default:
verbose(message: "input stream caused unrecognized event: \(eventCode)")
}
} else if aStream === self.outputStream {
switch eventCode {
case Stream.Event.openCompleted:
self.dispatchGroup.leave()
case Stream.Event.errorOccurred:
// probably safe to close all the things because Ruby already disconnected
verbose(message: "output stream recevied error")
break
case Stream.Event.endEncountered:
// nothing special here
break
case Stream.Event.hasSpaceAvailable:
// we don't care about this
break
default:
verbose(message: "output stream caused unrecognized event: \(eventCode)")
}
}
}
func read() {
var buffer = [UInt8](repeating: 0, count: maxReadLength)
var output = ""
while self.inputStream!.hasBytesAvailable {
let bytesRead: Int = inputStream!.read(&buffer, maxLength: buffer.count)
if bytesRead >= 0 {
output += NSString(bytes: UnsafePointer(buffer), length: bytesRead, encoding: String.Encoding.utf8.rawValue)! as String
} else {
verbose(message: "Stream read() error")
}
}
processResponse(string: output)
}
func handleFailure(message: [String]) {
log(message: "Encountered a problem: \(message.joined(separator:"\n"))")
sendAbort()
}
func processResponse(string: String) {
guard string.count > 0 else {
self.socketDelegate?.commandExecuted(serverResponse: .malformedResponse)
self.handleFailure(message: ["empty response from ruby process"])
return
}
let responseString = string.trimmingCharacters(in: .whitespacesAndNewlines)
let socketResponse = SocketResponse(payload: responseString)
verbose(message: "response is: \(responseString)")
switch socketResponse.responseType {
case .failure(let failureInformation):
self.socketDelegate?.commandExecuted(serverResponse: .serverError)
self.handleFailure(message: failureInformation)
case .parseFailure(let failureInformation):
self.socketDelegate?.commandExecuted(serverResponse: .malformedResponse)
self.handleFailure(message: failureInformation)
case .readyForNext(let returnedObject, let closureArgumentValue):
self.socketDelegate?.commandExecuted(serverResponse: .success(returnedObject: returnedObject, closureArgumentValue: closureArgumentValue))
// cool, ready for next command
break
}
self.dispatchGroup.leave() // should now pull the next piece of work
}
}
// Please don't remove the lines below
// They are used to detect outdated files
// FastlaneRunnerAPIVersion [0.9.1]
| 8b62778e5ba7aa375614e7f99345e950 | 35.339223 | 175 | 0.622909 | false | false | false | false |
KrishMunot/swift | refs/heads/master | test/NameBinding/Inputs/accessibility_other.swift | apache-2.0 | 7 | import has_accessibility
public let a = 0
internal let b = 0
private let c = 0
extension Foo {
public static func a() {}
internal static func b() {}
private static func c() {} // expected-note {{'c' declared here}}
}
struct PrivateInit {
private init() {} // expected-note {{'init' declared here}}
}
extension Foo {
private func method() {}
private typealias TheType = Float
}
extension OriginallyEmpty {
func method() {}
typealias TheType = Float
}
private func privateInBothFiles() {}
func privateInPrimaryFile() {} // expected-note {{previously declared here}}
private func privateInOtherFile() {} // expected-error {{invalid redeclaration}}
| c68b0d5cf8d8287d0f387e6a7e4a69ca | 22.068966 | 80 | 0.696562 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.