repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
powerytg/Accented | Accented/UI/Search/Layouts/UserSearchResultLayout.swift | 1 | 3397 | //
// UserSearchResultLayout.swift
// Accented
//
// User search result layout
//
// Created by Tiangong You on 5/22/17.
// Copyright © 2017 Tiangong You. All rights reserved.
//
import UIKit
class UserSearchResultLayout: InfiniteLoadingLayout<UserModel> {
private let vGap : CGFloat = 8
private let itemHeight : CGFloat = 60
private let footerHeight : CGFloat = 50
private var width : CGFloat = 0
private let leftMargin : CGFloat = 15
private let rightMargin : CGFloat = 15
var paddingTop : CGFloat = 0
override init() {
super.init()
}
required init?(coder aDecoder: NSCoder) {
fatalError("Not implemented")
}
override func prepare() {
scrollDirection = .vertical
if collectionView != nil {
width = collectionView!.bounds.width
}
}
override var collectionViewContentSize : CGSize {
return CGSize(width: width, height: contentHeight)
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var layoutAttributes = [UICollectionViewLayoutAttributes]()
for attributes in layoutCache.values {
if attributes.frame.intersects(rect) {
layoutAttributes.append(attributes.copy() as! UICollectionViewLayoutAttributes)
}
}
return layoutAttributes
}
override func generateLayoutAttributesIfNeeded() {
guard collection != nil else { return }
if collectionView != nil {
width = collectionView!.bounds.width
}
// If there's a previous loading indicator, reset its section height to 0
updateCachedLayoutHeight(cacheKey: loadingIndicatorCacheKey, toHeight: 0)
var nextY : CGFloat = paddingTop
for (index, user) in collection!.items.enumerated() {
// Ignore if the user already has a layout
let cacheKey = cacheKeyForUser(user)
var attrs = layoutCache[cacheKey]
if attrs == nil {
let cellSize = CGSize(width: width - leftMargin - rightMargin, height: itemHeight)
let indexPath = IndexPath(item: index, section: 0)
attrs = UICollectionViewLayoutAttributes(forCellWith: indexPath)
attrs!.frame = CGRect(x: leftMargin, y: nextY, width: cellSize.width, height: cellSize.height)
layoutCache[cacheKey] = attrs!
}
nextY += attrs!.frame.size.height + vGap
}
// Always show the footer regardless of the loading state
// If not loading, then the footer is simply not visible
let footerHeight = defaultLoadingIndicatorHeight
let footerCacheKey = loadingIndicatorCacheKey
let indexPath = IndexPath(item: 0, section: 0)
let footerAttributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, with: indexPath)
footerAttributes.frame = CGRect(x: 0, y: nextY, width: width, height: footerHeight)
layoutCache[footerCacheKey] = footerAttributes
nextY += footerHeight + vGap
contentHeight = nextY
}
private func cacheKeyForUser(_ user : UserModel) -> String {
return "user_\(user.userId)"
}
}
| mit | c2f07f4cfb89c42f5fdfb8b31e9f4579 | 34.010309 | 146 | 0.632803 | 5.399046 | false | false | false | false |
noahemmet/FingerPaint | Example/HistoryView.swift | 1 | 2141 | //
// HistoryView.swift
// FingerPaint
//
// Created by Noah Emmet on 5/1/16.
// Copyright © 2016 Sticks. All rights reserved.
//
import UIKit
import FingerPaint
protocol HistoryViewDelegate: class {
func resetToStroke(stroke: Stroke, atIndex index: Int)
}
class HistoryView: UICollectionView {
var history: History!
weak var historyViewDelegate: HistoryViewDelegate?
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.dataSource = self
self.delegate = self
}
}
extension HistoryView: UICollectionViewDataSource, UICollectionViewDelegate {
override func numberOfSections() -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return history.strokes.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("HistoryCell", forIndexPath: indexPath)
let stroke = history.strokes.reverse()[indexPath.row]
cell.contentView.layer.sublayers?.removeAll()
let layer = stroke.createLayer(scale: 0.1)
cell.contentView.layer.addSublayer(layer)
return cell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
if indexPath.item == history.strokes.count - 1 {
return
}
let stroke = history.strokes[indexPath.row]
self.historyViewDelegate?.resetToStroke(stroke, atIndex: indexPath.row + 1)
self.history.resetToStroke(stroke, atIndex: indexPath.row + 1)
self.reloadSections(NSIndexSet(index: 0))
// let indexPaths = (indexPath.row ..< history.strokes.count).map { NSIndexPath(forItem: $0, inSection: 0) }
// self.performBatchUpdates(
// {
//// self.deleteItemsAtIndexPaths(indexPaths)
// }, completion: nil)
}
}
extension HistoryView: HistoryDelegate {
func historyUpdated(history: History) {
self.reloadData()
let lastIndexPath = NSIndexPath(forItem: history.strokes.count - 1, inSection: 0)
self.scrollToItemAtIndexPath(lastIndexPath, atScrollPosition: .Right, animated: true)
}
} | apache-2.0 | 0b605e682a967de0f3fb80fc924bd84d | 30.485294 | 127 | 0.761215 | 4.037736 | false | false | false | false |
qiuncheng/CuteAttribute | CuteAttribute/CuteAttribute+Match.swift | 1 | 4242 | //
// CuteAttribute+Match.swift
// Cute
//
// Created by vsccw on 2017/8/11.
// Copyright © 2017年 https://vsccw.com. All rights reserved.
//
import Foundation
public extension CuteAttribute where Base: NSMutableAttributedString {
/// As set `NSRange`'s location, it must less than string's length.
///
/// - Parameter location: the location you choose to set.
/// - Returns: self
func from(_ location: Int) -> CuteAttribute<Base> {
assert(location <= base.string.length, "`from` must less than string's length.")
from = location
return self
}
/// As set `NSRange`'s length,
/// it must less than string's length,
/// and it must more than from. It must be work with `from(_:)`
///
/// - Parameter location: the locatoin you choose to set.
/// - Returns: self
func to(_ location: Int) -> CuteAttribute<Base> {
assert(location <= base.string.length, "`to` must less than string's length.")
let range = NSRange(location: from, length: location - from)
return self.range(range)
}
/// Match all the `NSMutableAttributedString`.
///
/// - Returns: self
func matchAll() -> CuteAttribute<Base> {
self.ranges = [base.string.nsrange]
return self
}
/// Match `subString` with regex pattern.
///
/// - Parameter re: the regex pattern you set.
/// - Returns: self
func match(using regex: String) -> CuteAttribute<Base> {
do {
let regex = try RegexHelper(pattern: regex)
ranges = regex.matchs(input: base.string)
} catch let err {
fatalError("could not find string with re: \(err)")
}
return self
}
/// Match all the subString.
///
/// - Parameter str: subString
/// - Returns: self
func match(string: String) -> CuteAttribute<Base> {
var range = base.string.range(substring: string)
assert(range.location != NSNotFound, "Substring must be in string.")
ranges.removeAll()
ranges.append(range)
repeat {
let location = range.location + range.length
let length = base.string.length - location
let allRange = NSRange(location: location, length: length)
range = base.string.range(substring: string, options: [], range: allRange)
if range.length == 0 || range.location == NSNotFound {
break
}
ranges.append(range)
} while true
return self
}
/// Match the special range
///
/// - Parameter ran: the NSRange you set.
/// - Returns: self
func match(range ran: NSRange) -> CuteAttribute<Base> {
assert(base.string.nsrange >> ran, "range should be in range of string.")
return self.range(ran)
}
/// Match all the url.
///
/// - Returns: self
func matchAllURL() -> CuteAttribute<Base> {
return matchAllAttribute(checkingType: .link)
}
/// Match all the phone number.
///
/// - Returns: self
func matchAllPhoneNumber() -> CuteAttribute<Base> {
return matchAllAttribute(checkingType: .phoneNumber)
}
/// Match all the address.
///
/// - Returns: self
func matchAllAddress() -> CuteAttribute<Base> {
return matchAllAttribute(checkingType: .address)
}
/// Match all the date.
///
/// - Returns: self
func matchAllDate() -> CuteAttribute<Base> {
return matchAllAttribute(checkingType: .date)
}
internal func matchAllAttribute(checkingType: NSTextCheckingResult.CheckingType) -> CuteAttribute<Base> {
do {
let dataHelper = try DataDetectorHelper(types: checkingType.rawValue)
ranges = dataHelper.matches(string: base.string)
} catch let err {
fatalError("Could not match string : \(err)")
}
return self
}
internal var from: Int {
set {
objc_setAssociatedObject(base, CuteAttributeKey.fromKey, Box(newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
get {
return (objc_getAssociatedObject(base, CuteAttributeKey.fromKey) as? Box<Int>)?.value ?? 0
}
}
}
| mit | 9064f1a1825fe360345f195e49ec8f35 | 30.634328 | 119 | 0.595659 | 4.243243 | false | false | false | false |
crspybits/SMSyncServer | iOS/iOSTests/Pods/SMSyncServer/SMSyncServer/Classes/Internal/CoreData/SMUploadFileOperation.swift | 3 | 2111 | //
// SMUploadFileOperation.swift
// SMSyncServer
//
// Created by Christopher Prince on 4/9/16.
// Copyright © 2016 Spastic Muffin, LLC. All rights reserved.
//
import Foundation
import CoreData
import SMCoreLib
class SMUploadFileOperation: SMUploadOperation {
enum OperationStage : String {
// There are two main server stages in uploads and upload-deletions
// 1) Upload, when the operation needs to be queued in our server
case ServerUpload
// 2) When the file needs to be transferred to cloud storage or deleted from cloud storage
case CloudStorage
}
// Don't access .internalOperationStage directly.
var operationStage: OperationStage {
set {
self.internalOperationStage = newValue.rawValue
CoreData.sessionNamed(SMCoreData.name).saveContext()
}
get {
return OperationStage(rawValue: self.internalOperationStage!)!
}
}
func convertToServerFile() -> SMServerFile {
let localFile = self.localFile!
Log.msg("SMUploadFileOperation: \(self)")
let localVersion:Int = localFile.localVersion!.integerValue
Log.msg("Local file version: \(localVersion)")
let serverFile = SMServerFile(uuid: NSUUID(UUIDString: localFile.uuid!)!, remoteFileName: localFile.remoteFileName!, mimeType: localFile.mimeType!, appMetaData: localFile.appMetaData, version: localVersion)
var deleted = false
if let _ = self as? SMUploadDeletion {
deleted = true
}
serverFile.deleted = deleted
serverFile.localFile = localFile
return serverFile
}
class func convertToServerFiles(uploadFiles:[SMUploadFileOperation]) -> [SMServerFile]? {
var result = [SMServerFile]()
for uploadFile in uploadFiles {
result.append(uploadFile.convertToServerFile())
}
if result.count > 0 {
return result
}
else {
return nil
}
}
}
| gpl-3.0 | 3bbe1f1acada7751032122034c16a22f | 29.57971 | 214 | 0.625118 | 5.0358 | false | false | false | false |
jedlewison/ObservableProperty | ObservablePropertyTests/ObservablePropertyTests.swift | 1 | 6769 | //
// ObservablePropertyTests.swift
// ObservablePropertyTests
//
// Created by Jed Lewison on 2/21/16.
// Copyright © 2016 Jed Lewison. All rights reserved.
//
import Quick
import Nimble
enum TestError: ErrorType {
case SimpleError
}
@testable import ObservableProperty
let nilStringOptional = Optional<String>(nilLiteral: ())
class TestClass {
var text = ObservableProperty<String>(value: "lulz")
var optionalString = ObservableProperty(value: nilStringOptional, error: nil)
}
class ObservablePropertySpec: QuickSpec {
override func spec() {
var subject: TestClass!
var observedValue: String?
var observedError: ErrorType?
beforeEach {
subject = TestClass()
subject.text.setValue("First Value")
}
context("observing with initial value included") {
beforeEach {
subject.text.addObserver(self) {
switch $0.event {
case .Error(let error, let value):
observedError = error
observedValue = value
case .Next(let value):
observedError = nil
observedValue = value
}
}
}
describe("immediately after observation") {
it("should not have an error") {
expect(observedError).to(beNil())
}
it("Should have the initial value") {
expect(observedValue).to(equal("First Value"))
}
}
context("after a change") {
beforeEach {
subject.text.setValue("Second Value")
}
it("still should not have an error") {
expect(observedError).to(beNil())
}
it("Should eventualy get the second value") {
expect(observedValue).to(equal("Second Value"))
}
}
context("when reporting an error") {
beforeEach {
subject.text.setError(TestError.SimpleError)
}
it("should have the error") {
expect(observedError).toNot(beNil())
}
it("should still have the first value") {
expect(observedValue).to(equal("First Value"))
}
context("The next time a value is set") {
beforeEach {
subject.text.setValue("Error-clearing value")
}
it("should automatically clear the error") {
expect(observedError).to(beNil())
}
it("the new value should equal the error-clearing value") {
expect(observedValue).to(equal("Error-clearing value"))
}
}
context("The next time a value is set with another error") {
beforeEach {
subject.text.setValue("Value with error", error: TestError.SimpleError)
}
it("should still have an error") {
expect(observedError).toNot(beNil())
}
it("the new value should be the value with an error") {
expect(observedValue).to(equal("Value with error"))
}
}
}
}
context("observing while ignoring initial value") {
beforeEach {
subject.text.addObserver(self, includeInitialValue: false) {
switch $0.event {
case .Error(let error, let value):
observedError = error
observedValue = value
case .Next(let value):
observedError = nil
observedValue = value
}
}
}
describe("immediately after observation") {
it("should not have an error") {
expect(observedError).to(beNil())
}
it("Should have the initial value") {
expect(observedValue).to(beNil())
}
}
context("after a change") {
beforeEach {
subject.text.setValue("Second Value")
}
it("still should not have an error") {
expect(observedError).to(beNil())
}
it("Should eventualy get the second value") {
expect(observedValue).to(equal("Second Value"))
}
}
context("when reporting an error") {
beforeEach {
subject.text.setError(TestError.SimpleError)
}
it("should have the error") {
expect(observedError).toNot(beNil())
}
it("should still have the first value") {
expect(observedValue).to(equal("First Value"))
}
context("The next time a value is set") {
beforeEach {
subject.text.setValue("Error-clearing value")
}
it("should automatically clear the error") {
expect(observedError).to(beNil())
}
it("the new value should equal the error-clearing value") {
expect(observedValue).to(equal("Error-clearing value"))
}
}
context("The next time a value is set with another error") {
beforeEach {
subject.text.setValue("Value with error", error: TestError.SimpleError)
}
it("should still have an error") {
expect(observedError).toNot(beNil())
}
it("the new value should be the value with an error") {
expect(observedValue).to(equal("Value with error"))
}
}
}
}
afterEach {
subject = nil
observedError = nil
observedValue = nil
}
}
}
| mit | 7fac5fc4b0c2a55c58574f589f43cc63 | 27.317992 | 95 | 0.441933 | 6.108303 | false | false | false | false |
crazypoo/PTools | Pods/Appz/Appz/Appz/Apps/Ibooks.swift | 1 | 1012 | //
// Ibooks.swift
// Pods
//
// Created by Mariam AlJamea on 1/2/16.
// Copyright © 2016 kitz. All rights reserved.
//
public extension Applications {
public struct Ibooks: ExternalApplication {
public typealias ActionType = Applications.Ibooks.Action
public let scheme = "itms-Books:"
public let fallbackURL = "https://itunes.apple.com/us/app/ibooks/id364709193?mt=8"
public let appStoreId = "364709193"
public init() {}
}
}
// MARK: - Actions
public extension Applications.Ibooks {
public enum Action {
case open
}
}
extension Applications.Ibooks.Action: ExternalApplicationAction {
public var paths: ActionPaths {
switch self {
case .open:
return ActionPaths(
app: Path(
pathComponents: ["app"],
queryParameters: [:]
),
web: Path()
)
}
}
}
| mit | ab1d794ab347c260fe5e8bc38993a028 | 20.510638 | 90 | 0.542038 | 4.637615 | false | false | false | false |
sergii-frost/weeknum-ios | weeknum/weeknum/Utils/FormatterUtils.swift | 1 | 1290 | //
// FormatterUtils.swift
// weeknum
//
// Created by Sergii Nezdolii on 03/07/16.
// Copyright © 2016 FrostDigital. All rights reserved.
//
import Foundation
class FormatterUtils {
static let kDateFormat = "EEE, dd MMM yyyy"
static let kShortDateFormat = "dd MMM"
fileprivate static func dateFormatter(_ dateFormat: String) -> DateFormatter {
let df = DateFormatter()
df.locale = Locale.current
df.dateFormat = dateFormat
return df
}
static func formattedDate(_ date: Date?, dateFormat: String = kDateFormat) -> String? {
guard let date = date else {return nil}
return dateFormatter(dateFormat).string(from: date)
}
static func dateFromString(_ string: String, dateFormat: String) -> Date? {
return dateFormatter(dateFormat).date(from: string)
}
static func getWeekInfo(_ date: Date?, shortDateFormat: String = kShortDateFormat) -> String? {
guard
let date = date,
let weekStart = formattedDate(date.thisWeekStart(), dateFormat: shortDateFormat),
let weekEnd = formattedDate(date.nextWeekStart()?.dayBefore(), dateFormat: shortDateFormat)
else {return nil}
return "\(weekStart) - \(weekEnd)"
}
}
| mit | 8f1ea6e98509ebfb3127bfd50a535eb7 | 31.225 | 103 | 0.641583 | 4.460208 | false | false | false | false |
lionchina/RxSwiftBook | RxImagePicker/RxImagePicker/UIImagePickerController+RxCreate.swift | 1 | 2801 | //
// UIImagePickerController+RxCreate.swift
// RxImagePicker
//
// Created by MaxChen on 03/08/2017.
// Copyright © 2017 com.linglustudio. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
func dismissViewController(_ viewController: UIViewController, animated: Bool) {
if viewController.isBeingDismissed || viewController.isBeingPresented {
DispatchQueue.main.async {
dismissViewController(viewController, animated: animated)
}
return
}
if viewController.presentingViewController != nil {
viewController.dismiss(animated: animated, completion: nil)
}
}
extension Reactive where Base: UIImagePickerController {
public var didFinishPickingMediaWithInfo: Observable<[String: AnyObject]> {
return delegate.methodInvoked(#selector(UIImagePickerControllerDelegate.imagePickerController(_:didFinishPickingMediaWithInfo:)))
.map({ (a) in
return try castOrThrow(Dictionary<String, AnyObject>.self, a[1])
})
}
public var didCancel: Observable<()> {
return delegate.methodInvoked(#selector(UIImagePickerControllerDelegate.imagePickerControllerDidCancel(_:)))
.map { _ in () }
}
static func createWithParent(_ parent: UIViewController?, animated: Bool = true, configureImagePicker: @escaping (UIImagePickerController) throws -> () = { x in }) -> Observable<UIImagePickerController> {
return Observable.create{ [weak parent] observer in
let imagePicker = UIImagePickerController()
let dismissDisposable = imagePicker.rx.didCancel
.subscribe(onNext: { [weak imagePicker] in
guard let imagePicker = imagePicker else {
return
}
dismissViewController(imagePicker, animated: animated)
})
do {
try configureImagePicker(imagePicker)
} catch let error {
observer.on(.error(error))
return Disposables.create()
}
guard let parent = parent else {
observer.on(.completed)
return Disposables.create()
}
parent.present(imagePicker, animated: animated, completion: nil)
observer.on(.next(imagePicker))
return Disposables.create(dismissDisposable, Disposables.create {
dismissViewController(imagePicker, animated: animated)
})
}
}
}
fileprivate func castOrThrow<T>(_ resultType: T.Type, _ object: Any) throws -> T {
guard let returnValue = object as? T else {
throw RxCocoaError.castingError(object: object, targetType: resultType)
}
return returnValue
}
| apache-2.0 | 686f3b8140d214d1e3b58cf787d1b887 | 37.356164 | 208 | 0.635357 | 5.668016 | false | false | false | false |
AbelSu131/ios-charts | Charts/Classes/Components/ChartLimitLine.swift | 3 | 1969 | //
// ChartLimitLine.swift
// Charts
//
// Created by Daniel Cohen Gindi on 23/2/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import UIKit
/// The limit line is an additional feature for all Line, Bar and ScatterCharts.
/// It allows the displaying of an additional line in the chart that marks a certain maximum / limit on the specified axis (x- or y-axis).
public class ChartLimitLine: ChartComponentBase
{
@objc
public enum ChartLimitLabelPosition: Int
{
case Left
case Right
}
/// limit / maximum (the y-value or xIndex)
public var limit = Double(0.0)
private var _lineWidth = CGFloat(2.0)
public var lineColor = UIColor(red: 237.0/255.0, green: 91.0/255.0, blue: 91.0/255.0, alpha: 1.0)
public var lineDashPhase = CGFloat(0.0)
public var lineDashLengths: [CGFloat]?
public var valueTextColor = UIColor.blackColor()
public var valueFont = UIFont.systemFontOfSize(13.0)
public var label = ""
public var labelPosition = ChartLimitLabelPosition.Right
public override init()
{
super.init();
}
public init(limit: Double)
{
super.init();
self.limit = limit;
}
public init(limit: Double, label: String)
{
super.init();
self.limit = limit;
self.label = label;
}
/// set the line width of the chart (min = 0.2, max = 12); default 2
public var lineWidth: CGFloat
{
get
{
return _lineWidth;
}
set
{
_lineWidth = newValue;
if (_lineWidth < 0.2)
{
_lineWidth = 0.2;
}
if (_lineWidth > 12.0)
{
_lineWidth = 12.0;
}
}
}
} | apache-2.0 | c4fc13d8a090df06aeb762dbbf352f7f | 23.625 | 138 | 0.574403 | 4.145263 | false | false | false | false |
cpageler93/ConsulSwift | Sources/ConsulSwift/Consul+AgentChecks.swift | 1 | 11617 | //
// Consul+AgentCheck.swift
// ConsulSwift
//
// Created by Christoph Pageler on 14.06.17.
//
import Foundation
import Quack
// API Documentation:
// https://www.consul.io/api/agent.html
public extension Consul {
// MARK: - Checks
/// This endpoint returns all checks that are registered with the local agent.
/// These checks were either provided through configuration files or added dynamically using the HTTP API.
///
/// It is important to note that the checks known by the agent may be different from those reported by
/// the catalog. This is usually due to changes being made while there is no leader elected.
/// The agent performs active anti-entropy, so in most situations everything will be in sync
/// within a few seconds.
///
/// [API Documentation][apidoc]
///
/// - Returns: Result with Checks
///
/// [apidoc]: https://www.consul.io/api/agent/check.html#list-checks
///
public func agentChecks() -> Quack.Result<[AgentCheckOutput]> {
return respondWithArray(path: "/v1/agent/checks",
parser: Quack.ArrayParserByIgnoringDictionaryKeys(),
model: AgentCheckOutput.self)
}
/// Async version of `Consul.agentChecks()`
///
/// - SeeAlso: `Consul.agentChecks()`
/// - Parameter completion: completion block
public func agentChecks(completion: @escaping (Quack.Result<[AgentCheckOutput]>) -> (Void)) {
respondWithArrayAsync(path: "/v1/agent/checks",
parser: Quack.ArrayParserByIgnoringDictionaryKeys(),
model: AgentCheckOutput.self,
completion: completion)
}
// MARK: Register / Deregister
/// This endpoint adds a new check to the local agent. Checks may be of script, HTTP, TCP, or TTL type.
/// The agent is responsible for managing the status of the check and keeping the Catalog in sync.
///
/// [API Documentation][apidoc]
///
/// - Parameter check: check to register
/// - Returns: Void Result
///
/// [apidoc]: https://www.consul.io/api/agent/check.html#register-check
public func agentRegisterCheck(_ check: AgentCheckInput) -> Quack.Void {
let params = agentRegisterCheckParams(check)
return respondVoid(method: .put,
path: "/v1/agent/check/register",
body: params,
requestModification: { (request) -> (Quack.Request) in
var request = request
request.encoding = .json
return request
})
}
/// Async version of `Consul.agentRegisterCheck(_ check: ConsulAgentCheckInput)`
///
/// - SeeAlso: `Consul.agentRegisterCheck(_ check: ConsulAgentCheckInput)`
/// - Parameter completion: completion block
public func agentRegisterCheck(_ check: AgentCheckInput,
completion: @escaping (Quack.Void) -> (Void)) {
let params = agentRegisterCheckParams(check)
respondVoidAsync(method: .put,
path: "/v1/agent/check/register",
body: params,
requestModification: { (request) -> (Quack.Request) in
var request = request
request.encoding = .json
return request
},
completion: completion)
}
/// helper method which returns parameters for register check
///
/// - Parameter check: check input
/// - Returns: parameters
private func agentRegisterCheckParams(_ check: AgentCheckInput) -> Quack.JSONBody {
var params: [String: Any] = [:]
params["Name"] = check.name
let optionalParams: [String: Any?] = [
"ID": check.id,
"Notes": check.notes,
"DeregisterCriticalServiceAfter": check.deregisterCriticalServiceAfter,
"Script": check.script,
"DockerContainerID": check.dockerContainerID,
"ServiceID": check.serviceID,
"HTTP": check.http,
"TCP": check.tcp,
"Interval": check.interval,
"TTL": check.ttl,
"TLSSkipVerify": check.tlsSkipVerify,
"Status": check.status?.rawValue
]
for (key, value) in optionalParams {
if let value = value {
params[key] = value
}
}
return Quack.JSONBody(params)
}
/// This endpoint remove a check from the local agent.
/// The agent will take care of deregistering the check from the catalog.
/// If the check with the provided ID does not exist, no action is taken.
///
/// [API Documentation][apidoc]
///
/// - Parameter id: check id
/// - Returns: Void Result
///
/// [apidoc]: https://www.consul.io/api/agent/check.html#deregister-check
public func agentDeregisterCheck(id: String) -> Quack.Void {
return respondVoid(method: .put, path: "/v1/agent/check/deregister/\(id)")
}
/// Async version of `Consul.agentDeregisterCheck(id: String)`
///
/// - SeeAlso: `Consul.agentDeregisterCheck(id: String)`
/// - Parameter completion: completion block
public func agentDeregisterCheck(id: String,
completion: @escaping (Quack.Void) -> (Void)) {
respondVoidAsync(method: .put,
path: "/v1/agent/check/deregister/\(id)",
completion: completion)
}
// MARK: Check Status
/// This endpoint is used with a TTL type check to set the status of the check to passing and
/// to reset the TTL clock.
///
/// [API Documentation][apidoc]
///
/// - Parameter id: check id
/// - Returns: Void Result
///
/// [apidoc]: https://www.consul.io/api/agent/check.html#ttl-check-pass
@discardableResult
public func agentCheckPass(id: String) -> Quack.Void {
return respondVoid(method: .put,
path: "/v1/agent/check/pass/\(id)")
}
/// Async version of `Consul.agentCheckPass(id: String)`
///
/// - SeeAlso: `Consul.agentCheckPass(id: String)`
/// - Parameter completion: completion block
public func agentCheckPass(id: String,
completion: @escaping (Quack.Void) -> (Void)) {
respondVoidAsync(method: .put,
path: "/v1/agent/check/pass/\(id)",
completion: completion)
}
/// This endpoint is used with a TTL type check to set the status of the check to warning and
/// to reset the TTL clock.
///
/// [API Documentation][apidoc]
///
/// - Parameters:
/// - id: check id
/// - note: note
/// - Returns: Void Result
///
/// [apidoc]: https://www.consul.io/api/agent/check.html#ttl-check-warn
@discardableResult
public func agentCheckWarn(id: String,
note: String = "") -> Quack.Void {
return respondVoid(method: .put,
path: "/v1/agent/check/warn/\(id)",
body: Quack.JSONBody(["note": note]))
}
/// Async version of `Consul.agentCheckWarn(id: String, note: String)`
///
/// - SeeAlso: `Consul.agentCheckWarn(id: String, note: String)`
/// - Parameter completion: completion block
public func agentCheckWarn(id: String,
note: String = "",
completion: @escaping (Quack.Void) -> (Void)) {
respondVoidAsync(method: .put,
path: "/v1/agent/check/warn/\(id)",
body: Quack.JSONBody(["note": note]),
completion: completion)
}
/// This endpoint is used with a TTL type check to set the status of the check to critical and
/// to reset the TTL clock.
///
/// [API Documentation][apidoc]
///
/// - Parameters:
/// - id: check id
/// - note: note
/// - Returns: Void Result
///
/// [apidoc]: https://www.consul.io/api/agent/check.html#ttl-check-fail
@discardableResult
public func agentCheckFail(id: String,
note: String = "") -> Quack.Void {
return respondVoid(method: .put,
path: "/v1/agent/check/fail/\(id)",
body: Quack.JSONBody(["note": note]))
}
/// Async version of `Consul.agentCheckFail(id: String, note: String)`
///
/// - SeeAlso: `Consul.agentCheckFail(id: String, note: String)`
/// - Parameter completion: completion block
public func agentCheckFail(id: String,
note: String = "",
completion: @escaping (Quack.Void) -> (Void)) {
respondVoidAsync(method: .put,
path: "/v1/agent/check/fail/\(id)",
body: Quack.JSONBody(["note": note]),
completion: completion)
}
/// This endpoint is used with a TTL type check to set the status of the check and to reset the TTL clock.
///
/// [API Documentation][apidoc]
///
/// - Parameters:
/// - id: check id
/// - status: new status
/// - output: output string
/// - Returns: Void Result
///
/// [apidoc]: https://www.consul.io/api/agent/check.html#ttl-check-update
@discardableResult
public func agentCheckUpdate(id: String,
status: AgentCheckStatus,
output: String = "") -> Quack.Void {
return respondVoid(method: .put,
path: "/v1/agent/check/update/\(id)",
body: Quack.JSONBody([
"Status": status.rawValue,
"Output": output
]),
requestModification: { (request) -> (Quack.Request) in
var request = request
request.encoding = .json
return request
})
}
/// Async version of `Consul.agentCheckUpdate(id: String, status: ConsulAgentCheckStatus, output: String)`
///
/// - SeeAlso: `Consul.agentCheckUpdate(id: String, status: ConsulAgentCheckStatus, output: String)`
/// - Parameter completion: completion block
public func agentCheckUpdate(id: String,
status: AgentCheckStatus,
output: String = "",
completion: @escaping (Quack.Void) -> (Void)) {
respondVoidAsync(method: .put,
path: "/v1/agent/check/update/\(id)",
body: Quack.JSONBody([
"Status": status.rawValue,
"Output": output
]),
requestModification: { (request) -> (Quack.Request) in
var request = request
request.encoding = .json
return request
},
completion: completion)
}
}
| mit | c21e79bb50c9355a79fbc289e13b16e3 | 38.784247 | 110 | 0.528536 | 4.676731 | false | false | false | false |
johnno1962d/swift | stdlib/public/core/ImplicitlyUnwrappedOptional.swift | 1 | 4182 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// An optional type that allows implicit member access.
@_fixed_layout
public enum ImplicitlyUnwrappedOptional<Wrapped> : NilLiteralConvertible {
// The compiler has special knowledge of the existence of
// `ImplicitlyUnwrappedOptional<Wrapped>`, but always interacts with it using
// the library intrinsics below.
case none
case some(Wrapped)
/// Construct a non-`nil` instance that stores `some`.
public init(_ some: Wrapped) { self = .some(some) }
/// Create an instance initialized with `nil`.
@_transparent
public init(nilLiteral: ()) {
self = .none
}
}
extension ImplicitlyUnwrappedOptional : CustomStringConvertible {
/// A textual representation of `self`.
public var description: String {
switch self {
case .some(let value):
return String(value)
case .none:
return "nil"
}
}
}
/// Directly conform to CustomDebugStringConvertible to support
/// optional printing. Implementation of that feature relies on
/// _isOptional thus cannot distinguish ImplicitlyUnwrappedOptional
/// from Optional. When conditional conformance is available, this
/// outright conformance can be removed.
extension ImplicitlyUnwrappedOptional : CustomDebugStringConvertible {
public var debugDescription: String {
return description
}
}
@_transparent
@warn_unused_result
public // COMPILER_INTRINSIC
func _stdlib_ImplicitlyUnwrappedOptional_isSome<Wrapped>
(_ `self`: Wrapped!) -> Bool {
return `self` != nil
}
@_transparent
@warn_unused_result
public // COMPILER_INTRINSIC
func _stdlib_ImplicitlyUnwrappedOptional_unwrapped<Wrapped>
(_ `self`: Wrapped!) -> Wrapped {
switch `self` {
case .some(let wrapped):
return wrapped
case .none:
_preconditionFailure(
"unexpectedly found nil while unwrapping an Optional value")
}
}
#if _runtime(_ObjC)
extension ImplicitlyUnwrappedOptional : _ObjectiveCBridgeable {
public func _bridgeToObjectiveC() -> AnyObject {
switch self {
case .none:
_preconditionFailure("attempt to bridge an implicitly unwrapped optional containing nil")
case .some(let x):
return Swift._bridgeToObjectiveC(x)!
}
}
public static func _forceBridgeFromObjectiveC(
_ x: AnyObject,
result: inout Wrapped!?
) {
result = Swift._forceBridgeFromObjectiveC(x, Wrapped.self)
}
public static func _conditionallyBridgeFromObjectiveC(
_ x: AnyObject,
result: inout Wrapped!?
) -> Bool {
let bridged: Wrapped? =
Swift._conditionallyBridgeFromObjectiveC(x, Wrapped.self)
if let value = bridged {
result = value
}
return false
}
public static func _isBridgedToObjectiveC() -> Bool {
return Swift._isBridgedToObjectiveC(Wrapped.self)
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: AnyObject?)
-> Wrapped! {
var result: Wrapped!?
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
#endif
extension ImplicitlyUnwrappedOptional {
@available(*, unavailable, message: "Please use nil literal instead.")
public init() {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, message: "Has been removed in Swift 3.")
public func map<U>(
_ f: @noescape (Wrapped) throws -> U
) rethrows -> ImplicitlyUnwrappedOptional<U> {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, message: "Has been removed in Swift 3.")
public func flatMap<U>(
_ f: @noescape (Wrapped) throws -> ImplicitlyUnwrappedOptional<U>
) rethrows -> ImplicitlyUnwrappedOptional<U> {
fatalError("unavailable function can't be called")
}
}
| apache-2.0 | 96b3763b100361e4d03b2f24317ab682 | 28.041667 | 95 | 0.683883 | 4.857143 | false | false | false | false |
mbrandonw/swift-fp | swift-fp/Ordering.swift | 1 | 2521 | import Foundation
enum Ordering {
case EQ
case LT
case GT
}
extension Ordering : Printable, DebugPrintable {
var description: String {
get {
switch self {
case .EQ: return "{Ordering EQ}"
case .LT: return "{Ordering LT}"
case .GT: return "{Ordering GT}"
}
}
}
var debugDescription: String {
get {
return self.description
}
}
}
extension Ordering : Semigroup {
func op (g: Ordering) -> Ordering {
switch (self, g) {
case (.LT, _): return .LT
case (.GT, _): return .GT
case let (.EQ, v): return v
}
}
}
extension Ordering : Monoid {
static func mzero () -> Ordering {
return .EQ
}
}
/**
A semigroup structure on functions (A -> Ordering)
*/
func sop <A> (f: A -> Ordering, g: A -> Ordering) -> A -> Ordering {
return {a in
return sop(f(a), g(a))
}
}
infix operator ++ {associativity left}
func ++ <A> (f: A -> Ordering, g: A -> Ordering) -> A -> Ordering {
return sop(f, g)
}
prefix operator ++ {}
prefix func ++ <A> (g: A -> Ordering) -> (A -> Ordering) -> (A -> Ordering) {
return {f in f ++ g}
}
postfix operator ++ {}
postfix func ++ <A> (f: A -> Ordering) -> (A -> Ordering) -> (A -> Ordering) {
return {g in f ++ g}
}
/**
A monoid structure on functions into Ordering
*/
func mzero <A> (x: A) -> Ordering {
return .EQ
}
/**
Equatable
*/
extension Ordering : Equatable {
}
func == (lhs: Ordering, rhs: Ordering) -> Bool {
switch (lhs, rhs) {
case (.LT, .LT), (.GT, .GT), (.EQ, .EQ):
return true
case (_, _):
return false
}
}
/**
Comprable
*/
extension Ordering : Comparable {
}
func < (lhs: Ordering, rhs: Ordering) -> Bool {
switch (lhs, rhs) {
case (.LT, .EQ), (.LT, .GT), (.LT, .GT), (.EQ, .GT):
return true
case (_, _):
return false
}
}
/**
Spaceship operator
*/
infix operator <=> {associativity left}
func <=> <A: Comparable> (left: A, right: A) -> Ordering {
if left < right { return .LT }
if left > right { return .GT }
return .EQ
}
/**
Converts a function that maps into a comparable type to
one that can order.
*/
func ordering <A: Comparable> (f: (A, A) -> Bool) -> (A, A) -> Ordering {
return {x, y in
if x == y {
return .EQ
} else if x < y {
return .LT
} else {
return .GT
}
}
}
func ordering <A, B: Comparable> (f: A -> B) -> (A, A) -> Ordering {
return {x, y in
let fx = f(x)
let fy = f(y)
if fx == fy { return .EQ }
if fx < fy { return .LT }
return .GT
}
}
| mit | b2f5a33ffd3cc252e28a2aeff5e2824b | 17.268116 | 78 | 0.547005 | 3.159148 | false | false | false | false |
GeekYong/JYMagicMove | JYMagicMove/JYMagicMove/JYMagicMoveTransion.swift | 1 | 2425 | //
// JYMagicMoveTransion.swift
// JYMagicMove
//
// Created by 杨勇 on 16/8/16.
// Copyright © 2016年 JackYang. All rights reserved.
//
import UIKit
class JYMagicMoveTransion: NSObject ,UIViewControllerAnimatedTransitioning{
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return 0.5;
}
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
//拿到 fromVC 和 toVC 以及 容器
let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as! ViewController
let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) as! JYDetailController
let container = transitionContext.containerView();
//拿到 cell上的 imageView的快照 隐藏 cell上的imageView
let snapshotView = fromVC.selectCell.imageView.snapshotViewAfterScreenUpdates(false)
//设置快照的frame
snapshotView.frame = container!.convertRect(fromVC.selectCell.imageView.frame, fromView: fromVC.selectCell.imageView.superview)
//隐藏
fromVC.selectCell.imageView.hidden = true
//设置toVC 的位置 并设置为透明
toVC.view.frame = transitionContext.finalFrameForViewController(toVC)
toVC.view.alpha = 0
toVC.avaterImageView.hidden = true
//把 toVC的 view 和 快照 加到 容器 上,顺序!
container?.addSubview(toVC.view)
container?.addSubview(snapshotView)
//做动画前先把avaterImageView 的frame 更新一下 不然 storyboard 尺寸没有更新
// toVC.avaterImageView.layoutIfNeeded()
UIView.animateWithDuration(transitionDuration(transitionContext), delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: {
() -> Void in
//动画
toVC.view.layoutIfNeeded()
snapshotView.frame = toVC.avaterImageView.frame
toVC.view.alpha = 1
}) { (finish:Bool) -> Void in
fromVC.selectCell.imageView.hidden = false // 把之前隐藏的 显示出来
toVC.avaterImageView.hidden = false
snapshotView.removeFromSuperview()
transitionContext.completeTransition(!transitionContext.transitionWasCancelled())
}
}
}
| mit | a56ef255c3a404ad5710cc2f296b63fb | 39.285714 | 145 | 0.68883 | 5.234339 | false | false | false | false |
BPForEveryone/BloodPressureForEveryone | BPApp/Shared/PersistentPatients.swift | 1 | 2566 | //
// PersistentPatients.swift
// BPApp
//
// Created by MiningMarsh on 9/26/17.
// Copyright © 2017 BlackstoneBuilds. All rights reserved.
//
import Foundation
import UIKit
import os.log
public class PersistentPatients {
// Where to save and load patient data.
static let DocumentsDirectory = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first!
static let PersistentStore = DocumentsDirectory.appendingPathComponent("patients")
// The list of patients we save.
static var patients: [Patient]?
static var lock = false
// Get a list of patients.
public func patientList() -> [Patient] {
objc_sync_enter(PersistentPatients.lock)
defer { objc_sync_exit(PersistentPatients.lock) }
if PersistentPatients.patients == nil {
PersistentPatients.patients = []
}
return PersistentPatients.patients!
}
// Initializer
init?() {
objc_sync_enter(PersistentPatients.lock)
defer { objc_sync_exit(PersistentPatients.lock) }
// If we haven't yet grabbed patients, do it now.
if PersistentPatients.patients == nil {
restore()
}
}
// Persist whenever the object is destroyed.
deinit {
persist();
}
// Persist the patients.
private func persist() {
objc_sync_enter(PersistentPatients.lock)
defer { objc_sync_exit(PersistentPatients.lock) }
if let patients = PersistentPatients.patients {
let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(patients, toFile: PersistentPatients.PersistentStore.path)
if isSuccessfulSave {
os_log("Patients persisted.", log: OSLog.default, type: .debug)
} else {
os_log("Failed to persist patients...", log: OSLog.default, type: .error)
}
}
}
// Restore the patients from persistent store.
private func restore() {
objc_sync_enter(PersistentPatients.lock)
defer { objc_sync_exit(PersistentPatients.lock) }
if let restored = NSKeyedUnarchiver.unarchiveObject(withFile: PersistentPatients.PersistentStore.path) as? [Patient] {
PersistentPatients.patients = restored
os_log("Patients restored.", log: OSLog.default, type: .debug)
} else {
os_log("Failed to restore patients.", log: OSLog.default, type: .debug)
PersistentPatients.patients = []
}
}
}
| mit | 59686b79c9f615292a89dc1be4e080b0 | 30.666667 | 127 | 0.622222 | 4.422414 | false | false | false | false |
PlanTeam/BSON | Sources/BSON/Document/DocumentSlice.swift | 1 | 2688 | public struct DocumentSlice: RandomAccessCollection {
public func index(before i: DocumentIndex) -> DocumentIndex {
return DocumentIndex(offset: i.offset - 1)
}
public func index(after i: DocumentIndex) -> DocumentIndex {
return DocumentIndex(offset: i.offset + 1)
}
public subscript(position: DocumentIndex) -> (String, Primitive) {
return document.pair(atIndex: position)!
}
public subscript(bounds: Range<DocumentIndex>) -> DocumentSlice {
DocumentSlice(document: document, startIndex: bounds.lowerBound, endIndex: bounds.upperBound)
}
public typealias Element = (String, Primitive)
public typealias SubSequence = DocumentSlice
let document: Document
public let startIndex: DocumentIndex
public let endIndex: DocumentIndex
}
public struct DocumentIterator: IteratorProtocol {
/// The Document that is being iterated over
fileprivate let document: Document
/// The next index to be returned
private var currentIndex = 0
private var currentBinaryIndex = 4
/// If `true`, the end of this iterator has been reached
private var isDrained: Bool {
return count <= currentIndex
}
/// The total amount of elements in this iterator (previous, current and upcoming elements)
private let count: Int
/// Creates an iterator for a given Document
public init(document: Document) {
self.document = document
self.count = document.count
}
/// Returns the next element in the Document *unless* the last element was already returned
public mutating func next() -> (String, Primitive)? {
guard currentIndex < count else { return nil }
defer { currentIndex += 1 }
guard
let typeByte = document.storage.getByte(at: currentBinaryIndex),
let type = TypeIdentifier(rawValue: typeByte)
else {
return nil
}
currentBinaryIndex += 1
guard
let key = document.getKey(at: currentBinaryIndex),
document.skipKey(at: ¤tBinaryIndex),
let valueLength = document.valueLength(forType: type, at: currentBinaryIndex),
let value = document.value(forType: type, at: currentBinaryIndex)
else {
return nil
}
currentBinaryIndex += valueLength
return (key, value)
}
}
extension Document {
func pair(atIndex index: DocumentIndex) -> (String, Primitive)? {
guard index.offset < count else { return nil }
return (keys[index.offset], values[index.offset])
}
}
| mit | aa90425e2ab5971e7c0358ededbe1ef7 | 31 | 101 | 0.639881 | 4.95941 | false | false | false | false |
akrio714/Wbm | Wbm/Component/UIImage/UIImage+Extension.swift | 1 | 2830 | //
// UIImage+Extension.swift
// Wbm
//
// Created by akrio on 2017/7/20.
// Copyright © 2017年 akrio. All rights reserved.
//
import UIKit
extension UIImage {
/// 设置图片颜色
///
/// - Parameter tintColor: 修改的图片颜色
/// - Returns: 修改后的图片
func imageWithTintColor(tintColor:UIColor) -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.size, false, 0)
tintColor.setFill()
let bounds = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)
UIRectFill(bounds)
self.draw(in: bounds, blendMode: .destinationIn, alpha: 1)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
/**
* 重设图片大小
*/
func reSizeImage(reSize:CGSize)->UIImage {
//UIGraphicsBeginImageContext(reSize);
UIGraphicsBeginImageContextWithOptions(reSize,false,UIScreen.main.scale);
self.draw(in: CGRect(x:0,y: 0,width: reSize.width,height: reSize.height));
let reSizeImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!;
UIGraphicsEndImageContext();
return reSizeImage;
}
/// 根据颜色生成图片
///
/// - Parameter color: 生成图片颜色
class func initWith(color:UIColor?) -> UIImage? {
guard let color = color else {
return nil
}
let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(color.cgColor)
context?.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image ?? nil
}
//生成圆形图片
func toCircle() -> UIImage {
//取最短边长
let shotest = min(self.size.width, self.size.height)
//输出尺寸
let outputRect = CGRect(x: 0, y: 0, width: shotest, height: shotest)
//开始图片处理上下文(由于输出的图不会进行缩放,所以缩放因子等于屏幕的scale即可)
UIGraphicsBeginImageContextWithOptions(outputRect.size, false, 0)
let context = UIGraphicsGetCurrentContext()!
//添加圆形裁剪区域
context.addEllipse(in: outputRect)
context.clip()
//绘制图片
self.draw(in: CGRect(x: (shotest-self.size.width)/2,
y: (shotest-self.size.height)/2,
width: self.size.width,
height: self.size.height))
//获得处理后的图片
let maskedImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return maskedImage
}
}
| apache-2.0 | b22bc43adbc6be2dc8ca51df60ebefa1 | 34.202703 | 89 | 0.619962 | 4.341667 | false | true | false | false |
DATX02-16-86/Code | TreeLSystem/TreeLSystemRenderer/TreeLSystemRenderer/GameViewController.swift | 1 | 3796 | import SceneKit
import QuartzCore
class GameViewController: NSViewController {
@IBOutlet weak var gameView: SCNView!
let height: CGFloat = 20
let distance: CGFloat = 50
override func awakeFromNib(){
// create a new scene
let scene = SCNScene()
// create and add a camera to the scene
let cameraNode = SCNNode()
cameraNode.camera = SCNCamera()
scene.rootNode.addChildNode(cameraNode)
// create and add tree object
let tree = TreeLSystemBridge()
let treeNode = SCNNode()
for vector in tree.voxels.map({ $0.vector }) {
let cubeGeometry = SCNBox(width: 0.1, height: 0.1, length: 0.1, chamferRadius: 0)
let material = SCNMaterial()
let variance = CGFloat(Int(arc4random_uniform(50)) - 25) / 255.0
material.diffuse.contents = NSColor(red: 139.0 / 255.0 + variance, green: 69.0 / 255.0 + variance, blue: 19.0 / 255.9 + variance, alpha: 1.0)
cubeGeometry.materials = [material]
let cubeNode = SCNNode(geometry: cubeGeometry)
cubeNode.position = vector
treeNode.addChildNode(cubeNode)
}
scene.rootNode.addChildNode(treeNode)
treeNode.runAction(SCNAction.repeatActionForever(SCNAction.rotateByX(0, y: 2*CGFloat(M_PI), z: 0, duration: 180)))
// place the camera
cameraNode.position = SCNVector3(x: 0, y: height, z: distance)
// create and add an ambient light to the scene
let ambientLightNode = SCNNode()
ambientLightNode.light = SCNLight()
ambientLightNode.light!.type = SCNLightTypeAmbient
ambientLightNode.light!.color = NSColor.darkGrayColor()
scene.rootNode.addChildNode(ambientLightNode)
// set the scene to the view
self.gameView.scene = scene
// allows the user to manipulate the camera
self.gameView.allowsCameraControl = true
// configure the view
self.gameView.backgroundColor = NSColor.whiteColor()
}
}
//* -------------------------------------------------------------------------------------------- *//
//import SceneKit
//import QuartzCore
//
//class GameViewController: NSViewController {
//
// @IBOutlet weak var gameView: SCNView!
//
// override func awakeFromNib(){
// // create a new scene
// let scene = SCNScene()
//
// // create and add a camera to the scene
// let cameraNode = SCNNode()
// cameraNode.camera = SCNCamera()
// scene.rootNode.addChildNode(cameraNode)
//
// // place the camera
// cameraNode.position = SCNVector3(x: 0, y: 1, z: 5)
//
// // create and add an ambient light to the scene
// let ambientLightNode = SCNNode()
// ambientLightNode.light = SCNLight()
// ambientLightNode.light!.type = SCNLightTypeAmbient
// ambientLightNode.light!.color = NSColor.darkGrayColor()
// scene.rootNode.addChildNode(ambientLightNode)
//
// // create and add tree object
// let tree = TreeLSystemBridge()
// let vertices = tree.vertices.map { $0.vector }
// let indices = tree.indices.map { CInt($0.integerValue) }
// let material = SCNMaterial()
// material.diffuse.contents = NSColor(red: 139.0 / 255.0, green: 69.0 / 255.0, blue: 19.0 / 255.9, alpha: 1.0)
// let geometrySrc = SCNGeometrySource(vertices: vertices, count: vertices.count)
// let geometryEl = SCNGeometryElement(indices: indices, primitiveType: .Triangles)
// let geometry = SCNGeometry(sources: [geometrySrc], elements: [geometryEl])
// geometry.materials = [material]
// scene.rootNode.addChildNode(SCNNode(geometry: geometry))
//
// // set the scene to the view
// self.gameView.scene = scene
//
// // allows the user to manipulate the camera
// self.gameView.allowsCameraControl = true
//
// // configure the view
// self.gameView.backgroundColor = NSColor.whiteColor()
// }
//
//}
| mit | 8d95c3acf4f2ac0a55f4b6b19e26b558 | 33.198198 | 147 | 0.65569 | 4.108225 | false | false | false | false |
laurentVeliscek/AudioKit | AudioKit/Common/Nodes/Effects/Filters/High Shelf Parametric Equalizer Filter/AKHighShelfParametricEqualizerFilter.swift | 1 | 5663 | //
// AKHighShelfParametricEqualizerFilter.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright (c) 2016 Aurelius Prochazka. All rights reserved.
//
import AVFoundation
/// This is an implementation of Zoelzer's parametric equalizer filter.
///
/// - Parameters:
/// - input: Input node to process
/// - centerFrequency: Corner frequency.
/// - gain: Amount at which the corner frequency value shall be increased or decreased. A value of 1 is a flat response.
/// - q: Q of the filter. sqrt(0.5) is no resonance.
///
public class AKHighShelfParametricEqualizerFilter: AKNode, AKToggleable {
// MARK: - Properties
internal var internalAU: AKHighShelfParametricEqualizerFilterAudioUnit?
internal var token: AUParameterObserverToken?
private var centerFrequencyParameter: AUParameter?
private var gainParameter: AUParameter?
private var qParameter: AUParameter?
/// Ramp Time represents the speed at which parameters are allowed to change
public var rampTime: Double = AKSettings.rampTime {
willSet {
if rampTime != newValue {
internalAU?.rampTime = newValue
internalAU?.setUpParameterRamp()
}
}
}
/// Corner frequency.
public var centerFrequency: Double = 1000 {
willSet {
if centerFrequency != newValue {
if internalAU!.isSetUp() {
centerFrequencyParameter?.setValue(Float(newValue), originator: token!)
} else {
internalAU?.centerFrequency = Float(newValue)
}
}
}
}
/// Amount at which the corner frequency value shall be increased or decreased. A value of 1 is a flat response.
public var gain: Double = 1.0 {
willSet {
if gain != newValue {
if internalAU!.isSetUp() {
gainParameter?.setValue(Float(newValue), originator: token!)
} else {
internalAU?.gain = Float(newValue)
}
}
}
}
/// Q of the filter. sqrt(0.5) is no resonance.
public var q: Double = 0.707 {
willSet {
if q != newValue {
if internalAU!.isSetUp() {
qParameter?.setValue(Float(newValue), originator: token!)
} else {
internalAU?.q = Float(newValue)
}
}
}
}
/// Tells whether the node is processing (ie. started, playing, or active)
public var isStarted: Bool {
return internalAU!.isPlaying()
}
// MARK: - Initialization
/// Initialize this equalizer node
///
/// - Parameters:
/// - input: Input node to process
/// - centerFrequency: Corner frequency.
/// - gain: Amount at which the corner frequency value shall be increased or decreased. A value of 1 is a flat response.
/// - q: Q of the filter. sqrt(0.5) is no resonance.
///
public init(
_ input: AKNode,
centerFrequency: Double = 1000,
gain: Double = 1.0,
q: Double = 0.707) {
self.centerFrequency = centerFrequency
self.gain = gain
self.q = q
var description = AudioComponentDescription()
description.componentType = kAudioUnitType_Effect
description.componentSubType = 0x70657132 /*'peq2'*/
description.componentManufacturer = 0x41754b74 /*'AuKt'*/
description.componentFlags = 0
description.componentFlagsMask = 0
AUAudioUnit.registerSubclass(
AKHighShelfParametricEqualizerFilterAudioUnit.self,
asComponentDescription: description,
name: "Local AKHighShelfParametricEqualizerFilter",
version: UInt32.max)
super.init()
AVAudioUnit.instantiateWithComponentDescription(description, options: []) {
avAudioUnit, error in
guard let avAudioUnitEffect = avAudioUnit else { return }
self.avAudioNode = avAudioUnitEffect
self.internalAU = avAudioUnitEffect.AUAudioUnit as? AKHighShelfParametricEqualizerFilterAudioUnit
AudioKit.engine.attachNode(self.avAudioNode)
input.addConnectionPoint(self)
}
guard let tree = internalAU?.parameterTree else { return }
centerFrequencyParameter = tree.valueForKey("centerFrequency") as? AUParameter
gainParameter = tree.valueForKey("gain") as? AUParameter
qParameter = tree.valueForKey("q") as? AUParameter
token = tree.tokenByAddingParameterObserver {
address, value in
dispatch_async(dispatch_get_main_queue()) {
if address == self.centerFrequencyParameter!.address {
self.centerFrequency = Double(value)
} else if address == self.gainParameter!.address {
self.gain = Double(value)
} else if address == self.qParameter!.address {
self.q = Double(value)
}
}
}
internalAU?.centerFrequency = Float(centerFrequency)
internalAU?.gain = Float(gain)
internalAU?.q = Float(q)
}
// MARK: - Control
/// Function to start, play, or activate the node, all do the same thing
public func start() {
self.internalAU!.start()
}
/// Function to stop or bypass the node, both are equivalent
public func stop() {
self.internalAU!.stop()
}
}
| mit | bca5c677feb4c1512752f560b58639d4 | 33.530488 | 126 | 0.595444 | 5.152866 | false | false | false | false |
peterprokop/AlertyAlert | AlertyAlert/Alerty.swift | 1 | 1789 | //
// Alerty.swift
// AlertyAlertExample
//
// Created by Peter Prokop on 23/01/2017.
// Copyright © 2017 Prokop. All rights reserved.
//
import Foundation
open class Alerty {
public static var `default` = Alerty()
open var style = AlertyStyle()
open func alert(withTitle title: String?, message: String?) -> AlertyAlertController {
let bundle = Bundle(for: Alerty.self)
let storyboard = UIStoryboard(name: "AlertyAlert", bundle: bundle)
let alertyAlertController = storyboard.instantiateViewController(withIdentifier: "AlertyAlertController") as! AlertyAlertController
alertyAlertController.title = title
alertyAlertController.message = message
alertyAlertController.style = style
return alertyAlertController
}
public init() {}
public init(style: AlertyStyle) {
self.style = style
}
}
open class AlertyStyle {
open var cornerRadius = CGFloat(15)
open var backgroundColor = UIColor.white
open var buttonBorderColor: UIColor? = UIColor.lightGray
open var titleFont: UIFont?
open var titleColor = UIColor.black
open var messageFont: UIFont?
open var messageColor = UIColor.black
open var defaultActionStyle = AlertyActionStyle(font: UIFont.systemFont(ofSize: 15, weight: UIFontWeightRegular), tintColor: nil)
open var cancelActionStyle = AlertyActionStyle(font: UIFont.systemFont(ofSize: 15, weight: UIFontWeightSemibold), tintColor: nil)
open var destructiveActionStyle = AlertyActionStyle(font: UIFont.systemFont(ofSize: 15, weight: UIFontWeightRegular), tintColor: UIColor(red: 1, green: 0.23, blue: 0.12, alpha: 1))
public init() {}
}
| mit | 690ba31395d89a7940ba010d0ff0b6e9 | 28.8 | 184 | 0.678971 | 4.57289 | false | false | false | false |
contentful/contentful.swift | Sources/Contentful/DataCache.swift | 1 | 1830 | //
// DataCache.swift
// Contentful
//
// Created by JP Wright on 31.07.17.
// Copyright © 2017 Contentful GmbH. All rights reserved.
//
import Foundation
internal class DataCache {
private static let cacheKeyDelimiter = "_"
internal static func cacheKey(for link: Link) -> String {
let linkType: String
switch link {
case .asset: linkType = "asset"
case .entry, .entryDecodable: linkType = "entry"
case .unresolved(let sys): linkType = sys.linkType
}
let cacheKey = DataCache.cacheKey(id: link.id, linkType: linkType)
return cacheKey
}
private static func cacheKey(id: String, linkType: String) -> String {
let delimeter = DataCache.cacheKeyDelimiter
let cacheKey = id + delimeter + linkType.lowercased() + delimeter
return cacheKey
}
private var assetCache = Dictionary<String, Asset>()
private var entryCache = Dictionary<String, Any>()
internal func add(asset: Asset) {
assetCache[DataCache.cacheKey(id: asset.id, linkType: "Asset")] = asset
}
internal func add(entry: EntryDecodable) {
entryCache[DataCache.cacheKey(id: entry.id, linkType: "Entry")] = entry
}
internal func asset(for identifier: String) -> Asset? {
return assetCache[identifier]
}
internal func entry(for identifier: String) -> EntryDecodable? {
return entryCache[identifier] as? EntryDecodable
}
internal func item<T>(for identifier: String) -> T? {
return item(for: identifier) as? T
}
internal func item(for identifier: String) -> Any? {
var target: Any? = self.asset(for: identifier)
if target == nil {
target = self.entry(for: identifier)
}
return target
}
}
| mit | 032d92a5d56dedd3e9c3c226f024620d | 27.138462 | 79 | 0.624932 | 4.175799 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/UserInterface/Helpers/UIFont+MonoSpaced.swift | 1 | 2787 | //
// Wire
// Copyright (C) 2016 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import UIKit
private let monospacedFeatureSettingsAttribute = [
UIFontDescriptor.FeatureKey.featureIdentifier: kNumberSpacingType,
UIFontDescriptor.FeatureKey.typeIdentifier: kMonospacedNumbersSelector
]
private let monospaceAttribute = [
UIFontDescriptor.AttributeName.featureSettings: [monospacedFeatureSettingsAttribute]
]
private let smallCapsFeatureSettingsAttributeLowerCase = [
UIFontDescriptor.FeatureKey.featureIdentifier: kLowerCaseType,
UIFontDescriptor.FeatureKey.typeIdentifier: kLowerCaseSmallCapsSelector
]
private let smallCapsFeatureSettingsAttributeUpperCase = [
UIFontDescriptor.FeatureKey.featureIdentifier: kUpperCaseType,
UIFontDescriptor.FeatureKey.typeIdentifier: kUpperCaseSmallCapsSelector
]
private let proportionalNumberSpacingFeatureSettingAttribute = [
UIFontDescriptor.FeatureKey.featureIdentifier: kNumberSpacingType,
UIFontDescriptor.FeatureKey.typeIdentifier: kProportionalNumbersSelector
]
private let smallCapsAttribute = [
UIFontDescriptor.AttributeName.featureSettings: [smallCapsFeatureSettingsAttributeLowerCase, smallCapsFeatureSettingsAttributeUpperCase]
]
private let proportionalNumberSpacingAttribute = [
UIFontDescriptor.AttributeName.featureSettings: [proportionalNumberSpacingFeatureSettingAttribute]
]
extension UIFont {
@objc func monospaced() -> UIFont {
let descriptor = fontDescriptor
let monospaceFontDescriptor = descriptor.addingAttributes(monospaceAttribute)
return UIFont(descriptor: monospaceFontDescriptor, size: 0.0)
}
func smallCaps() -> UIFont {
let descriptor = fontDescriptor
let allCapsDescriptor = descriptor.addingAttributes(smallCapsAttribute)
return UIFont(descriptor: allCapsDescriptor, size: 0.0)
}
func proportionalNumberSpacing() -> UIFont {
let descriptor = fontDescriptor
let propertionalNumberSpacingDescriptor = descriptor.addingAttributes(proportionalNumberSpacingAttribute)
return UIFont(descriptor: propertionalNumberSpacingDescriptor, size: 0.0)
}
}
| gpl-3.0 | a92cacea89d5bc21c3c94809dfab7e27 | 37.178082 | 140 | 0.789738 | 5.067273 | false | false | false | false |
Holmusk/HMRequestFramework-iOS | HMRequestFrameworkTests/database/CoreDataManagerTest.swift | 1 | 21528 | //
// CoreDataManagerTest.swift
// HMRequestFrameworkTests
//
// Created by Hai Pham on 21/7/17.
// Copyright © 2017 Holmusk. All rights reserved.
//
import CoreData
import RxSwift
import RxBlocking
import RxTest
import SwiftUtilities
import SwiftUtilitiesTests
import XCTest
@testable import HMRequestFramework
public final class CoreDataManagerTest: CoreDataRootTest {
public func test_constructBuildable_shouldWork() {
/// Setup
let observer = scheduler.createObserver(Dummy2.self)
let expect = expectation(description: "Should have completed")
let manager = self.manager!
let context = manager.disposableObjectContext()
let dummies = (0..<10000).map({_ in Dummy2()})
/// When
manager.rx.construct(context, dummies)
.subscribeOnConcurrent(qos: .background)
.flattenSequence()
.map({try! $0.asPureObject()})
.doOnDispose(expect.fulfill)
.subscribe(observer)
.disposed(by: disposeBag)
waitForExpectations(timeout: timeout, handler: nil)
/// Then
let nextElements = observer.nextElements()
XCTAssertEqual(dummies, nextElements)
}
public func test_saveAndFetchBuildable_shouldWork() {
/// Setup
let observer = scheduler.createObserver(Dummy1.self)
let expect = expectation(description: ("Should have completed"))
let dummyCount = self.dummyCount!
let manager = self.manager!
let dummies = (0..<dummyCount).map({_ in Dummy1()})
let fetchRq = try! dummy1FetchRequest().fetchRequest(Dummy1.self)
// Different contexts for each operation.
let saveContext = manager.disposableObjectContext()
let fetchContext1 = manager.disposableObjectContext()
let fetchContext2 = manager.disposableObjectContext()
/// When
// Save the dummies in memory. Their NSManagedObject equivalents will
// be constructed here.
manager.rx.savePureObjects(saveContext, dummies)
// Perform a fetch to verify that the data have been inserted, but
// not persisted.
.flatMap({manager.rx.fetch(fetchContext1, fetchRq).subscribeOnConcurrent(qos: .background)})
.doOnNext({XCTAssertEqual($0.count, dummyCount)})
.map(toVoid)
// Persist the data.
.flatMap({manager.rx.persistLocally()})
// Fetch the data and verify that they have been persisted.
.flatMap({manager.rx.fetch(fetchContext2, fetchRq)})
.map({$0.map({try! $0.asPureObject()})})
.subscribeOnConcurrent(qos: .background)
.flattenSequence()
.doOnDispose(expect.fulfill)
.subscribe(observer)
.disposed(by: disposeBag)
waitForExpectations(timeout: timeout, handler: nil)
/// Then
let nextElements = observer.nextElements()
XCTAssertEqual(nextElements.count, dummyCount)
XCTAssertTrue(nextElements.all(dummies.contains))
}
}
public extension CoreDataManagerTest {
public func test_refetchUpsertables_shouldWork() {
/// Setup
let observer = scheduler.createObserver(Dummy1.self)
let expect = expectation(description: "Should have completed")
let manager = self.manager!
let context = manager.disposableObjectContext()
let dummyCount = self.dummyCount!
let pureObjects = (0..<dummyCount).flatMap({_ in Dummy1()})
let cdObjects = try! manager.constructUnsafely(context, pureObjects)
let entityName = try! Dummy1.CDClass.entityName()
// Different contexts.
let saveContext = manager.disposableObjectContext()
let refetchContext = manager.disposableObjectContext()
/// When
// Save data without persisting to DB.
manager.rx.savePureObjects(saveContext, pureObjects)
// Persist data to DB.
.flatMap({_ in manager.rx.persistLocally()})
// Refetch based on identifiable objects. We expect the returned
// data to contain the same properties.
.flatMap({manager.rx.fetchIdentifiables(refetchContext, entityName, cdObjects)})
.map({$0.map({try! $0.asPureObject()})})
.subscribeOnConcurrent(qos: .background)
.flattenSequence()
.doOnDispose(expect.fulfill)
.subscribe(observer)
.disposed(by: disposeBag)
waitForExpectations(timeout: timeout, handler: nil)
/// Then
let nextElements = observer.nextElements()
XCTAssertEqual(nextElements.count, dummyCount)
XCTAssertTrue(nextElements.all(pureObjects.contains))
}
public func test_insertAndDeleteUpsertables_shouldWork() {
/// Setup
let observer = scheduler.createObserver(Dummy1.CDClass.self)
let expect = expectation(description: "Should have completed")
let manager = self.manager!
// Two contexts for two operations, no shared context.
let context = manager.disposableObjectContext()
let dummyCount = self.dummyCount!
let pureObjects1 = (0..<dummyCount).map({_ in Dummy1()})
let pureObjects2 = (0..<dummyCount).flatMap({(i) -> Dummy1 in
Dummy1.builder().with(id: pureObjects1[i].id).build()
})
let cdObjects1 = try! manager.constructUnsafely(context, pureObjects1)
let cdObjects2 = try! manager.constructUnsafely(context, pureObjects2)
let fetchRq = try! Req.builder()
.with(poType: Dummy1.self)
.with(operation: .fetch)
.with(predicate: NSPredicate(value: true))
.build()
.fetchRequest(Dummy1.CDClass.self)
let entityName = fetchRq.entityName!
// Different contexts.
let saveContext = manager.disposableObjectContext()
let fetchContext1 = manager.disposableObjectContext()
let deleteContext = manager.disposableObjectContext()
let fetchContext2 = manager.disposableObjectContext()
/// When
// Save data1 to memory without persisting to DB.
manager.rx.saveConvertibles(saveContext, cdObjects1)
// Persist changes to DB. At this stage, data1 is the only set
// of data within the DB.
.flatMap({_ in manager.rx.persistLocally()})
// Fetch to verify that the DB only contains data1.
.flatMap({manager.rx.fetch(fetchContext1, fetchRq)})
.map({$0.map({try! $0.asPureObject()})})
.doOnNext({XCTAssertTrue($0.all(pureObjects1.contains))})
.doOnNext({XCTAssertEqual($0.count, dummyCount)})
// Delete data2 from memory. data1 and data2 are two different
// sets of data that only have the same primary key-value.
.flatMap({_ in manager.rx.deleteIdentifiables(deleteContext,
entityName,
cdObjects2)})
// Persist changes to DB.
.flatMap({manager.rx.persistLocally()})
// Fetch to verify that the DB is now empty.
.flatMap({manager.rx.fetch(fetchContext2, fetchRq)})
.subscribeOnConcurrent(qos: .background)
.flattenSequence()
.doOnDispose(expect.fulfill)
.subscribe(observer)
.disposed(by: disposeBag)
waitForExpectations(timeout: timeout, handler: nil)
/// Then
let nextElements = observer.nextElements()
XCTAssertEqual(nextElements.count, 0)
}
}
public extension CoreDataManagerTest {
public func test_insertAndDeleteByBatch_shouldWork() {
let manager = self.manager!
// This does not work for in-memory store.
if manager.areAllStoresInMemory() {
return
}
/// Setup
let observer = scheduler.createObserver(Any.self)
let expect = expectation(description: "Should have completed")
let dummyCount = self.dummyCount!
let pureObjects = (0..<dummyCount).map({_ in Dummy1()})
let fetchRequest = try! dummy1FetchRequest().fetchRequest(Dummy1.self)
let deleteRequest = try! dummy1FetchRequest().untypedFetchRequest()
// Different contexts.
let saveContext = manager.disposableObjectContext()
let fetchContext1 = manager.disposableObjectContext()
let deleteContext = manager.disposableObjectContext()
let fetchContext2 = manager.disposableObjectContext()
/// When
manager.rx.savePureObjects(saveContext, pureObjects)
.flatMap({_ in manager.rx.persistLocally()})
.flatMap({manager.rx.fetch(fetchContext1, fetchRequest)})
.map({$0.map({try! $0.asPureObject()})})
.doOnNext({XCTAssertEqual($0.count, dummyCount)})
.doOnNext({XCTAssertTrue(pureObjects.all($0.contains))})
.flatMap({_ in manager.rx.delete(deleteContext, deleteRequest)})
.flatMap({_ in manager.rx.persistLocally()})
.flatMap({_ in manager.rx.fetch(fetchContext2, fetchRequest)})
.map({$0.map({try! $0.asPureObject()})})
.flattenSequence()
.cast(to: Any.self)
.doOnDispose(expect.fulfill)
.subscribe(observer)
.disposed(by: disposeBag)
waitForExpectations(timeout: timeout, handler: nil)
/// Then
let nextElements = observer.nextElements()
XCTAssertEqual(nextElements.count, 0)
}
public func test_insertAndDeleteManyRandomDummies_shouldWork() {
/// Setup
let observer = scheduler.createObserver(Any.self)
let expect = expectation(description: "Should have completed")
let manager = self.manager!
let iterationCount = 10
let dummyCount = 100
let request = try! dummy1FetchRequest().fetchRequest(Dummy1.self)
let entityName = request.entityName!
// Different contexts
let fetchContext1 = manager.disposableObjectContext()
let fetchContext2 = manager.disposableObjectContext()
/// When
Observable.from((0..<iterationCount).map({$0}))
// For each iteration, create a bunch of dummies in a disposable
// context and save them in memory. The main context should then
// own the changes.
.flatMap({(i) -> Observable<Void> in
// Always beware that if we don't keep a reference to the
// context, CD objects may lose their data.
let sc1 = manager.disposableObjectContext()
return Observable<[Dummy1]>
.create({
let pureObjects = (0..<dummyCount).map({_ in Dummy1()})
$0.onNext(pureObjects)
$0.onCompleted()
return Disposables.create()
})
.flatMap({manager.rx.savePureObjects(sc1, $0)})
.map(toVoid)
.subscribeOnConcurrent(qos: .background)
})
.reduce((), accumulator: {(_, _) in ()})
// Persist all changes to DB.
.flatMap({manager.rx.persistLocally()})
// Fetch to verify that the data have been persisted.
.flatMap({manager.rx.fetch(fetchContext1, request)})
.doOnNext({XCTAssertEqual($0.count, iterationCount * dummyCount)})
.doOnNext({XCTAssertTrue($0.flatMap({$0.id}).count > 0)})
.map({$0.map({try! $0.asPureObject()})})
.flatMap({(objects) -> Observable<Void> in
let sc = manager.disposableObjectContext()
return manager.rx.deleteIdentifiables(sc, entityName, objects)
})
// Persist the changes.
.flatMap({manager.rx.persistLocally()})
// Fetch to verify that the data have been deleted.
.flatMap({manager.rx.fetch(fetchContext2, request).subscribeOnConcurrent(qos: .background)})
.map({$0.map({try! $0.asPureObject()})})
.subscribeOnConcurrent(qos: .background)
.flattenSequence()
.cast(to: Any.self)
.doOnDispose(expect.fulfill)
.subscribe(observer)
.disposed(by: disposeBag)
waitForExpectations(timeout: timeout, handler: nil)
/// Then
let elements = observer.nextElements()
XCTAssertEqual(elements.count, 0)
}
}
public extension CoreDataManagerTest {
public func test_predicateForIdentifiableFetch_shouldWork() {
/// Setup
let times = 100
let pureObjs1 = (0..<times).map({_ in Dummy1()})
let pureObjs2 = (0..<times).map({_ in Dummy2()})
let allUpsertables = [
pureObjs1.map({$0 as HMIdentifiableType}),
pureObjs2.map({$0 as HMIdentifiableType})
].flatMap({$0})
/// When
let predicate = manager.predicateForIdentifiableFetch(allUpsertables)
/// Then
let description = predicate.description
XCTAssertTrue(description.contains("IN"))
XCTAssertTrue(description.contains("OR"))
}
}
public extension CoreDataManagerTest {
public func test_saveConvertiblesToDB_shouldWork() {
/// Setup
let observer = scheduler.createObserver(Dummy1.self)
let expect = expectation(description: "Should have completed")
let manager = self.manager!
let context = manager.disposableObjectContext()
let dummyCount = self.dummyCount!
let pureObjects = (0..<dummyCount).map({_ in Dummy1()})
let convertibles = try! manager.constructUnsafely(context, pureObjects)
let fetchRq = try! dummy1FetchRequest().fetchRequest(Dummy1.self)
// Different contexts.
let saveContext = manager.disposableObjectContext()
let fetchContext = manager.disposableObjectContext()
/// When
// The convertible objects should be converted into their NSManagedObject
// counterparts here. Even if we do not have access to the context that
// created these objects, we can reconstruct them and insert into another
// context of choice.
manager.rx.saveConvertibles(saveContext, convertibles)
.doOnNext({XCTAssertTrue($0.all({$0.isSuccess()}))})
.flatMap({_ in manager.rx.persistLocally()})
.flatMap({manager.rx.fetch(fetchContext, fetchRq)})
.map({$0.map({try! $0.asPureObject()})})
.subscribeOnConcurrent(qos: .background)
.flattenSequence()
.doOnDispose(expect.fulfill)
.subscribe(observer)
.disposed(by: disposeBag)
waitForExpectations(timeout: timeout, handler: nil)
/// Then
let nextElements = observer.nextElements()
XCTAssertEqual(nextElements.count, pureObjects.count)
XCTAssertTrue(pureObjects.all(nextElements.contains))
}
public func test_upsertConvertibles_shouldWork() {
/// Setup
let observer = scheduler.createObserver(Dummy1.self)
let expect = expectation(description: "Should have completed")
let manager = self.manager!
let context = manager.disposableObjectContext()
let dummyCount = self.dummyCount!
let originalPureObjects = (0..<dummyCount).map({_ in Dummy1()})
let editedPureObjects = (0..<dummyCount).map({(i) -> Dummy1 in
Dummy1.builder().with(id: originalPureObjects[i].id).build()
})
let newPureObjects = (0..<dummyCount).map({_ in Dummy1()})
let upsertedPureObjects = [editedPureObjects, newPureObjects].flatMap({$0})
let upsertedCDObjects = try! manager.constructUnsafely(context, upsertedPureObjects)
let fetchRq = try! dummy1FetchRequest().fetchRequest(Dummy1.self)
let entityName = fetchRq.entityName!
// Different contexts.
let saveContext = manager.disposableObjectContext()
let upsertContext = manager.disposableObjectContext()
let fetchContext = manager.disposableObjectContext()
/// When
manager.rx.savePureObjects(saveContext, originalPureObjects)
.flatMap({_ in manager.rx.persistLocally()})
// We expect the edited data to overwrite, while new data will
// simply be inserted.
.flatMap({_ in manager.rx.upsert(upsertContext, entityName, upsertedCDObjects)})
.flatMap({_ in manager.rx.persistLocally()})
.flatMap({manager.rx.fetch(fetchContext, fetchRq)})
.map({$0.map({try! $0.asPureObject()})})
.subscribeOnConcurrent(qos: .background)
.flattenSequence()
.doOnDispose(expect.fulfill)
.subscribe(observer)
.disposed(by: disposeBag)
waitForExpectations(timeout: timeout, handler: nil)
/// Then
let nextElements = observer.nextElements()
XCTAssertEqual(nextElements.count, upsertedPureObjects.count)
XCTAssertTrue(upsertedPureObjects.all(nextElements.contains))
}
}
public extension CoreDataManagerTest {
public func test_fetchLimit_shouldWork() {
/// Setup
let observer = scheduler.createObserver(Dummy1.self)
let expect = expectation(description: "Should have completed")
let manager = self.manager!
let dummyCount = self.dummyCount!
let limit = dummyCount / 2
let pureObjects = (0..<dummyCount).map({_ in Dummy1()})
let fetchRq = try! dummy1FetchRequest().cloneBuilder()
.with(fetchLimit: limit)
.build()
.fetchRequest(Dummy1.self)
// Different contexts.
let saveContext = manager.disposableObjectContext()
let fetchContext = manager.disposableObjectContext()
/// When
manager.rx.savePureObjects(saveContext, pureObjects)
.flatMap({_ in manager.rx.persistLocally()})
// We expect the number of results returned by this fetch to be
// limited to the predefined fetchLimit.
.flatMap({manager.rx.fetch(fetchContext, fetchRq)})
.map({$0.map({try! $0.asPureObject()})})
.subscribeOnConcurrent(qos: .background)
.flattenSequence()
.doOnDispose(expect.fulfill)
.subscribe(observer)
.disposed(by: disposeBag)
waitForExpectations(timeout: timeout, handler: nil)
/// Then
let nextElements = observer.nextElements()
XCTAssertEqual(nextElements.count, limit)
XCTAssertTrue(nextElements.all(pureObjects.contains))
}
}
public extension CoreDataManagerTest {
public func test_resetCDStack_shouldWork() {
/// Setup
let observer = scheduler.createObserver(Dummy1.self)
let expect = expectation(description: "Should have completed")
let manager = self.manager!
let dummyCount = self.dummyCount!
let pureObjects = (0..<dummyCount).map({_ in Dummy1()})
let fetchRq = try! dummy1FetchRequest().fetchRequest(Dummy1.self)
// Different contexts
let saveContext1 = manager.disposableObjectContext()
let saveContext2 = manager.disposableObjectContext()
let fetchContext1 = manager.disposableObjectContext()
let fetchContext2 = manager.disposableObjectContext()
let fetchContext3 = manager.disposableObjectContext()
/// When
// Save the pure objects once then check that they are in the DB.
manager.rx.savePureObjects(saveContext1, pureObjects)
.flatMap({manager.rx.persistLocally()})
.flatMap({manager.rx.fetch(fetchContext1, fetchRq)})
.doOnNext({XCTAssertEqual($0.count, dummyCount)})
// Reset the stack, then do another fetch to confirm DB is empty.
.flatMap({_ in manager.rx.resetStack()})
.flatMap({manager.rx.fetch(fetchContext2, fetchRq)})
.doOnNext({XCTAssertEqual($0.count, 0)})
// Save the pure objects again to ensure the DB is reset correctly.
.flatMap({_ in manager.rx.savePureObjects(saveContext2, pureObjects)})
.flatMap({manager.rx.persistLocally()})
.flatMap({manager.rx.fetch(fetchContext3, fetchRq)})
.map({$0.map({try! $0.asPureObject()})})
.subscribeOnConcurrent(qos: .background)
.flattenSequence()
.doOnDispose(expect.fulfill)
.subscribe(observer)
.disposed(by: disposeBag)
waitForExpectations(timeout: timeout, handler: nil)
/// Then
let nextElements = observer.nextElements()
XCTAssertEqual(nextElements.count, dummyCount)
XCTAssertTrue(pureObjects.all(nextElements.contains))
}
}
| apache-2.0 | 024907318b83ea9bb165b699718382db | 40.318618 | 104 | 0.607609 | 4.852795 | false | false | false | false |
mrazam110/MRSelectCountry | MRSelectCountry/MRSelectCountry/MRSelectCountryTableViewController.swift | 1 | 4509 | //
// MRSelectCountryTableViewController.swift
// MRSelectCountry
//
// Created by Muhammad Raza on 09/08/2017.
// Copyright © 2017 Muhammad Raza. All rights reserved.
//
import UIKit
public class MRSelectCountryTableViewController: UITableViewController, UISearchResultsUpdating, UISearchControllerDelegate {
// MARK :- IBOutlets
// MARK :- Properties
private(set) var countries: [MRCountry] = []
private var filteredCountries: [MRCountry] = []
public weak var delegate: MRSelectCountryDelegate? = nil
private let searchController = UISearchController(searchResultsController: nil)
// MARK: - UIViewController Lifecycle methods
public override func viewDidLoad() {
super.viewDidLoad()
// Get Countries
countries = MRSelectCountry.getCountries()
// Remove extra seperator lines
tableView.tableFooterView = UIView(frame: .zero)
// Setup Search controller
setupSearchController()
}
// MARK: - Supporting functions
private func setupSearchController() {
// Setup the Search Controller
searchController.searchResultsUpdater = self
searchController.searchBar.placeholder = "Search"
searchController.delegate = self
searchController.hidesNavigationBarDuringPresentation = true
searchController.obscuresBackgroundDuringPresentation = true
if #available(iOS 11.0, *) {
navigationItem.hidesSearchBarWhenScrolling = false
searchController.dimsBackgroundDuringPresentation = false // default is YES
navigationItem.searchController = searchController
} else {
// Fallback on earlier versions
tableView.tableHeaderView = searchController.searchBar
}
definesPresentationContext = true
}
// MARK: - IBActions
// MARK: - Table view data source
override public func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
if isFiltering() {
return filteredCountries.count
}
return countries.count
}
override public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! MRSelectCountryTableViewCell
// Configure the cell...
var country: MRCountry
if isFiltering() {
country = filteredCountries[indexPath.row]
}else{
country = countries[indexPath.row]
}
cell.countryNameLabel.text = country.name
cell.codeLabel.text = country.dialCode
cell.countryCodeLabel.text = country.code
cell.countryLocaleLabel.text = country.locale
return cell
}
override public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
var selectedCountry: MRCountry!
if isFiltering() {
selectedCountry = filteredCountries[indexPath.row]
}else{
selectedCountry = countries[indexPath.row]
}
self.delegate?.didSelectCountry(controller: self, country: selectedCountry)
}
// MARK: - UISearchController
public func updateSearchResults(for searchController: UISearchController) {
filterCountry(text: searchController.searchBar.text!)
}
private func filterCountry(text: String) {
filteredCountries = self.countries.filter({ (country) -> Bool in
return country.name.lowercased().contains(text.lowercased()) || country.code.lowercased().contains(text.lowercased()) || country.dialCode.lowercased().contains(text.lowercased())
})
tableView.reloadData()
}
private func searchBarIsEmpty() -> Bool {
return searchController.searchBar.text?.isEmpty ?? true
}
private func isFiltering() -> Bool {
let searchBarScopeIsFiltering = searchController.searchBar.selectedScopeButtonIndex != 0
return searchController.isActive && (!searchBarIsEmpty() || searchBarScopeIsFiltering)
}
}
| mit | 3f0f3911bc4bb5cb85b718b745c59628 | 33.676923 | 190 | 0.661491 | 5.885117 | false | false | false | false |
LunaGao/cnblogs-Mac-Swift | CNBlogsForMac/LGWebImage/LGWebImage.swift | 1 | 507 | //
// LGWebImage.swift
// CNBlogsForMac
//
// Created by Luna Gao on 15/12/1.
// Copyright © 2015年 gao.luna.com. All rights reserved.
//
import Cocoa
class LGWebImage: NSObject {
static func loadImageInImageView(imageView:NSImageView,url:String) {
let imageURL = NSURL(string:url)
let imageData = NSData(contentsOfURL:imageURL!)
if imageData != nil {
let newImage = NSImage.init(data:imageData!)
imageView.image = newImage
}
}
}
| mit | 13ce8b73f775adfeb1660db33efd3153 | 23 | 72 | 0.634921 | 3.847328 | false | false | false | false |
IamAlchemist/DemoAnimations | Animations/OpenDoor.swift | 2 | 3201 | //
// OpenDoor.swift
// DemoAnimations
//
// show interactive animation and auto animation with "tranform.rotate.y"
//
// Created by wizard lee on 7/16/16.
// Copyright © 2016 Alchemist. All rights reserved.
//
import UIKit
import SnapKit
class OpenDoorViewController: UIViewController {
let autoReveseAnim = "AutoReverseAnimation"
var container : UIView!
var doorLayer : CALayer!
var isAuto : Bool = false
var gesture : UIPanGestureRecognizer?
override func viewDidLoad() {
super.viewDidLoad()
let width:CGFloat = 128
let height:CGFloat = 256
container = UIView(frame: CGRect(x: 0, y: 0, width: width, height: height))
container.backgroundColor = UIColor.blueColor()
view.addSubview(container)
container.snp_makeConstraints { (make) in
make.width.equalTo(width)
make.height.equalTo(height)
make.centerX.equalTo(view)
make.centerY.equalTo(view)
}
doorLayer = CALayer()
doorLayer.frame = container.bounds
doorLayer.anchorPoint = CGPoint(x: 0, y: 0.5)
doorLayer.position = CGPoint(x: 0, y: 128)
doorLayer.contents = UIImage(named: "Door")?.CGImage
container.layer.addSublayer(doorLayer)
var perspective = CATransform3DIdentity
perspective.m34 = -1.0/500.0
container.layer.sublayerTransform = perspective
addAutoReverseAnimation()
isAuto = true
}
@IBAction func toggle(sender: UIButton) {
doorLayer.removeAllAnimations()
if !isAuto {
gesture = UIPanGestureRecognizer(target: self, action: #selector(panned(_:)))
doorLayer.speed = 0.0
let animation = CABasicAnimation()
animation.keyPath = "transform.rotation.y"
animation.toValue = NSNumber(double:-M_PI_2)
animation.duration = 1.0
doorLayer.addAnimation(animation, forKey: nil)
view.addGestureRecognizer(gesture!)
}
else {
doorLayer.speed = 1.0
if let gesture = gesture {
view.removeGestureRecognizer(gesture)
self.gesture = nil
}
addAutoReverseAnimation()
}
isAuto = !isAuto
}
func panned(gesture : UIPanGestureRecognizer) {
var x = gesture.translationInView(view).x
x /= 200
var timeOffset = doorLayer.timeOffset
timeOffset = min(0.999, max(0.0, timeOffset - Double(x)))
doorLayer.timeOffset = timeOffset
gesture.setTranslation(CGPointZero, inView: view)
}
private func addAutoReverseAnimation() {
let animation = CABasicAnimation()
animation.keyPath = "transform.rotation.y"
animation.toValue = NSNumber(double: -M_PI_2)
animation.duration = 2.0
animation.autoreverses = true
animation.repeatDuration = Double.infinity
doorLayer.addAnimation(animation, forKey: autoReveseAnim)
}
}
| mit | c602be8f644f3d9d5ddd5ad2fd802a60 | 29.47619 | 89 | 0.591563 | 4.783259 | false | false | false | false |
DestructHub/ProjectEuler | Problem045/Swift/solution_1.swift | 1 | 667 | import Foundation
var lastTriangleValue:Double = 285
var res:Double = 0
typealias Polynomial = (a:Double, c:Double)
let P:Polynomial = (a:3, c:2)
let H:Polynomial = (a:2, c:1)
let PH_bModule:Double = 1
while true
{
lastTriangleValue += 1
res = (pow(lastTriangleValue, 2) + lastTriangleValue) / 2
let Pn = (PH_bModule + sqrt(PH_bModule + 4 * P.a * (P.c * res))) / (2 * P.a)
let Hn = (PH_bModule + sqrt(PH_bModule + 4 * H.a * (H.c * res))) / (2 * H.a)
if floor(Pn) == Pn && floor(Hn) == Hn
{
break
}
}
#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
print(String(format: "%.0f", res))
#else
print(NSString(format: "%.0f", res))
#endif
| mit | 7323402096618be8854fe79c7ecf8621 | 21.233333 | 78 | 0.596702 | 2.507519 | false | false | false | false |
morizotter/SwiftHTTPStatusCodes | HTTPStatusCodes.swift | 1 | 4913 | //
// HTTPStatusCodes.swift
//
// Created by Richard Hodgkins on 11/01/2015.
// Copyright (c) 2015 Richard Hodgkins. All rights reserved.
//
import Foundation
/**
HTTP status codes as per http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
The RF2616 standard is completely covered (http://www.ietf.org/rfc/rfc2616.txt)
*/
public enum HTTPStatusCode : Int {
// Informational
case Continue = 100
case SwitchingProtocols = 101
case Processing = 102
// Success
case OK = 200
case Created = 201
case Accepted = 202
case NonAuthoritativeInformation = 203
case NoContent = 204
case ResetContent = 205
case PartialContent = 206
case MultiStatus = 207
case AlreadyReported = 208
case IMUsed = 226
// Redirections
case MultipleChoices = 300
case MovedPermanently = 301
case Found = 302
case SeeOther = 303
case NotModified = 304
case UseProxy = 305
case SwitchProxy = 306
case TemporaryRedirect = 307
case PermanentRedirect = 308
// Client Errors
case BadRequest = 400
case Unauthorized = 401
case PaymentRequired = 402
case Forbidden = 403
case NotFound = 404
case MethodNotAllowed = 405
case NotAcceptable = 406
case ProxyAuthenticationRequired = 407
case RequestTimeout = 408
case Conflict = 409
case Gone = 410
case LengthRequired = 411
case PreconditionFailed = 412
case RequestEntityTooLarge = 413
case RequestURITooLong = 414
case UnsupportedMediaType = 415
case RequestedRangeNotSatisfiable = 416
case ExpectationFailed = 417
case ImATeapot = 418
case AuthenticationTimeout = 419
case UnprocessableEntity = 422
case Locked = 423
case FailedDependency = 424
case UpgradeRequired = 426
case PreconditionRequired = 428
case TooManyRequests = 429
case RequestHeaderFieldsTooLarge = 431
case LoginTimeout = 440
case NoResponse = 444
case RetryWith = 449
case UnavailableForLegalReasons = 451
case RequestHeaderTooLarge = 494
case CertError = 495
case NoCert = 496
case HTTPToHTTPS = 497
case TokenExpired = 498
case ClientClosedRequest = 499
// Server Errors
case InternalServerError = 500
case NotImplemented = 501
case BadGateway = 502
case ServiceUnavailable = 503
case GatewayTimeout = 504
case HTTPVersionNotSupported = 505
case VariantAlsoNegotiates = 506
case InsufficientStorage = 507
case LoopDetected = 508
case BandwidthLimitExceeded = 509
case NotExtended = 510
case NetworkAuthenticationRequired = 511
case NetworkTimeoutError = 599
}
public extension HTTPStatusCode {
/// Informational - Request received, continuing process.
public var isInformational: Bool {
return inRange(100...200)
}
/// Success - The action was successfully received, understood, and accepted.
public var isSuccess: Bool {
return inRange(200...299)
}
/// Redirection - Further action must be taken in order to complete the request.
public var isRedirection: Bool {
return inRange(300...399)
}
/// Client Error - The request contains bad syntax or cannot be fulfilled.
public var isClientError: Bool {
return inRange(400...499)
}
/// Server Error - The server failed to fulfill an apparently valid request.
public var isServerError: Bool {
return inRange(500...599)
}
/// :returns: true if the status code is in the provided range, false otherwise.
private func inRange(range: Range<Int>) -> Bool {
return contains(range, rawValue)
}
}
public extension HTTPStatusCode {
public var localizedReasonPhrase: String {
return NSHTTPURLResponse.localizedStringForStatusCode(rawValue)
}
}
// MARK: - Printing
extension HTTPStatusCode: DebugPrintable, Printable {
public var description: String {
return "\(rawValue) - \(localizedReasonPhrase)"
}
public var debugDescription: String {
return "HTTPStatusCode:\(description)"
}
}
// MARK: - HTTP URL Response
public extension HTTPStatusCode {
/// Obtains a possible status code from an optional HTTP URL response.
public init?(HTTPResponse: NSHTTPURLResponse?) {
if let value = HTTPResponse?.statusCode {
self.init(rawValue: value)
} else {
return nil
}
}
}
public extension NSHTTPURLResponse {
public var statusCodeValue: HTTPStatusCode? {
return HTTPStatusCode(HTTPResponse: self)
}
@availability(iOS, introduced=7.0)
public convenience init?(URL url: NSURL, statusCode: HTTPStatusCode, HTTPVersion: String?, headerFields: [NSObject : AnyObject]?) {
self.init(URL: url, statusCode: statusCode.rawValue, HTTPVersion: HTTPVersion, headerFields: headerFields)
}
}
| mit | a2d2e8dfce6a6a6bdf860590a332bb8d | 28.596386 | 135 | 0.684307 | 4.793171 | false | false | false | false |
Teleglobal/MHQuickBlockLib | MHQuickBlockLib/Classes/ConferenceClientManager.swift | 1 | 28315 | //
// ConferenceClientManager.swift
// MHQuickBlockLib
//
// Created by Muhammad Adil on 20/09/2017.
//
import Quickblox
import QuickbloxWebRTC
import RealmSwift
extension QBRTCConnectionState {
func toString() -> String {
switch self {
case .unknown:
return "Unknown"
case .new:
return "New"
case .pending:
return "Pending"
case .connecting:
return "Connecting"
case .checking:
return "Checking"
case .disconnected:
return "Disconnected"
case .closed:
return "Closed"
case .disconnectTimeout:
return "Disconnect Timeout"
case .noAnswer:
return "No Answer"
case .rejected:
return "Rejected"
case .hangUp:
return "Hangup"
case .failed:
return "Failed"
case .connected:
return "Connected"
default:
return "Connected"
}
}
}
public enum CallStatus : Int {
case noAnswer = 0
case busy = 1
case rejected = 2
case accepted = 3
case ended = 4
}
public enum ConferenceCallErrors: Error {
case AlreadyInCallError
case AudioVideoCallPermissionError
}
public enum ConferenceCallMessage: String {
case ConferenceCallLeave = "ConferenceCallLeave1" // Leave/Hangup the call after accepting
case ConferenceCallInviteAccepted = "ConferenceCallInviteAccepted" // Call Receiver Accepted the Invite
case ConferenceCallInviteRejected = "ConferenceCallInviteRejected" // Call Receiver Rejected the Invite
case ConferenceCallSessionCreated = "ConferenceCallSessionCreated" // Call Receiver Rejected the Invite
// Only these 3 case are of concern when we receive system message
case ConferenceCallInvite = "ConferenceCallInvite" // Call Initializer Send Invitation
case ConferenceCallInviteCancel = "ConferenceCallLeave" // Call Initializer Cancel Invitation
case ConferenceCallSelfAccept = "ConferenceCallSelfAccept" // I have accepted the call, now if I am logged in on other device, I have to send this message
}
open class ConferenceClientManager : NSObject {
open var session: QBRTCConferenceSession?
open var dialogId: String = ""
open var incoming: Bool = false
fileprivate var videoFormat: QBRTCVideoFormat = QBRTCVideoFormat.init()
var cameraCapture: QBRTCCameraCapture?
// MARK:- Delegates Management
open var conferenceClientDelegates : [ConferenceClientDelegate] = []
/**
*
*
*/
open func addConferenceClientDelegate(_ conferenceClientDelegate: ConferenceClientDelegate) {
for i in 0..<conferenceClientDelegates.count {
let object: ConferenceClientDelegate = conferenceClientDelegates[i]
if (object === conferenceClientDelegate) {
return
}
}
conferenceClientDelegates.append(conferenceClientDelegate)
}
/**
*
*
*/
open func removeConferenceClientDelegate(_ conferenceClientDelegate: ConferenceClientDelegate) {
for i in 0..<conferenceClientDelegates.count {
let object: ConferenceClientDelegate = conferenceClientDelegates[i]
if (object === conferenceClientDelegate) {
conferenceClientDelegates.remove(at: i)
return
}
}
}
/**
*
*
*/
internal func removeAllConferenceClientDelegates() {
self.conferenceClientDelegates.removeAll()
}
// Public Methods
public func createConferenceCall(dialogId: String,
incoming: Bool = false,
conferenceType type: QBRTCConferenceType = .video,
completionBlock: @escaping (Error?) -> Void) {
if incoming {
self.incoming = true
}
if (self.session != nil) {
completionBlock(ConferenceCallErrors.AlreadyInCallError)
} else {
AVAudioSession.sharedInstance().requestRecordPermission { (granted) in
if (granted) {
AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo, completionHandler: { (allowed) in
if (allowed) {
self.dialogId = dialogId
self.session = QBRTCConferenceClient.instance().createSession(withChatDialogID: dialogId, conferenceType: type)
completionBlock(nil)
} else {
completionBlock(ConferenceCallErrors.AudioVideoCallPermissionError)
}
})
} else {
completionBlock(ConferenceCallErrors.AudioVideoCallPermissionError)
}
}
}
}
/**
*
*
*/
open func setViewCapture(_ videoCapture: QBRTCVideoCapture) {
self.session?.localMediaStream.videoTrack.videoCapture = videoCapture
}
/**
*
*
*/
open func getViewCapture() -> QBRTCVideoCapture? {
return self.session?.localMediaStream.videoTrack.videoCapture
}
/**
*
*
*/
open func getCameraCapture() -> QBRTCCameraCapture? {
return self.cameraCapture
}
/**
*
*
*/
open func enableMediaStream(_ value: Bool = true) {
self.session?.localMediaStream.videoTrack.isEnabled = value
}
/**
*
*
*/
open func getConferenceType() -> QBRTCConferenceType {
return self.session!.conferenceType
}
/**
*
*
*/
open func anySession() -> Bool {
return self.session != nil
}
/**
*
*
*/
open func connectionStateForUser(_ userID : NSNumber?) -> QBRTCConnectionState? {
return self.session?.connectionState(forUser: userID!)
}
/**
*
*
*/
open func remoteVideoTrackWithUserID(_ userID : NSNumber?) -> QBRTCVideoTrack? {
return self.session?.remoteVideoTrack(withUserID: userID!)
}
// MARK:- Accept/Reject Call Protocol Methods
public func acceptCall() {
//self.sendCallMessage(msgType: .ConferenceCallInviteAccepted)
self.createConferenceCall(dialogId: self.dialogId) { (error) in
// Hide calling view and show video view
if error == nil {
}
}
}
// MARK:- Send Call Accept/Reject Methods
public func dropCallInvitation() {
self.sendCallMessage(msgType: .ConferenceCallInviteCancel)
}
public func leaveCall() {
self.callCleanUp()
}
public func inviteToConferenceCall() {
self.sendCallMessage(msgType: .ConferenceCallInvite)
}
public func callCleanUp() {
self.dialogId = ""
self.session?.leave()
self.session = nil
self.cameraCapture = nil
}
open func sendCallSystemMessage(_ msgType: ConferenceCallMessage, _ occupant: UInt) {
let message: QBChatMessage = QBChatMessage()
let params = NSMutableDictionary()
params["notification_type"] = "ConferenceCall"
params["msg"] = msgType.rawValue
if let dialog = Messenger.dialogServiceManager.dialogInMemory(self.dialogId) {
if dialog.type == QBChatDialogType.group.rawValue {
params["username"] = dialog.name ?? "Group Call"
} else {
if let currentUser = Messenger.chatAuthServiceManager.currentUser() {
params["username"] = currentUser.fullName ?? ""
} else {
params["username"] = ""
}
}
}
if let session = self.session {
params["userId"] = session.currentUserID
} else {
params["userId"] = ""
}
params["dialogKey"] = self.dialogId
message.customParameters = params
message.recipientID = occupant
message.dialogID = self.dialogId
QBChat.instance.sendSystemMessage(message) { (error) in
if QBSettings.logLevel == .debug {
if error != nil {
print(error?.localizedDescription ?? "Message Send Failure")
}
}
}
}
public func sendCallMessage(msgType: ConferenceCallMessage) {
if let dialog = Messenger.dialogServiceManager.dialogInMemory(self.dialogId) {
for occupant in dialog.occupants() {
if NSNumber(value: occupant) != self.session?.currentUserID {
self.sendCallSystemMessage(msgType, occupant)
}
}
}
if msgType != .ConferenceCallInvite && msgType != .ConferenceCallInviteAccepted {
self.callCleanUp()
}
}
public func sendConferenceCallSelfAcceptMessage() {
if let id = Messenger.chatAuthServiceManager.currentUser()?.id {
self.sendCallSystemMessage(.ConferenceCallSelfAccept, id)
}
}
func sendPushToOpponentsAboutNewCall() {
let opponentsIDs = (self.session!.publishersList as NSArray).componentsJoined(by: ",")
let currentUserLogin = QBSession.current.currentUser!.login
QBRequest.sendPush(withText: "\(String(describing: currentUserLogin)) is calling you", toUsers: opponentsIDs, successBlock: { (response: QBResponse, event:[QBMEvent]?) in
print("Push sent!")
}) { (error:QBError?) in
print("Can not send push: \(String(describing: error))")
}
}
public func createCallLogMessage(callStatus: CallStatus, callTo: NSNumber!, duration: String?, dialogId: String) {
if (incoming == false) {
var duration_ = ""
if duration != nil {
duration_ = duration!
}
var callTo_ = ""
if (callTo != nil) {
callTo_ = "\(callTo.intValue)"
}
var callFrom_ = ""
if let callFrom = self.session?.currentUserID {
callFrom_ = "\(callFrom)"
}
var custParams : [String:String] = [
"call_status" : "\(callStatus.rawValue)",
"call_from" : callFrom_,
"call_to" : callTo_]
if duration_.count > 0 {
custParams["call_duration"] = duration_
}
Messenger.messageServiceManager.sendMessage("",
toDialog: dialogId,
params: custParams,
completionBlock: { (error: NSError?) in
})
}
}
// MARK:-
open func resetVideoFormat(with position: AVCaptureDevicePosition) {
self.videoFormat = QBRTCCameraCapture.formats(with: position).first!
if self.cameraCapture == nil {
self.cameraCapture = QBRTCCameraCapture.init(videoFormat: self.videoFormat,
position: position)
} else {
self.cameraCapture?.setVideoFormat(self.videoFormat,
for: position)
}
self.cameraCapture?.previewLayer.frame = CGRect.init(x: 0, y: 0, width: 115, height: 150)
self.cameraCapture?.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
if (self.cameraCapture?.isRunning)! == false {
self.cameraCapture!.startSession {
if let cameraView = self.cameraCapture {
self.setViewCapture(cameraView)
}
}
}
if self.cameraCapture!.hasCamera(for: position) {
self.cameraCapture!.position = position
}
}
// MARK: - During Call Opetations -
open func isVideoStreamEnabled() -> Bool{
return self.session!.localMediaStream.videoTrack.isEnabled
}
open func enableVideoStream(_ enabled: Bool = true) {
self.session!.localMediaStream.videoTrack.isEnabled = enabled
}
open func currentSoundRouter() -> QBRTCAudioDevice {
return QBRTCAudioSession.instance().currentAudioDevice
}
open func setSoundRouter(_ router: QBRTCAudioDevice) {
QBRTCAudioSession.instance().currentAudioDevice = router
}
open func enableAudioStream(_ enabled: Bool = true) {
self.session!.localMediaStream.audioTrack.isEnabled = enabled
}
open func isAudioStreamEnabled() -> Bool {
return self.session!.localMediaStream.audioTrack.isEnabled
}
}
extension ConferenceClientManager: QBRTCConferenceClientDelegate, QBRTCBaseClientDelegate {
// MARK:- QBRTCBaseClientDelegate
/**
* Called by timeout with updated stats report for user ID.
*
* @param session QBRTCSession instance
* @param report QBRTCStatsReport instance
* @param userID user ID
*
* @remark Configure time interval with [QBRTCConfig setStatsReportTimeInterval:timeInterval].
*/
public func session(_ session: QBRTCBaseSession, updatedStatsReport report: QBRTCStatsReport, forUserID userID: NSNumber) {
if self.session != nil && self.session == session {
for conferenceClient in self.conferenceClientDelegates {
conferenceClient.session(session, updatedStatsReport: report, forUserID: userID)
}
}
}
/**
* Called when session state has been changed.
*
* @param session QBRTCSession instance
* @param state session state
*
* @discussion Use this to track a session state. As SDK 2.3 introduced states for session, you can now manage your own states based on this.
*/
@objc(session:didChangeState:) public func session(_ session: QBRTCBaseSession, didChange state: QBRTCSessionState) {
if self.session != nil && self.session == session {
for conferenceClient in self.conferenceClientDelegates {
conferenceClient.session(session, didChangeState: state)
}
}
}
/**
* Called when received remote audio track from user.
*
* @param audioTrack QBRTCAudioTrack instance
* @param userID ID of user
*/
public func session(_ session: QBRTCBaseSession, receivedRemoteAudioTrack audioTrack: QBRTCAudioTrack, fromUser userID: NSNumber) {
if self.session != nil && self.session == session {
for conferenceClient in self.conferenceClientDelegates {
conferenceClient.session(session, receivedRemoteAudioTrack: audioTrack, fromUser: userID)
}
}
}
/**
* Called when received remote video track from user.
*
* @param videoTrack QBRTCVideoTrack instance
* @param userID ID of user
*/
public func session(_ session: QBRTCBaseSession, receivedRemoteVideoTrack videoTrack: QBRTCVideoTrack, fromUser userID: NSNumber) {
if self.session != nil && self.session == session {
for conferenceClient in self.conferenceClientDelegates {
conferenceClient.session(session, receivedRemoteVideoTrack: videoTrack, fromUser: userID)
}
}
}
/**
* Called when connection is closed for user.
*
* @param session QBRTCSession instance
* @param userID ID of user
*/
public func session(_ session: QBRTCBaseSession, connectionClosedForUser userID: NSNumber) {
if self.session != nil && self.session == session {
for conferenceClient in self.conferenceClientDelegates {
conferenceClient.session(session, connectionClosedForUser: userID)
}
}
}
/**
* Called when connection is initiated with user.
*
* @param session QBRTCSession instance
* @param userID ID of user
*/
public func session(_ session: QBRTCBaseSession, startedConnectingToUser userID: NSNumber) {
if self.session != nil && self.session == session {
for conferenceClient in self.conferenceClientDelegates {
conferenceClient.session(session, startedConnectingToUser: userID)
}
}
}
/**
* Called when connection is established with user.
*
* @param session QBRTCSession instance
* @param userID ID of user
*/
public func session(_ session: QBRTCBaseSession, connectedToUser userID: NSNumber) {
if self.session != nil && self.session == session {
for conferenceClient in self.conferenceClientDelegates {
conferenceClient.session(session, connectedToUser: userID)
}
}
}
/**
* Called when disconnected from user.
*
* @param session QBRTCSession instance
* @param userID ID of user
*/
public func session(_ session: QBRTCBaseSession, disconnectedFromUser userID: NSNumber) {
if self.session != nil && self.session == session {
for conferenceClient in self.conferenceClientDelegates {
conferenceClient.session(session, disconnectedFromUser: userID)
}
}
}
/**
* Called when connection failed with user.
*
* @param session QBRTCSession instance
* @param userID ID of user
*/
public func session(_ session: QBRTCBaseSession, connectionFailedForUser userID: NSNumber) {
if self.session != nil && self.session == session {
for conferenceClient in self.conferenceClientDelegates {
conferenceClient.session(session, connectionFailedForUser: userID)
}
}
}
/**
* Called when session connection state changed for a specific user.
*
* @param session QBRTCSession instance
* @param state state - @see QBRTCConnectionState
* @param userID ID of user
*/
public func session(_ session: QBRTCBaseSession, didChange state: QBRTCConnectionState, forUser userID: NSNumber) {
if self.session != nil && self.session == session {
for conferenceClient in self.conferenceClientDelegates {
conferenceClient.session(session, didChangeConnectionState: state, forUser: userID)
}
}
}
// MARK:- QBRTCConferenceClientDelegate
/**
* Called when session was created on server.
*
* @param session QBRTCConferenceSession instance
*
* @discussion When this method is called, session instance that was already created by QBRTCConferenceClient
* will be assigned valid session ID from server.
*
* @see QBRTCConferenceSession, QBRTCConferenceClient
*/
public func didCreateNewSession(_ session: QBRTCConferenceSession) {
if self.session == session {
if self.incoming == false {
self.inviteToConferenceCall()
} else {
self.sendConferenceCallSelfAcceptMessage()
}
let audioSession = QBRTCAudioSession.instance()
audioSession.initialize(configurationBlock: { (configuration) in
// adding blutetooth support
configuration.categoryOptions = configuration.categoryOptions.union(AVAudioSessionCategoryOptions.allowBluetooth)
if #available(iOS 10.0, *) {
configuration.categoryOptions = configuration.categoryOptions.union(AVAudioSessionCategoryOptions.allowBluetoothA2DP)
configuration.categoryOptions = configuration.categoryOptions.union(AVAudioSessionCategoryOptions.allowAirPlay)
}
if (session.conferenceType == .video) {
// setting mode to video chat to enable airplay audio and speaker only for video call
configuration.mode = AVAudioSessionModeVideoChat
}
})
self.session?.joinAsPublisher()
self.resetVideoFormat(with: .front)
for conferenceClient in self.conferenceClientDelegates {
conferenceClient.didCreateNewSession(session: session)
}
}
}
/**
* Called when join to session is performed and acknowledged by server.
*
* @param session QBRTCConferenceSession instance
* @param chatDialogID chat dialog ID
* @param publishersList array of user IDs, that are currently publishers
*
* @see QBRTCConferenceSession
*/
public func session(_ session: QBRTCConferenceSession, didJoinChatDialogWithID chatDialogID: String, publishersList: Array<NSNumber>) {
if self.session != nil && self.session == session {
for userId in publishersList {
self.session?.subscribeToUser(withID: userId)
}
for conferenceClient in self.conferenceClientDelegates {
conferenceClient.session(session, didJoinChatDialogWithID: chatDialogID, publishersList: publishersList)
}
}
}
/**
* Called when new publisher did join.
*
* @param session QBRTCConferenceSession instance
* @param userID new publisher user ID
*
* @see QBRTCConferenceSession
*/
public func session(_ session: QBRTCConferenceSession, didReceiveNewPublisherWithUserID userID: NSNumber) {
if self.session != nil && self.session == session {
self.session?.subscribeToUser(withID: userID)
for conferenceClient in self.conferenceClientDelegates {
conferenceClient.session(session, didReceiveNewPublisherWithUserID: userID)
}
}
}
/**
* Called when publisher did leave.
*
* @param session QBRTCConferenceSession instance
* @param userID publisher that left user ID
*
* @see QBRTCConferenceSession
*/
public func session(_ session: QBRTCConferenceSession, publisherDidLeaveWithUserID userId: NSNumber) {
if self.session != nil && self.session == session {
self.session?.unsubscribeFromUser(withID: userId)
for conferenceClient in self.conferenceClientDelegates {
conferenceClient.session(session, publisherDidLeaveWithUserID: userId)
}
}
}
/**
* Called when session did receive error from server.
*
* @param session QBRTCConferenceSession instance
* @param error received error from server
*
* @note Error doesn't necessarily means that session is closed. Can be just a minor error that can be fixed/ignored.
*
* @see QBRTCConferenceSession
*/
public func session(_ session: QBRTCConferenceSession, didReceiveError error: Error) {
if self.session != nil && self.session == session {
for conferenceClient in self.conferenceClientDelegates {
conferenceClient.session(session, didReceiveError: error)
}
}
}
/**
* Called when slowlink was received.
*
* @param session QBRTCConferenceSession instance
* @param uplink whether the issue is uplink or not
* @param nacks number of nacks
*
* @discussion this callback is triggered when serber reports trouble either sending or receiving media on the
* specified connection, typically as a consequence of too many NACKs received from/sent to the user in the last
* second: for instance, a slowLink with uplink=true means you notified several missing packets from server,
* while uplink=false means server is not receiving all your packets.
*
* @note useful to figure out when there are problems on the media path (e.g., excessive loss), in order to
* possibly react accordingly (e.g., decrease the bitrate if most of our packets are getting lost).
*
* @see QBRTCConferenceSession
*/
public func session(_ session: QBRTCConferenceSession, didReceiveSlowlinkWithUplink uplink: Bool, nacks: NSNumber) {
if self.session != nil && self.session == session {
for conferenceClient in self.conferenceClientDelegates {
conferenceClient.session(session, didReceiveSlowlinkWithUplink: uplink, nacks: nacks)
}
}
}
/**
* Called when media receiving state was changed on server.
*
* @param session QBRTCConferenceSession instance
* @param mediaType media type
* @param receiving whether media is receiving by server
*
* @see QBRTCConferenceSession, QBRTCConferenceMediaType
*/
public func session(_ session: QBRTCConferenceSession, didChangeMediaStateWith mediaType: QBRTCConferenceMediaType, receiving: Bool) {
if self.session != nil && self.session == session {
for conferenceClient in self.conferenceClientDelegates {
conferenceClient.session(session, didChangeMediaStateWithType: mediaType, receiving: receiving)
}
}
}
/**
* Session did initiate close request.
*
* @param session QBRTCConferenceSession instance
*
* @discussion 'sessionDidClose:withTimeout:' will be called after server will close session with callback
*
* @see QBRTCConferenceSession
*/
public func sessionWillClose(_ session: QBRTCConferenceSession) {
if self.session == session {
if QBRTCAudioSession.instance().isInitialized {
QBRTCAudioSession.instance().deinitialize()
}
self.callCleanUp()
for conferenceClient in self.conferenceClientDelegates {
conferenceClient.sessionWillClose(session)
}
}
}
/**
* Called when session was closed completely on server.
*
* @param session QBRTCConferenceSession instance
* @param timeout whether session was closed due to timeout on server
*
* @see QBRTCConferenceSession
*/
public func sessionDidClose(_ session: QBRTCConferenceSession, withTimeout timeout: Bool) {
if self.session == session {
self.callCleanUp()
}
for conferenceClient in self.conferenceClientDelegates {
conferenceClient.sessionDidClose(session, withTimeout: timeout)
}
}
}
| mit | e9590ac3bedee201cfdee08b6b914d83 | 32.078271 | 178 | 0.575984 | 5.258124 | false | false | false | false |
hilen/TimedSilver | Sources/UIKit/UIApplication+TSExtension.swift | 3 | 1915 | //
// UIApplication+TSExtension.swift
// TimedSilver
// Source: https://github.com/hilen/TimedSilver
//
// Created by Hilen on 8/10/16.
// Copyright © 2016 Hilen. All rights reserved.
//
import Foundation
import UIKit
extension UIApplication {
/// Avoid the error: [UIApplication sharedApplication] is unavailable in xxx extension
///
/// - returns: UIApplication?
public class func ts_sharedApplication() -> UIApplication? {
let selector = NSSelectorFromString("sharedApplication")
guard UIApplication.responds(to: selector) else { return nil }
return UIApplication.perform(selector).takeUnretainedValue() as? UIApplication
}
///Get screen orientation
public class var ts_screenOrientation: UIInterfaceOrientation? {
guard let app = self.ts_sharedApplication() else {
return nil
}
return app.statusBarOrientation
}
///Get status bar's height
@available(iOS 8.0, *)
public class var ts_screenStatusBarHeight: CGFloat {
guard let app = UIApplication.ts_sharedApplication() else {
return 0
}
return app.statusBarFrame.height
}
/**
Run a block in background after app resigns activity
- parameter closure: The closure
- parameter expirationHandler: The expiration handler
*/
public func ts_runIntoBackground(_ closure: @escaping () -> Void, expirationHandler: (() -> Void)? = nil) {
DispatchQueue.main.async {
let taskID: UIBackgroundTaskIdentifier
if let expirationHandler = expirationHandler {
taskID = self.beginBackgroundTask(expirationHandler: expirationHandler)
} else {
taskID = self.beginBackgroundTask(expirationHandler: { })
}
closure()
self.endBackgroundTask(taskID)
}
}
}
| mit | d2031721d2fe7a0150bac0f3ff26dbb7 | 30.9 | 111 | 0.640021 | 5.229508 | false | false | false | false |
wangyuanou/LZRequest | LZRequest/LZRequest.swift | 1 | 3184 | //
// LZRequest.swift
// LZRequest
//
// Created by 王渊鸥 on 2016/10/21.
// Copyright © 2016年 王渊鸥. All rights reserved.
//
import Foundation
public struct LZRequest {
var session:URLSession
var request:URLRequest
}
public extension LZRequest {
func array(_ response:@escaping ([Any]?)->Void) {
let url = request.url?.absoluteString ?? "[unknown]"
let body = request.httpBody?.string ?? "[empty]"
let header = request.allHTTPHeaderFields
self.session.dataTask(with: request) { [url, body, header] (data, resp, error) in
if let data = data {
print("\nRequest success [array]: \(String(describing: resp)), error: \(String(describing: error)), url: \(url)")
print("header---> ", header ?? "[empty]")
print("body---> ", body)
if let json = (try? JSONSerialization.jsonObject(with: data, options: .allowFragments) ) as? [Any] {
response(json)
} else {
print("Json array parser error: \(data)")
response(nil)
}
} else {
print("\nRequest error [array]: \(String(describing: resp)), error: \(String(describing: error)), url: \(url)")
print("header---> ", header ?? "[empty]")
print("body---> ", body)
response(nil)
}
}.resume()
}
func dictionary(_ response:@escaping ([AnyHashable:Any]?)->Void) {
print("req-->", request.url?.absoluteString ?? "[unknown]")
let url = request.url?.absoluteString ?? "[unknown]"
let body = request.httpBody?.string ?? "[empty]"
let header = request.allHTTPHeaderFields
self.session.dataTask(with: request) { [url, body, header] (data, resp, error) in
if let data = data {
print("\nRequest success [dict]: \(String(describing: resp)), error: \(String(describing: error)), url: \(url)")
print("header---> ", header ?? "[empty]")
print("body---> ", body)
if let json = (try? JSONSerialization.jsonObject(with: data, options: .allowFragments) ) as? [AnyHashable:Any] {
if let jsonData = try? JSONSerialization.data(withJSONObject: json, options: JSONSerialization.WritingOptions.prettyPrinted) {
print("json--->", jsonData.string ?? "[unknown]")
}
response(json)
} else {
print("Json array parser error: \(data)")
response(nil)
}
} else {
print("\nRequest error [dict]: \(String(describing: resp)), error: \(String(describing: error)), url: \(url)")
print("header---> ", header ?? "[empty]")
print("body---> ", body)
response(nil)
}
}.resume()
}
func string(_ response:@escaping (String?)->Void) {
self.session.dataTask(with: request) { (data, resp, error) in
if let data = data {
if let text = String(data: data, encoding: String.Encoding.utf8) {
response(text)
} else {
print("String parse error: \(data)")
response(nil)
}
} else {
print("Request error [string]: \(String(describing: resp))")
response(nil)
}
}.resume()
}
func data(_ response:@escaping (Data?)->Void) {
self.session.dataTask(with: request) { (data, resp, error) in
if let data = data {
response(data)
} else {
print("Request error [data]: \(String(describing: resp))")
response(nil)
}
}.resume()
}
}
| mit | fb1323842f8896dfdc4726cb274368ad | 31.670103 | 131 | 0.619438 | 3.493936 | false | false | false | false |
kosicki123/eidolon | Kiosk/App/Models/Artwork.swift | 1 | 3220 | import Foundation
import SwiftyJSON
public class Artwork: JSONAble {
public let id: String
public let dateString: String
public dynamic let title: String
public dynamic let titleAndDate: NSAttributedString
public dynamic let price: String
public dynamic let date: String
public dynamic var medium: String?
public dynamic var dimensions = [String]()
public dynamic var imageRights: String?
public dynamic var additionalInfo: String?
public dynamic var blurb: String?
public dynamic var artists: [Artist]?
public dynamic var culturalMarker: String?
public dynamic var images: [Image]?
init(id: String, dateString: String, title: String, titleAndDate: NSAttributedString, price: String, date: String) {
self.id = id
self.dateString = dateString
self.title = title
self.titleAndDate = titleAndDate
self.price = price
self.date = date
}
override public class func fromJSON(json: [String: AnyObject]) -> JSONAble {
let json = JSON(json)
let id = json["id"].stringValue
let title = json["title"].stringValue
let dateString = json["date"].stringValue
let price = json["price"].stringValue
let date = json["date"].stringValue
let titleAndDate = titleAndDateAttributedString(title, dateString)
let artwork = Artwork(id: id, dateString: dateString, title: title, titleAndDate:titleAndDate, price: price, date: date)
artwork.additionalInfo = json["additional_information"].string
artwork.medium = json["medium"].string
artwork.blurb = json["blurb"].string
if let artistDictionary = json["artist"].object as? [String: AnyObject] {
artwork.artists = [Artist.fromJSON(artistDictionary) as Artist]
}
if let imageDicts = json["images"].object as? Array<Dictionary<String, AnyObject>> {
artwork.images = imageDicts.map({ return Image.fromJSON($0) as Image })
}
if let dimensions = json["dimensions"].dictionary {
artwork.dimensions = ["in", "cm"].reduce([String](), combine: { (array, key) -> [String] in
if let dimension = dimensions[key]?.string {
return array + [dimension]
} else {
return array
}
})
}
return artwork
}
func sortableArtistID() -> String {
return artists?.first?.sortableID ?? "_"
}
}
private func titleAndDateAttributedString(title: String, dateString: String) -> NSAttributedString {
let workTitle = countElements(title) > 0 ? title : "Untitled"
let workFont = UIFont.serifItalicFontWithSize(16)
var attributedString = NSMutableAttributedString(string: workTitle, attributes: [NSFontAttributeName : workFont ])
if countElements(dateString) > 0 {
let dateFont = UIFont.serifFontWithSize(16)
let dateString = NSMutableAttributedString(string: ", " + dateString, attributes: [ NSFontAttributeName : dateFont ])
attributedString.appendAttributedString(dateString)
}
return attributedString.copy() as NSAttributedString
}
| mit | 2a559db04f0f87d2e6f3facb049b39b9 | 35.179775 | 128 | 0.651242 | 4.969136 | false | true | false | false |
dclelland/HOWL | Pods/ProtonomeAudioKitControls/Classes/Extensions/UIColor+Protonome.swift | 2 | 2313 | //
// UIColor+Protonome.swift
// HOWL
//
// Created by Daniel Clelland on 20/11/15.
// Copyright © 2015 Daniel Clelland. All rights reserved.
//
import UIKit
import Lerp
// MARK: - Color scheme
/// Color helpers used throughout the `ProtonomeAudioKitControls` module.
extension UIColor {
// MARK: - Colors
/// A low brightness color used for non highlighted audio control backgrounds.
public static func protonomeDark(hue: CGFloat, saturation: CGFloat = 1.0, brightness: CGFloat = 1.0) -> UIColor {
return UIColor(
hue: hue,
saturation: saturation.clamp(min: 0.0, max: 1.0).lerp(min: 0.0, max: 0.5),
brightness: brightness.clamp(min: 0.0, max: 1.0).lerp(min: 0.2, max: 0.5),
alpha: 1.0
)
}
/// A medium brightness color used for highlighted audio control backgrounds.
public static func protonomeMedium(hue: CGFloat, saturation: CGFloat = 1.0, brightness: CGFloat = 1.0) -> UIColor {
return UIColor(
hue: hue,
saturation: saturation.clamp(min: 0.0, max: 1.0).lerp(min: 0.0, max: 0.625),
brightness: brightness.clamp(min: 0.0, max: 1.0).lerp(min: 0.25, max: 0.75),
alpha: 1.0
)
}
/// A high brightness color used for audio control foregrounds.
public static func protonomeLight(hue: CGFloat, saturation: CGFloat = 1.0, brightness: CGFloat = 1.0) -> UIColor {
return UIColor(
hue: hue,
saturation: saturation.clamp(min: 0.0, max: 1.0).lerp(min: 0.0, max: 0.75),
brightness: brightness.clamp(min: 0.0, max: 1.0).lerp(min: 0.3, max: 1.0),
alpha: 1.0
)
}
// MARK: - Greyscale colors
/// A default black color.
public static let protonomeBlack = UIColor(white: 0.0, alpha: 1.0)
/// A default dark gray color.
public static let protonomeDarkGray = UIColor(white: 0.2, alpha: 1.0)
/// A default medium gray color.
public static let protonomeMediumGray = UIColor(white: 0.25, alpha: 1.0)
/// A default light gray color.
public static let protonomeLightGray = UIColor(white: 0.3, alpha: 1.0)
/// A default white color.
public static let protonomeWhite = UIColor(white: 1.0, alpha: 1.0)
}
| mit | 61470f6548a315dd49f7592af4382c33 | 34.030303 | 119 | 0.611592 | 3.573416 | false | false | false | false |
LockLight/Weibo_Demo | SinaWeibo/SinaWeibo/Classes/View/Compose(发布微博)/WBPicViewCell.swift | 1 | 2232 | //
// WBPicViewCell.swift
// SinaWeibo
//
// Created by locklight on 17/4/12.
// Copyright © 2017年 LockLight. All rights reserved.
//
import UIKit
protocol WBPicViewCellDelegate :NSObjectProtocol{
func addOrReplacePicView(cell:WBPicViewCell)
func deletePic(cell:WBPicViewCell)
}
class WBPicViewCell: UICollectionViewCell {
//代理属性
weak var delegate:WBPicViewCellDelegate?
//图片属性
var image:UIImage?{
didSet{
if let image = image {
addOrReplaceBtn.setBackgroundImage(image, for: .normal)
addOrReplaceBtn.setBackgroundImage(image, for: .highlighted)
}else{
addOrReplaceBtn.setBackgroundImage(UIImage(named:"compose_pic_add"), for: .normal)
addOrReplaceBtn.setBackgroundImage(UIImage(named:"compose_pic_add_highlighted"),for: .highlighted )
}
deleteBtn.isHidden = image == nil
}
}
//添加或替换图片的btn
lazy var addOrReplaceBtn:UIButton = UIButton(title: nil, bgImage: "compose_pic_add", target: self, action: #selector(addOrReplacePicView))
//删除图片的btn
lazy var deleteBtn:UIButton = UIButton(title: nil, bgImage: "compose_photo_close", target: self, action: #selector(deletePic))
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension WBPicViewCell{
func addOrReplacePicView(){
self.delegate?.addOrReplacePicView(cell: self)
}
func deletePic(){
self.delegate?.deletePic(cell: self)
}
}
extension WBPicViewCell{
func setupUI(){
addSubview(addOrReplaceBtn)
addSubview(deleteBtn)
addOrReplaceBtn.snp.makeConstraints { (make ) in
make.top.left.equalTo(self.contentView).offset(10)
make.right.bottom.equalTo(self.contentView).offset(-10)
}
deleteBtn.snp.makeConstraints { (make ) in
make.top.equalTo(self.contentView)
make.right.equalTo(self.snp.right).offset(-3)
}
}
}
| mit | 7fc1a01e30eb87ce34de7db0ebe342af | 26.3375 | 143 | 0.633288 | 4.157795 | false | false | false | false |
creatubbles/ctb-api-swift | CreatubblesAPIClientUnitTests/Spec/Hashtag/SuggestedHashtagsFetchRequestSpec.swift | 1 | 1867 | //
// SuggestedHashtagsFetchRequestSpec.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 Quick
import Nimble
@testable import CreatubblesAPIClient
class SuggestedHashtagsFetchRequestSpec: QuickSpec
{
override func spec()
{
describe("Suggested hashtags request")
{
it("Should have a proper method") {
let request = SuggestedHashtagsFetchRequest(page: 1, perPage: 10)
expect(request.method) == RequestMethod.get
}
it("Should have a proper endpoint") {
let request = SuggestedHashtagsFetchRequest(page: 1, perPage: 10)
expect(request.endpoint) == "hashtags/suggested"
}
}
}
}
| mit | 6c8a04d5d57008301da6d9275cc1b287 | 38.723404 | 81 | 0.695233 | 4.65586 | false | false | false | false |
marko628/Playground | String Stuff.playground/Contents.swift | 1 | 3216 | // String and Character Practice
import UIKit
import Foundation
var cashInt: Int
var cents: Int
var dollars: Int
var cashString: String = "$1.00"
var myString: String
myString = "show me the money"
// concatenating strings
myString + "! hello?"
myString += "! hello?"
// appending characters with append method
var c: Character = "!"
myString.append(c)
myString.append(Character("?"))
// appending characters with +=
myString += "!"
// count() to get string length
count(cashString)
count(myString)
// indexes of first and last characters
myString.startIndex
myString.endIndex
cashString.startIndex
cashString.endIndex
// looping through characters in a string
for c in myString {
println(c)
}
// String interpolation: \(<variable>)
dollars = 10
cents = 1
if cents < 10 {
cashString = "$\(dollars).0\(cents)"
} else {
cashString = "$\(dollars).\(cents)"
}
// Last n characters
var n = 2
let centRange = advance(cashString.endIndex, -n)..<cashString.endIndex
cashString[centRange]
cashString[centRange].toInt()
// Substring: characters (start + m) through (end - n)
var m = 1
n = 3
let dollarRange = advance(cashString.startIndex, m)..<advance(cashString.endIndex, -n)
cashString[dollarRange]
cashString[dollarRange].toInt()
func right(str: String, n: Int) -> String {
let range = advance(str.endIndex, -n)..<str.endIndex
return str[range]
}
right("hello", 3)
// check for non-numeric characters
func containsNonNumeric(str: String) -> Bool {
var numbers = NSCharacterSet.decimalDigitCharacterSet()
for c in str.utf16 {
println(c)
if !numbers.characterIsMember(c) {
return true
}
}
return false
}
containsNonNumeric("22")
containsNonNumeric("22a")
containsNonNumeric("22!")
containsNonNumeric("2")
func getDollarsAndCentsFromString(cashString: String) -> (Int, Int) {
var newCashString: String
if cashString.toInt() <= 9 {
newCashString = "$0.0\(cashString)"
} else {
newCashString = cashString
}
let centRange = advance(newCashString.endIndex, -2)..<newCashString.endIndex
let dollarRange = advance(newCashString.startIndex, 1)..<advance(newCashString.endIndex, -3)
var dollars: Int = 0
var cents: Int = 0
if let d = newCashString[dollarRange].toInt() {
dollars = d
}
if let c = newCashString[centRange].toInt() {
cents = c
}
return (dollars, cents)
}
func dollarsAndCentsToString(dollars: Int, cents: Int) -> String {
var cashString: String = "$0.00"
if cents < 10 {
cashString = "$\(dollars).0\(cents)"
} else {
cashString = "$\(dollars).\(cents)"
}
return cashString
}
var dol: Int
var cen: Int
(dol, cen) = getDollarsAndCentsFromString("$0.00")
dol
cen
dollarsAndCentsToString(dol, cen)
(dol, cen) = getDollarsAndCentsFromString("4")
func shift(amount: Float, digit: Int) -> Float {
return 0.00
}
1999 / 100
1999 % 100
19998 / 100
19998 % 100
var str = "1234"
let numbers = NSCharacterSet.decimalDigitCharacterSet()
var d = ""
for n in "$123.45" {
if let i = String(n).toInt() {
d += String(n)
}
}
d
| mit | c8a8c3cfd8423736ad265d9ba1d1b680 | 17.697674 | 96 | 0.653918 | 3.54185 | false | false | false | false |
noppoMan/swifty-libuv | Sources/SpawnWrap.swift | 1 | 6901 | //
// ProcessWrap.swift
// SwiftyLibuv
//
// Created by Yuki Takei on 6/12/16.
//
//
//
// Spawn.swift
// Suv
//
// Created by Yuki Takei on 1/23/16.
// Copyright © 2016 MikeTOKYO. All rights reserved.
//
#if os(Linux)
import Glibc
#else
import Darwin.C
#endif
import CLibUv
private func dict2ArrayWithEqualSeparator(_ dict: [String: String]) -> [String] {
var envs = [String]()
for (k,v) in dict {
envs.append("\(k)=\(v)")
}
return envs
}
internal let ENV_ARRAY = dict2ArrayWithEqualSeparator(CommandLine.env)
/**
Flags for stdio
here is original declaration
typedef enum {
UV_IGNORE = 0x00,
UV_CREATE_PIPE = 0x01,
UV_INHERIT_FD = 0x02,
UV_INHERIT_STREAM = 0x04,
UV_READABLE_PIPE = 0x10,
UV_WRITABLE_PIPE = 0x20
} uv_stdio_flags;
*/
public enum StdioFlags: Int32 {
case ignore = 0x00
case createPipe = 0x01
case inheritFd = 0x02
case inheritStream = 0x04
case readablePipe = 0x10
case writablePipe = 0x20
case createReadablePipe = 0x11 // UV_CREATE_PIPE | UV_READABLE_PIPE
case createWritablePipe = 0x21 // UV_CREATE_PIPE | UV_WRITABLE_PIPE
}
/**
Stdio option specifc type for spawn
*/
public class StdioOption {
public private(set) var flags: StdioFlags
/*
* fd should be return value of dup2 or raw value of STD*_FILENO
*
* r = uv_fs_open(NULL,
* &fs_req,
* "stdout_file",
* O_CREAT | O_RDWR,
* S_IRUSR | S_IWUSR,
* NULL)
*
* file = dup2(r, STDERR_FILENO)
*/
public private(set) var fd: Int32? = nil
public private(set) var pipe: PipeWrap? = nil
public init(flags: StdioFlags, fd: Int32? = nil, pipe: PipeWrap? = nil){
self.flags = flags
self.fd = fd
self.pipe = pipe
}
func getNativeFlags() -> uv_stdio_flags {
return unsafeBitCast(self.flags.rawValue, to: uv_stdio_flags.self)
}
}
/**
Option specifc type for spawn
*/
public struct SpawnOptions {
public var detached = false
public var env: [String: String] = [:]
public var stdio: [StdioOption] = []
public var cwd: String? = nil
public var silent = true
public init(loop: Loop = Loop.defaultLoop){
stdio = [
// stdin
StdioOption(flags: .createReadablePipe, pipe: PipeWrap(loop: loop)),
// stdout
StdioOption(flags: .createWritablePipe, pipe: PipeWrap(loop: loop)),
// stderr
StdioOption(flags: .createWritablePipe, pipe: PipeWrap(loop: loop))
]
}
}
private func exit_cb(req: UnsafeMutablePointer<uv_process_t>?, status: Int64, signal: Int32) {
guard let req = req else {
return
}
defer {
close_handle(req)
}
let context = Unmanaged<Proc>.fromOpaque(UnsafeMutableRawPointer(req.pointee.data)).takeRetainedValue()
context.onExitCallback(status)
}
public class SpawnWrap {
public enum SpawnWrapError: Error {
case pipeArgumentIsRequiredForFlags
case fdArgumentIsRequiredForFlags
}
let execPath: String
let execOptions: [String]
let loop: UnsafeMutablePointer<uv_loop_t>
var opts: SpawnOptions
public init(_ execPath: String, _ execOptions: [String] = [], loop: Loop = Loop.defaultLoop, options: SpawnOptions? = nil) {
self.loop = loop.loopPtr
self.execPath = execPath
self.execOptions = execOptions
self.opts = options == nil ? SpawnOptions(loop: loop) : options!
}
public func spawn() throws -> Proc {
// initialize process
let proc = Proc(stdio: opts.stdio)
let childReq = UnsafeMutablePointer<uv_process_t>.allocate(capacity: MemoryLayout<uv_process_t>.size)
let options = UnsafeMutablePointer<uv_process_options_t>.allocate(capacity: MemoryLayout<uv_process_options_t>.size)
memset(options, 0, MemoryLayout<uv_process_options_t>.size)
defer {
dealloc(options, capacity: opts.stdio.count)
}
if let cwd = opts.cwd {
options.pointee.cwd = cwd.buffer
}
var env = (ENV_ARRAY + dict2ArrayWithEqualSeparator(opts.env)).map{ UnsafeMutablePointer<Int8>(mutating: $0.buffer) }
env.append(nil)
options.pointee.env = UnsafeMutablePointer(mutating: env)
// stdio
options.pointee.stdio = UnsafeMutablePointer<uv_stdio_container_t>.allocate(capacity: opts.stdio.count)
options.pointee.stdio_count = Int32(opts.stdio.count)
for i in 0..<opts.stdio.count {
let op = opts.stdio[i]
options.pointee.stdio[i].flags = op.getNativeFlags()
switch(op.flags) {
// Ready for readableStream
case .createWritablePipe:
guard let stream = op.pipe else {
throw SpawnWrapError.pipeArgumentIsRequiredForFlags
}
options.pointee.stdio[i].data.stream = stream.streamPtr
// Ready for writableStream
case .createReadablePipe:
guard let stream = op.pipe else {
throw SpawnWrapError.pipeArgumentIsRequiredForFlags
}
options.pointee.stdio[i].data.stream = stream.streamPtr
case .inheritStream:
guard let stream = op.pipe else {
throw SpawnWrapError.pipeArgumentIsRequiredForFlags
}
options.pointee.stdio[i].data.stream = stream.streamPtr
case .inheritFd:
guard let fd = op.fd else {
throw SpawnWrapError.fdArgumentIsRequiredForFlags
}
options.pointee.stdio[i].data.fd = fd
default:
continue
}
}
var argv = ([execPath] + execOptions).map { UnsafeMutablePointer<Int8>(mutating: $0.buffer) }
argv.append(nil)
options.pointee.file = execPath.withCString { $0 }
options.pointee.args = UnsafeMutablePointer(mutating: argv)
if(opts.detached) {
options.pointee.exit_cb = nil
options.pointee.flags = UV_PROCESS_DETACHED.rawValue
} else {
options.pointee.exit_cb = exit_cb
}
let unmanaged = Unmanaged.passRetained(proc).toOpaque()
childReq.pointee.data = UnsafeMutableRawPointer(unmanaged)
let r = uv_spawn(loop, childReq, options)
if r < 0 {
close_handle(childReq)
throw UVError.rawUvError(code: r)
}
proc.pid = childReq.pointee.pid
return proc
}
}
| mit | f079233dbcdd64fdea73e217e89dc413 | 27.630705 | 128 | 0.582319 | 3.995368 | false | false | false | false |
AloneMonkey/RxSwiftStudy | RxSwiftTwoWayBinding/RxSwiftTwoWayBinding/Utils/Operators.swift | 1 | 3438 | //
// Operators.swift
// RxSwiftTwoWayBinding
//
// Created by monkey on 2017/3/30.
// Copyright © 2017年 Coder. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
// Two way binding operator between control property and variable, that's all it takes {
infix operator <-> : DefaultPrecedence
func nonMarkedText(_ textInput: UITextInput) -> String? {
let start = textInput.beginningOfDocument
let end = textInput.endOfDocument
guard let rangeAll = textInput.textRange(from: start, to: end),
let text = textInput.text(in: rangeAll) else {
return nil
}
guard let markedTextRange = textInput.markedTextRange else {
return text
}
guard let startRange = textInput.textRange(from: start, to: markedTextRange.start),
let endRange = textInput.textRange(from: markedTextRange.end, to: end) else {
return text
}
return (textInput.text(in: startRange) ?? "") + (textInput.text(in: endRange) ?? "")
}
func <-> <Base: UITextInput>(textInput: TextInput<Base>, variable: Variable<String>) -> Disposable {
let bindToUIDisposable = variable.asObservable()
.bindTo(textInput.text)
let bindToVariable = textInput.text
.subscribe(onNext: { [weak base = textInput.base] n in
guard let base = base else {
return
}
let nonMarkedTextValue = nonMarkedText(base)
/**
In some cases `textInput.textRangeFromPosition(start, toPosition: end)` will return nil even though the underlying
value is not nil. This appears to be an Apple bug. If it's not, and we are doing something wrong, please let us know.
The can be reproed easily if replace bottom code with
if nonMarkedTextValue != variable.value {
variable.value = nonMarkedTextValue ?? ""
}
and you hit "Done" button on keyboard.
*/
if let nonMarkedTextValue = nonMarkedTextValue, nonMarkedTextValue != variable.value {
variable.value = nonMarkedTextValue
}
}, onCompleted: {
bindToUIDisposable.dispose()
})
return Disposables.create(bindToUIDisposable, bindToVariable)
}
func <-> <T>(property: ControlProperty<T>, variable: Variable<T>) -> Disposable {
if T.self == String.self {
#if DEBUG
fatalError("It is ok to delete this message, but this is here to warn that you are maybe trying to bind to some `rx.text` property directly to variable.\n" +
"That will usually work ok, but for some languages that use IME, that simplistic method could cause unexpected issues because it will return intermediate results while text is being inputed.\n" +
"REMEDY: Just use `textField <-> variable` instead of `textField.rx.text <-> variable`.\n" +
"Find out more here: https://github.com/ReactiveX/RxSwift/issues/649\n"
)
#endif
}
let bindToUIDisposable = variable.asObservable()
.bindTo(property)
let bindToVariable = property
.subscribe(onNext: { n in
variable.value = n
}, onCompleted: {
bindToUIDisposable.dispose()
})
return Disposables.create(bindToUIDisposable, bindToVariable)
}
| mit | 21144d180d1a19b2ab1d1c719f1932f3 | 36.747253 | 211 | 0.624163 | 4.770833 | false | false | false | false |
mikaoj/BSImagePicker | Sources/Scene/Assets/AssetsViewController.swift | 1 | 11117 | // The MIT License (MIT)
//
// Copyright (c) 2019 Joakim Gyllström
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
import Photos
protocol AssetsViewControllerDelegate: class {
func assetsViewController(_ assetsViewController: AssetsViewController, didSelectAsset asset: PHAsset)
func assetsViewController(_ assetsViewController: AssetsViewController, didDeselectAsset asset: PHAsset)
func assetsViewController(_ assetsViewController: AssetsViewController, didLongPressCell cell: AssetCollectionViewCell, displayingAsset asset: PHAsset)
}
class AssetsViewController: UIViewController {
weak var delegate: AssetsViewControllerDelegate?
var settings: Settings! {
didSet { dataSource.settings = settings }
}
private let store: AssetStore
private let collectionView: UICollectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
private var fetchResult: PHFetchResult<PHAsset> = PHFetchResult<PHAsset>() {
didSet {
dataSource.fetchResult = fetchResult
}
}
private let dataSource: AssetsCollectionViewDataSource
private let selectionFeedback = UISelectionFeedbackGenerator()
init(store: AssetStore) {
self.store = store
dataSource = AssetsCollectionViewDataSource(fetchResult: fetchResult, store: store)
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
PHPhotoLibrary.shared().unregisterChangeObserver(self)
}
override func viewDidLoad() {
super.viewDidLoad()
PHPhotoLibrary.shared().register(self)
view = collectionView
// Set an empty title to get < back button
title = " "
collectionView.allowsMultipleSelection = true
collectionView.bounces = true
collectionView.alwaysBounceVertical = true
collectionView.backgroundColor = settings.theme.backgroundColor
collectionView.delegate = self
collectionView.dataSource = dataSource
collectionView.prefetchDataSource = dataSource
AssetsCollectionViewDataSource.registerCellIdentifiersForCollectionView(collectionView)
let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(AssetsViewController.collectionViewLongPressed(_:)))
longPressRecognizer.minimumPressDuration = 0.5
collectionView.addGestureRecognizer(longPressRecognizer)
syncSelections(store.assets)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
updateCollectionViewLayout(for: traitCollection)
}
func showAssets(in album: PHAssetCollection) {
fetchResult = PHAsset.fetchAssets(in: album, options: settings.fetch.assets.options)
collectionView.reloadData()
let selections = self.store.assets
syncSelections(selections)
collectionView.setContentOffset(.zero, animated: false)
}
private func syncSelections(_ assets: [PHAsset]) {
collectionView.allowsMultipleSelection = true
// Unselect all
for indexPath in collectionView.indexPathsForSelectedItems ?? [] {
collectionView.deselectItem(at: indexPath, animated: false)
}
// Sync selections
for asset in assets {
let index = fetchResult.index(of: asset)
guard index != NSNotFound else { continue }
let indexPath = IndexPath(item: index, section: 0)
collectionView.selectItem(at: indexPath, animated: false, scrollPosition: [])
updateSelectionIndexForCell(at: indexPath)
}
}
func unselect(asset: PHAsset) {
let index = fetchResult.index(of: asset)
guard index != NSNotFound else { return }
let indexPath = IndexPath(item: index, section: 0)
collectionView.deselectItem(at:indexPath, animated: false)
for indexPath in collectionView.indexPathsForSelectedItems ?? [] {
updateSelectionIndexForCell(at: indexPath)
}
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
updateCollectionViewLayout(for: traitCollection)
}
@objc func collectionViewLongPressed(_ sender: UILongPressGestureRecognizer) {
guard settings.preview.enabled else { return }
guard sender.state == .began else { return }
selectionFeedback.selectionChanged()
// Calculate which index path long press came from
let location = sender.location(in: collectionView)
guard let indexPath = collectionView.indexPathForItem(at: location) else { return }
guard let cell = collectionView.cellForItem(at: indexPath) as? AssetCollectionViewCell else { return }
let asset = fetchResult.object(at: indexPath.row)
delegate?.assetsViewController(self, didLongPressCell: cell, displayingAsset: asset)
}
private func updateCollectionViewLayout(for traitCollection: UITraitCollection) {
guard let collectionViewFlowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout else { return }
let itemSpacing = settings.list.spacing
let itemsPerRow = settings.list.cellsPerRow(traitCollection.verticalSizeClass, traitCollection.horizontalSizeClass)
let itemWidth = (collectionView.bounds.width - CGFloat(itemsPerRow - 1) * itemSpacing) / CGFloat(itemsPerRow)
let itemSize = CGSize(width: itemWidth, height: itemWidth)
collectionViewFlowLayout.minimumLineSpacing = itemSpacing
collectionViewFlowLayout.minimumInteritemSpacing = itemSpacing
collectionViewFlowLayout.itemSize = itemSize
dataSource.imageSize = itemSize.resize(by: UIScreen.main.scale)
}
private func updateSelectionIndexForCell(at indexPath: IndexPath) {
guard settings.theme.selectionStyle == .numbered else { return }
guard let cell = collectionView.cellForItem(at: indexPath) as? AssetCollectionViewCell else { return }
let asset = fetchResult.object(at: indexPath.row)
cell.selectionIndex = store.index(of: asset)
}
}
extension AssetsViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
selectionFeedback.selectionChanged()
let asset = fetchResult.object(at: indexPath.row)
store.append(asset)
delegate?.assetsViewController(self, didSelectAsset: asset)
updateSelectionIndexForCell(at: indexPath)
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
selectionFeedback.selectionChanged()
let asset = fetchResult.object(at: indexPath.row)
store.remove(asset)
delegate?.assetsViewController(self, didDeselectAsset: asset)
for indexPath in collectionView.indexPathsForSelectedItems ?? [] {
updateSelectionIndexForCell(at: indexPath)
}
}
func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
guard store.count < settings.selection.max || settings.selection.unselectOnReachingMax else { return false }
selectionFeedback.prepare()
return true
}
}
extension AssetsViewController: PHPhotoLibraryChangeObserver {
func photoLibraryDidChange(_ changeInstance: PHChange) {
guard let changes = changeInstance.changeDetails(for: fetchResult) else { return }
// Since we are gonna update UI, make sure we are on main
DispatchQueue.main.async {
if changes.hasIncrementalChanges {
self.collectionView.performBatchUpdates({
self.fetchResult = changes.fetchResultAfterChanges
// For indexes to make sense, updates must be in this order:
// delete, insert, move
if let removed = changes.removedIndexes, removed.count > 0 {
let removedItems = removed.map { IndexPath(item: $0, section:0) }
let removedSelections = self.collectionView.indexPathsForSelectedItems?.filter { return removedItems.contains($0) }
removedSelections?.forEach {
let removedAsset = changes.fetchResultBeforeChanges.object(at: $0.row)
self.store.remove(removedAsset)
self.delegate?.assetsViewController(self, didDeselectAsset: removedAsset)
}
self.collectionView.deleteItems(at: removedItems)
}
if let inserted = changes.insertedIndexes, inserted.count > 0 {
self.collectionView.insertItems(at: inserted.map { IndexPath(item: $0, section:0) })
}
changes.enumerateMoves { fromIndex, toIndex in
self.collectionView.moveItem(at: IndexPath(item: fromIndex, section: 0),
to: IndexPath(item: toIndex, section: 0))
}
})
// "Use these indices to reconfigure the corresponding cells after performBatchUpdates"
// https://developer.apple.com/documentation/photokit/phobjectchangedetails
if let changed = changes.changedIndexes, changed.count > 0 {
self.collectionView.reloadItems(at: changed.map { IndexPath(item: $0, section:0) })
}
} else {
self.fetchResult = changes.fetchResultAfterChanges
self.collectionView.reloadData()
}
// No matter if we have incremental changes or not, sync the selections
self.syncSelections(self.store.assets)
}
}
}
| mit | 3edf3f05b5156a7d4ba27e8cdffce4a6 | 43.64257 | 155 | 0.684599 | 5.688843 | false | false | false | false |
JGiola/swift-corelibs-foundation | Foundation/Set.swift | 3 | 3037 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
extension Set : _ObjectiveCBridgeable {
public typealias _ObjectType = NSSet
public func _bridgeToObjectiveC() -> _ObjectType {
let buffer = UnsafeMutablePointer<AnyObject>.allocate(capacity: count)
for (idx, obj) in enumerated() {
buffer.advanced(by: idx).initialize(to: obj as AnyObject)
}
let set = NSSet(objects: buffer, count: count)
buffer.deinitialize(count: count)
buffer.deallocate()
return set
}
public static func _forceBridgeFromObjectiveC(_ source: _ObjectType, result: inout Set?) {
result = _unconditionallyBridgeFromObjectiveC(source)
}
@discardableResult
public static func _conditionallyBridgeFromObjectiveC(_ source: _ObjectType, result: inout Set?) -> Bool {
var set = Set<Element>()
var failedConversion = false
if type(of: source) == NSSet.self || type(of: source) == NSMutableSet.self {
source.enumerateObjects(options: []) { obj, stop in
if let o = obj as? Element {
set.insert(o)
} else {
// here obj must be a swift type
if let nsObject = __SwiftValue.store(obj) as? Element {
set.insert(nsObject)
} else {
failedConversion = true
stop.pointee = true
}
}
}
} else if type(of: source) == _NSCFSet.self {
let cf = source._cfObject
let cnt = CFSetGetCount(cf)
let objs = UnsafeMutablePointer<UnsafeRawPointer?>.allocate(capacity: cnt)
CFSetGetValues(cf, objs)
for idx in 0..<cnt {
let obj = unsafeBitCast(objs.advanced(by: idx), to: AnyObject.self)
if let o = obj as? Element {
set.insert(o)
} else {
failedConversion = true
break
}
}
objs.deinitialize(count: cnt)
objs.deallocate()
}
if !failedConversion {
result = set
return true
}
return false
}
static public func _unconditionallyBridgeFromObjectiveC(_ source: _ObjectType?) -> Set {
if let object = source {
var value: Set<Element>?
_conditionallyBridgeFromObjectiveC(object, result: &value)
return value!
} else {
return Set<Element>()
}
}
}
| apache-2.0 | cc98d9b6dac47d475ed3cf95344657c6 | 33.511364 | 110 | 0.539019 | 5.236207 | false | false | false | false |
mirego/PinLayout | Example/PinLayoutSample/UI/Examples/Intro/IntroView.swift | 1 | 2922 | // Copyright (c) 2017 Luc Dion
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import PinLayout
class IntroView: UIView {
private let logo = UIImageView(image: UIImage(named: "PinLayout-logo"))
private let segmented = UISegmentedControl(items: ["Intro", "1", "2"])
private let textLabel = UILabel()
private let separatorView = UIView()
init() {
super.init(frame: .zero)
backgroundColor = .white
logo.contentMode = .scaleAspectFit
addSubview(logo)
segmented.selectedSegmentIndex = 0
segmented.tintColor = .pinLayoutColor
addSubview(segmented)
textLabel.text = "Swift manual views layouting without auto layout, no magic, pure code, full control. Concise syntax, readable & chainable.\n\nSwift manual views layouting without auto layout, no magic, pure code, full control. Concise syntax, readable & chainable."
textLabel.font = .systemFont(ofSize: 14)
textLabel.numberOfLines = 0
textLabel.lineBreakMode = .byWordWrapping
addSubview(textLabel)
separatorView.pin.height(1)
separatorView.backgroundColor = .pinLayoutColor
addSubview(separatorView)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func layoutSubviews() {
super.layoutSubviews()
let padding: CGFloat = 10
logo.pin.top(pin.safeArea).left(pin.safeArea).width(100).aspectRatio().margin(padding)
segmented.pin.after(of: logo, aligned: .top).right(pin.safeArea).marginHorizontal(padding)
textLabel.pin.below(of: segmented, aligned: .left).width(of: segmented).pinEdges().marginTop(10).sizeToFit(.width)
separatorView.pin.below(of: [logo, textLabel], aligned: .left).right(to: segmented.edge.right).marginTop(10)
}
}
| mit | 680f47875ec32c95f134b02159b61fd3 | 44.65625 | 275 | 0.703285 | 4.516229 | false | false | false | false |
mipstian/catch | Sources/App/PreferencesView.swift | 1 | 2559 | import AppKit
class PreferencesView: NSView {
@IBOutlet weak var toolBar: NSToolbar!
@IBOutlet weak var helpButton: NSButton!
@IBOutlet weak var acceptButton: NSButton!
@IBOutlet weak var importFromOPMLButton: NSButton!
@IBOutlet weak var exportToOPMLButton: NSButton!
@IBOutlet weak var onlyCheckBetweenCheckbox: NSButton!
@IBOutlet weak var andLabel: NSTextField!
@IBOutlet weak var saveToLabel: NSTextField!
@IBOutlet weak var organizeCheckbox: NSButton!
@IBOutlet weak var openAutomaticallyCheckbox: NSButton!
@IBOutlet weak var downloadScriptCheckbox: NSButton!
@IBOutlet weak var preventSleepCheckbox: NSButton!
@IBOutlet weak var checkForUpdatesCheckbox: NSButton!
@IBOutlet weak var openAtLoginButton: NSButton!
override func awakeFromNib() {
super.awakeFromNib()
for item in toolBar.items {
item.label = NSLocalizedString(item.itemIdentifier.rawValue, comment: "")
}
helpButton.title = NSLocalizedString("Help Me Configure Catch", comment: "")
acceptButton.title = NSLocalizedString("OK", comment: "")
importFromOPMLButton.title = NSLocalizedString("Import From OPML File…", comment: "")
exportToOPMLButton.title = NSLocalizedString("Export to OPML File…", comment: "")
onlyCheckBetweenCheckbox.title = NSLocalizedString("Only check feed between", comment: "")
andLabel.stringValue = NSLocalizedString("and", comment: "")
saveToLabel.stringValue = NSLocalizedString("Save to:", comment: "")
organizeCheckbox.title = NSLocalizedString("Organize in folders by show name", comment: "")
openAutomaticallyCheckbox.title = NSLocalizedString("Open automatically", comment: "")
downloadScriptCheckbox.title = NSLocalizedString("Download using script:", comment: "")
preventSleepCheckbox.title = NSLocalizedString("Prevent system sleep when active", comment: "")
checkForUpdatesCheckbox.title = NSLocalizedString("Automatically check for updates", comment: "")
openAtLoginButton.title = NSLocalizedString("Open at Login", comment: "")
if #available(OSX 11.0, *) {
let symbolsByIdentifier: [String:String] = [
"Feeds": "tray.2",
"Downloads": "square.and.arrow.down",
"Tweaks": "gearshape"
]
for item in toolBar.items {
if let symbolName = symbolsByIdentifier[item.itemIdentifier.rawValue] {
item.image = NSImage(
systemSymbolName: symbolName,
accessibilityDescription: nil
)
}
}
}
}
}
| mit | 2a024a9c81dfe46062bca74f7acfbfa3 | 39.555556 | 101 | 0.706067 | 4.932432 | false | false | false | false |
shu223/iOS8-Sampler | iOS8Sampler/Samples/TouchRadiusViewController.swift | 1 | 2207 | //
// TouchRadiusViewController.swift
// iOS8Sampler
//
// Created by Shuichi Tsutsumi on 2015/02/18.
// Copyright (c) 2015 Shuichi Tsutsumi. All rights reserved.
//
import UIKit
class TouchRadiusViewController: UIViewController {
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: "TouchRadiusViewController", bundle: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
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.
}
*/
// =========================================================================
// MARK: Private
fileprivate func createHaloAt(_ location: CGPoint, withRadius radius: CGFloat) {
let halo = PulsingHaloLayer()
halo.repeatCount = 1
halo.position = location
halo.radius = radius * 2.0
halo.fromValueForRadius = 0.5
halo.keyTimeForHalfOpacity = 0.7
halo.animationDuration = 0.8
self.view.layer.addSublayer(halo)
halo.start()
}
// =========================================================================
// MARK: Touch Handlers
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for obj: AnyObject in touches {
let touch = obj as! UITouch
let location = touch.location(in: self.view)
let radius = touch.majorRadius
self.createHaloAt(location, withRadius: radius)
}
}
}
| mit | a64e50651428ba7dd1a911b818e4fc15 | 28.039474 | 106 | 0.582691 | 5.108796 | false | false | false | false |
sotownsend/flok-apple | Pod/Classes/FlokDebugView.swift | 1 | 4408 | //If the user does not define any custom view, this view is used. It acts
//as a useful debugging aid by showing the name of the view and the names
//of spots as well as showing all the available spots
import UIKit
public class FlokDebugView: FlokView
{
//Maps spot names to autospot
var autoSpots = WeakValueDictionary<String, FlokSpot>()
var autoSpotConstraints = WeakValueDictionary<String, NSLayoutConstraint>()
lazy var nameLabel: UILabel! = UILabel()
//Returns an auto-created spot if there is no spot
public override func spotWithName(name: String) -> FlokSpot! {
//It was already created
if let autoSpot = autoSpots[name] {
return autoSpot
}
//No? Add it to our special list so we know to update constraints
let autoSpot = super.spotWithName(name)
autoSpots[name] = autoSpot
self.setNeedsLayout()
return autoSpot
}
public override func didLoad() {
self.backgroundColor = UIColor(red:0.094, green:0.094, blue:0.125, alpha: 1)
//Add 'view' nameLabel
self.addSubview(nameLabel)
nameLabel.text = self.name.snakeToClassCase
nameLabel.font = UIFont(name: "HelveticaNeue-Medium", size: 12)
nameLabel.textColor = UIColor(white: 1, alpha: 1)
nameLabel.textAlignment = .Left
nameLabel.translatesAutoresizingMaskIntoConstraints = false
let left = NSLayoutConstraint(item: nameLabel, attribute: .Left, relatedBy: .Equal, toItem: self, attribute: .Left, multiplier: 1, constant: 15)
let right = NSLayoutConstraint(item: nameLabel, attribute: .Right, relatedBy: .Equal, toItem: self, attribute: .Right, multiplier: 1, constant: 0)
let top = NSLayoutConstraint(item: nameLabel, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1, constant: 0)
let height = NSLayoutConstraint(item: nameLabel, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .Height, multiplier: 1, constant: 20)
self.addConstraints([left, right, top, height])
}
public override func updateConstraints() {
//Dump all the old constraints we added
for c in autoSpotConstraints.values { c.active = false }
autoSpotConstraints = WeakValueDictionary<String, NSLayoutConstraint>()
var lastTop: UIView = nameLabel
for (idx, spot) in autoSpots.values.enumerate() {
//All are attached to the left and right sides
let left = NSLayoutConstraint(item: spot, attribute: .Left, relatedBy: .Equal, toItem: self, attribute: .Left, multiplier: 1, constant: 0)
let right = NSLayoutConstraint(item: spot, attribute: .Right, relatedBy: .Equal, toItem: self, attribute: .Right, multiplier: 1, constant: 0)
//Attach it to the 'lastTop', if it's the first one, attach it to
//the very top of the superview
if idx == 0 {
let top = NSLayoutConstraint(item: spot, attribute: .Top, relatedBy: .Equal, toItem: lastTop, attribute: .Bottom, multiplier: 1, constant: 0)
self.addConstraints([left, right, top])
autoSpotConstraints[spot.name+".0"] = left
autoSpotConstraints[spot.name+".1"] = right
autoSpotConstraints[spot.name+".2"] = top
} else {
let top = NSLayoutConstraint(item: spot, attribute: .Height, relatedBy: .Equal, toItem: lastTop, attribute: .Height, multiplier: 1, constant: 0)
let height = NSLayoutConstraint(item: spot, attribute: .Top, relatedBy: .Equal, toItem: lastTop, attribute: .Bottom, multiplier: 1, constant: 0)
self.addConstraints([left, right, top, height])
autoSpotConstraints[spot.name+".0"] = left
autoSpotConstraints[spot.name+".1"] = right
autoSpotConstraints[spot.name+".2"] = top
autoSpotConstraints[spot.name+".3"] = height
}
lastTop = spot
}
//Last one should be attached to the bottom
let bottom = NSLayoutConstraint(item: lastTop, attribute: .Bottom, relatedBy: .Equal, toItem: self, attribute: .Bottom, multiplier: 1, constant: 0)
autoSpotConstraints["bottom"] = bottom
self.addConstraint(bottom)
super.updateConstraints()
}
}
| mit | 6212e3e7aab8dd83bf25049e451cb581 | 50.858824 | 160 | 0.645417 | 4.475127 | false | false | false | false |
diwu/LeetCode-Solutions-in-Swift | Solutions/Solutions/Medium/Medium_074_Search_A_2D_Matrix.swift | 1 | 1287 | /*
https://leetcode.com/problems/search-a-2d-matrix/
#74 Search a 2D Matrix
Level: medium
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.
For example,
Consider the following matrix:
[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
Given target = 3, return true.
Inspired by @vaputa at https://leetcode.com/discuss/10735/dont-treat-it-as-a-2d-matrix-just-treat-it-as-a-sorted-list
*/
import Foundation
struct Medium_074_Search_A_2D_Matrix {
static func searchMatrix(matrix: [[Int]], target: Int) -> Bool {
let m = matrix.count
guard m > 0 else { return false }
let n = matrix[0].count
guard n > 0 else { return false }
var lo = 0, hi = m * n - 1
while lo < hi {
let mid = (lo+hi)/2
let r = mid/n
let c = mid%n
let midV = matrix[r][c]
if target == midV { return true }
else if target < midV { hi = mid - 1 }
else { lo = mid + 1}
}
let r = lo/n, c = lo%n, midV = matrix[r][c]
return midV == target
}
}
| mit | 95a1798afd505e44da250055cf6a3e0b | 25.265306 | 117 | 0.589744 | 3.233668 | false | false | false | false |
nheagy/WordPress-iOS | WordPress/Classes/ViewRelated/Themes/ThemeBrowserCell.swift | 1 | 7933 | import Foundation
import WordPressShared.WPStyleGuide
/**
* @brief Actions provided in cell button triggered action sheet
*/
public enum ThemeAction
{
case Activate
case Customize
case Details
case Support
case TryCustomize
case View
static let actives = [Customize, Details, Support]
static let inactives = [TryCustomize, Activate, View, Details, Support]
var title: String {
switch self {
case .Activate:
return NSLocalizedString("Activate", comment: "Theme Activate action title")
case .Customize:
return NSLocalizedString("Customize", comment: "Theme Customize action title")
case .Details:
return NSLocalizedString("Details", comment: "Theme Details action title")
case .Support:
return NSLocalizedString("Support", comment: "Theme Support action title")
case .TryCustomize:
return NSLocalizedString("Try & Customize", comment: "Theme Try & Customize action title")
case .View:
return NSLocalizedString("View", comment: "Theme View action title")
}
}
func present(theme: Theme, _ presenter: ThemePresenter) {
switch self {
case .Activate:
presenter.activateTheme(theme)
case .Customize:
presenter.presentCustomizeForTheme(theme)
case .Details:
presenter.presentDetailsForTheme(theme)
case .Support:
presenter.presentSupportForTheme(theme)
case .TryCustomize:
presenter.presentPreviewForTheme(theme)
case .View:
presenter.presentViewForTheme(theme)
}
}
}
public class ThemeBrowserCell : UICollectionViewCell
{
// MARK: - Constants
public static let reuseIdentifier = "ThemeBrowserCell"
// MARK: - Private Aliases
private typealias Styles = WPStyleGuide.Themes
// MARK: - Outlets
@IBOutlet weak var imageView : UIImageView!
@IBOutlet weak var infoBar: UIView!
@IBOutlet weak var nameLabel : UILabel!
@IBOutlet weak var infoLabel: UILabel!
@IBOutlet weak var actionButton: UIButton!
@IBOutlet weak var highlightView: UIView!
@IBOutlet weak var activityView: UIActivityIndicatorView!
// MARK: - Properties
public var theme : Theme? {
didSet {
refreshGUI()
}
}
public weak var presenter: ThemePresenter?
private var placeholderImage = UIImage(named: "theme-loading")
private var activeEllipsisImage = UIImage(named: "icon-menu-ellipsis-white")
private var inactiveEllipsisImage = UIImage(named: "icon-menu-ellipsis")
// MARK: - GUI
override public var highlighted: Bool {
didSet {
let alphaFinal: CGFloat = highlighted ? 0.3 : 0
UIView.animateWithDuration(0.2) { [weak self] in
self?.highlightView.alpha = alphaFinal
}
}
}
override public func awakeFromNib() {
super.awakeFromNib()
actionButton.exclusiveTouch = true
layer.borderWidth = 1
infoBar.layer.borderWidth = 1
nameLabel.font = Styles.cellNameFont
infoLabel.font = Styles.cellInfoFont
actionButton.layer.borderWidth = 1
}
override public func prepareForReuse() {
super.prepareForReuse()
theme = nil
presenter = nil
}
private func refreshGUI() {
if let theme = theme {
if let imageUrl = theme.screenshotUrl where !imageUrl.isEmpty {
refreshScreenshotImage(imageUrl)
} else {
showPlaceholder()
}
nameLabel.text = theme.name
if theme.isCurrentTheme() {
backgroundColor = Styles.activeCellBackgroundColor
layer.borderColor = Styles.activeCellBorderColor.CGColor
infoBar.layer.borderColor = Styles.activeCellDividerColor.CGColor
actionButton.layer.borderColor = Styles.activeCellDividerColor.CGColor
actionButton.setImage(activeEllipsisImage, forState: .Normal)
nameLabel.textColor = Styles.activeCellNameColor
infoLabel.textColor = Styles.activeCellInfoColor
infoLabel.text = NSLocalizedString("ACTIVE", comment: "Label for active Theme browser cell")
} else {
backgroundColor = Styles.inactiveCellBackgroundColor
layer.borderColor = Styles.inactiveCellBorderColor.CGColor
infoBar.layer.borderColor = Styles.inactiveCellDividerColor.CGColor
actionButton.layer.borderColor = Styles.inactiveCellDividerColor.CGColor
actionButton.setImage(inactiveEllipsisImage, forState: .Normal)
nameLabel.textColor = Styles.inactiveCellNameColor
if theme.isPremium() {
infoLabel.textColor = Styles.inactiveCellPriceColor
infoLabel.text = theme.price
} else {
infoLabel.text = nil
}
}
} else {
imageView.image = nil
nameLabel.text = nil
infoLabel.text = nil
activityView.stopAnimating()
}
}
private func showPlaceholder() {
imageView.contentMode = .Center
imageView.backgroundColor = Styles.placeholderColor
imageView.image = placeholderImage
activityView.stopAnimating()
}
private func showScreenshot() {
imageView.contentMode = .ScaleAspectFit
imageView.backgroundColor = UIColor.clearColor()
activityView.stopAnimating()
}
private func refreshScreenshotImage(imageUrl: String) {
let imageUrlForWidth = imageUrl + "?w=\(presenter!.screenshotWidth)"
let screenshotUrl = NSURL(string: imageUrlForWidth)
imageView.backgroundColor = Styles.placeholderColor
activityView.startAnimating()
imageView.downloadImage(screenshotUrl,
placeholderImage: nil,
success: { [weak self] (image: UIImage) in
self?.showScreenshot()
}, failure: { [weak self] (error: NSError!) in
if error.domain == NSURLErrorDomain && error.code == NSURLErrorCancelled {
return
}
DDLogSwift.logError("Error loading theme screenshot: \(error.localizedDescription)")
self?.showPlaceholder()
})
}
// MARK: - Actions
@IBAction private func didTapActionButton(sender: UIButton) {
guard let theme = theme, presenter = presenter else {
return
}
let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
let themeActions = theme.isCurrentTheme() ? ThemeAction.actives : ThemeAction.inactives
themeActions.forEach { themeAction in
alertController.addActionWithTitle(themeAction.title,
style: .Default,
handler: { (action: UIAlertAction) in
themeAction.present(theme, presenter)
})
}
alertController.modalPresentationStyle = .Popover
if let popover = alertController.popoverPresentationController {
popover.sourceView = actionButton
popover.sourceRect = actionButton.bounds
popover.permittedArrowDirections = .Any
popover.canOverlapSourceViewRect = true
} else {
let cancelTitle = NSLocalizedString("Cancel", comment: "Cancel action title")
alertController.addCancelActionWithTitle(cancelTitle, handler: nil)
}
alertController.presentFromRootViewController()
}
}
| gpl-2.0 | d5144d466819ae83bcd36003ef2b67c0 | 34.895928 | 108 | 0.617169 | 5.642248 | false | false | false | false |
Miridescen/M_365key | 365KEY_swift/365KEY_swift/MainController/Class/UserCenter/controller/SKMyMessageController.swift | 1 | 6201 | //
// SKMyMessageController.swift
// 365KEY_swift
//
// Created by 牟松 on 2016/12/1.
// Copyright © 2016年 DoNews. All rights reserved.
//
import UIKit
class SKMyMessageController: UIViewController {
var navBar: UINavigationBar?
var navItem: UINavigationItem?
var dataArray: [SKMyMessageModel]?
var rowHeightArray: [CGFloat]?
var bgView: UIView?
lazy var takeCommentsView = SKTakeCommentView(frame: CGRect(x: 0, y: SKScreenHeight-50, width: SKScreenWidth, height: 50))
lazy var NoinfoView = SKNoInfoView(frame: CGRect(x: 0, y: 0, width: SKScreenWidth, height: SKScreenHeight-64))
lazy var myMessageTV = SKMyMessageTV(frame: CGRect(x: 0, y: 0, width: SKScreenWidth, height: SKScreenHeight-64), style: UITableViewStyle.init(rawValue: 0)!)
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: .UIKeyboardWillHide, object: nil)
addSubView()
loadData()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
func loadData() {
NSURLConnection.connection.userCenterMyMessageRequest { (bool, dataArray) in
if bool {
self.dataArray = dataArray
self.myMessageTV.dataSourceArray = dataArray!
self.myMessageTV.rowHeightArray = self.rowHeightArrayWith(modelArray: dataArray!)!
self.myMessageTV.reloadData()
self.bgView?.addSubview(self.myMessageTV)
} else {
self.bgView?.insertSubview(self.NoinfoView, at: (self.bgView?.subviews.count)!)
}
}
}
@objc private func keyboardWillShow(notifiction: Notification) {
let animationDuration = notifiction.userInfo?[AnyHashable("UIKeyboardAnimationDurationUserInfoKey")]
let animationCurve = notifiction.userInfo?[AnyHashable("UIKeyboardAnimationCurveUserInfoKey")]
let keyboardRect: CGRect = notifiction.userInfo?[AnyHashable("UIKeyboardFrameEndUserInfoKey")] as! CGRect
let keyBoardHeight = keyboardRect.height
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationBeginsFromCurrentState(true)
UIView.setAnimationDuration(animationDuration as! TimeInterval)
UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: animationCurve as! Int)!)
takeCommentsView.frame = CGRect(x: 0, y: SKScreenHeight-50-keyBoardHeight, width: SKScreenWidth, height: 50)
UIView.commitAnimations()
}
@objc private func keyboardWillHide(notifiction: Notification) {
let animationDuration = notifiction.userInfo?[AnyHashable("UIKeyboardAnimationDurationUserInfoKey")]
let animationCurve = notifiction.userInfo?[AnyHashable("UIKeyboardAnimationCurveUserInfoKey")]
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationBeginsFromCurrentState(true)
UIView.setAnimationDuration(animationDuration as! TimeInterval)
UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: animationCurve as! Int)!)
takeCommentsView.frame = CGRect(x: 0, y: SKScreenHeight-50, width: SKScreenWidth, height: 50)
UIView.commitAnimations()
takeCommentsView.removeFromSuperview()
}
}
extension SKMyMessageController{
func addSubView() {
navBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: SKScreenWidth, height: 64))
navBar?.isTranslucent = false
navBar?.barTintColor = UIColor().mainColor
navBar?.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
view.addSubview(navBar!)
navItem = UINavigationItem()
navItem?.leftBarButtonItem = UIBarButtonItem(SK_barButtonItem: UIImage(named:"icon_back"), selectorImage: UIImage(named:"icon_back"), tragtic: self, action: #selector(backBtnDidClick))
navItem?.title = "我的留言"
navBar?.items = [navItem!]
bgView = UIView(frame: CGRect(x: 0, y: 64, width: SKScreenWidth, height: SKScreenHeight-64))
view.addSubview(bgView!)
}
@objc private func backBtnDidClick(){
_ = navigationController?.popViewController(animated: true)
}
func rowHeightArrayWith(modelArray: [SKMyMessageModel]) -> [CGFloat]? {
if (dataArray?.count)! > 0 {
var heightArray = [CGFloat]()
for mesageModel in modelArray {
var messageHeight = SKLabelSizeWith(labelText: mesageModel.message!, font: UIFont.systemFont(ofSize: 16), width: SKScreenWidth-78).height
if mesageModel.childcount == 0 {
messageHeight += 104
messageHeight += 10
heightArray.append(messageHeight)
messageHeight = 0
} else {
var subCommentsHeight: CGFloat = 0
for childModel in mesageModel.childcommit! {
let childCommentsHeight = SKLabelSizeWith(labelText: (childModel as! SKMyMessageModel).message!, font: UIFont.systemFont(ofSize: 16), width: SKScreenWidth-78).height
subCommentsHeight += childCommentsHeight
}
subCommentsHeight += messageHeight
subCommentsHeight += 10
subCommentsHeight += CGFloat(mesageModel.childcount*10)
subCommentsHeight += 104
heightArray.append(subCommentsHeight)
subCommentsHeight = 0
messageHeight = 0
}
}
return heightArray
} else {
return nil
}
}
}
| apache-2.0 | 9d83628f4b2da65b851caf52386c8632 | 39.168831 | 192 | 0.625606 | 5.407343 | false | false | false | false |
stephentyrone/swift | validation-test/Reflection/reflect_Enum_NoCase.swift | 3 | 9503 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift -g -lswiftSwiftReflectionTest %s -o %t/reflect_Enum_NoCase
// RUN: %target-codesign %t/reflect_Enum_NoCase
// RUN: %target-run %target-swift-reflection-test %t/reflect_Enum_NoCase | %FileCheck %s --check-prefix=CHECK-%target-ptrsize
// REQUIRES: objc_interop
// REQUIRES: executable_test
// UNSUPPORTED: use_os_stdlib
import SwiftReflectionTest
enum NoCaseEnum {
}
class ClassWithNoCaseEnum {
var e1: NoCaseEnum?
var e2: NoCaseEnum??
var e3: NoCaseEnum???
var e4: NoCaseEnum????
var e5: NoCaseEnum?????
}
reflect(object: ClassWithNoCaseEnum())
// CHECK-64: Reflecting an object.
// CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-64: Type reference:
// CHECK-64: (class reflect_Enum_NoCase.ClassWithNoCaseEnum)
// CHECK-64: Type info:
// CHECK-64: (class_instance size=31 alignment=1 stride=31 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (field name=e1 offset=16
// CHECK-64: (single_payload_enum size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (case name=some index=0 offset=0
// CHECK-64: (no_payload_enum size=0 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1))
// CHECK-64: (case name=none index=1)))
// CHECK-64: (field name=e2 offset=17
// CHECK-64: (single_payload_enum size=2 alignment=1 stride=2 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (case name=some index=0 offset=0
// CHECK-64: (single_payload_enum size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (case name=some index=0 offset=0
// CHECK-64: (no_payload_enum size=0 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1))
// CHECK-64: (case name=none index=1)))
// CHECK-64: (case name=none index=1)))
// CHECK-64: (field name=e3 offset=19
// CHECK-64: (single_payload_enum size=3 alignment=1 stride=3 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (case name=some index=0 offset=0
// CHECK-64: (single_payload_enum size=2 alignment=1 stride=2 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (case name=some index=0 offset=0
// CHECK-64: (single_payload_enum size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (case name=some index=0 offset=0
// CHECK-64: (no_payload_enum size=0 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1))
// CHECK-64: (case name=none index=1)))
// CHECK-64: (case name=none index=1)))
// CHECK-64: (case name=none index=1)))
// CHECK-64: (field name=e4 offset=22
// CHECK-64: (single_payload_enum size=4 alignment=1 stride=4 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (case name=some index=0 offset=0
// CHECK-64: (single_payload_enum size=3 alignment=1 stride=3 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (case name=some index=0 offset=0
// CHECK-64: (single_payload_enum size=2 alignment=1 stride=2 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (case name=some index=0 offset=0
// CHECK-64: (single_payload_enum size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (case name=some index=0 offset=0
// CHECK-64: (no_payload_enum size=0 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1))
// CHECK-64: (case name=none index=1)))
// CHECK-64: (case name=none index=1)))
// CHECK-64: (case name=none index=1)))
// CHECK-64: (case name=none index=1)))
// CHECK-64: (field name=e5 offset=26
// CHECK-64: (single_payload_enum size=5 alignment=1 stride=5 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (case name=some index=0 offset=0
// CHECK-64: (single_payload_enum size=4 alignment=1 stride=4 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (case name=some index=0 offset=0
// CHECK-64: (single_payload_enum size=3 alignment=1 stride=3 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (case name=some index=0 offset=0
// CHECK-64: (single_payload_enum size=2 alignment=1 stride=2 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (case name=some index=0 offset=0
// CHECK-64: (single_payload_enum size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (case name=some index=0 offset=0
// CHECK-64: (no_payload_enum size=0 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1))
// CHECK-64: (case name=none index=1)))
// CHECK-64: (case name=none index=1)))
// CHECK-64: (case name=none index=1)))
// CHECK-64: (case name=none index=1)))
// CHECK-64: (case name=none index=1))))
// CHECK-32: Reflecting an object.
// CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-32: Type reference:
// CHECK-32: (class reflect_Enum_NoCase.ClassWithNoCaseEnum)
// CHECK-32: Type info:
// CHECK-32: (class_instance size=23 alignment=1 stride=23 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (field name=e1 offset=8
// CHECK-32: (single_payload_enum size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (case name=some index=0 offset=0
// CHECK-32: (no_payload_enum size=0 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1))
// CHECK-32: (case name=none index=1)))
// CHECK-32: (field name=e2 offset=9
// CHECK-32: (single_payload_enum size=2 alignment=1 stride=2 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (case name=some index=0 offset=0
// CHECK-32: (single_payload_enum size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (case name=some index=0 offset=0
// CHECK-32: (no_payload_enum size=0 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1))
// CHECK-32: (case name=none index=1)))
// CHECK-32: (case name=none index=1)))
// CHECK-32: (field name=e3 offset=11
// CHECK-32: (single_payload_enum size=3 alignment=1 stride=3 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (case name=some index=0 offset=0
// CHECK-32: (single_payload_enum size=2 alignment=1 stride=2 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (case name=some index=0 offset=0
// CHECK-32: (single_payload_enum size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (case name=some index=0 offset=0
// CHECK-32: (no_payload_enum size=0 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1))
// CHECK-32: (case name=none index=1)))
// CHECK-32: (case name=none index=1)))
// CHECK-32: (case name=none index=1)))
// CHECK-32: (field name=e4 offset=14
// CHECK-32: (single_payload_enum size=4 alignment=1 stride=4 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (case name=some index=0 offset=0
// CHECK-32: (single_payload_enum size=3 alignment=1 stride=3 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (case name=some index=0 offset=0
// CHECK-32: (single_payload_enum size=2 alignment=1 stride=2 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (case name=some index=0 offset=0
// CHECK-32: (single_payload_enum size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (case name=some index=0 offset=0
// CHECK-32: (no_payload_enum size=0 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1))
// CHECK-32: (case name=none index=1)))
// CHECK-32: (case name=none index=1)))
// CHECK-32: (case name=none index=1)))
// CHECK-32: (case name=none index=1)))
// CHECK-32: (field name=e5 offset=18
// CHECK-32: (single_payload_enum size=5 alignment=1 stride=5 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (case name=some index=0 offset=0
// CHECK-32: (single_payload_enum size=4 alignment=1 stride=4 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (case name=some index=0 offset=0
// CHECK-32: (single_payload_enum size=3 alignment=1 stride=3 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (case name=some index=0 offset=0
// CHECK-32: (single_payload_enum size=2 alignment=1 stride=2 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (case name=some index=0 offset=0
// CHECK-32: (single_payload_enum size=1 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (case name=some index=0 offset=0
// CHECK-32: (no_payload_enum size=0 alignment=1 stride=1 num_extra_inhabitants=0 bitwise_takable=1))
// CHECK-32: (case name=none index=1)))
// CHECK-32: (case name=none index=1)))
// CHECK-32: (case name=none index=1)))
// CHECK-32: (case name=none index=1))))
doneReflecting()
// CHECK-64: Done.
// CHECK-32: Done.
| apache-2.0 | 373e966262209db8b3a7f08d6044b12a | 60.309677 | 125 | 0.641482 | 3.201819 | false | false | false | false |
22377832/ccyswift | GCDDemo/GCDDemo/ViewController.swift | 1 | 3189 | //
// ViewController.swift
// GCDDemo
//
// Created by sks on 17/2/20.
// Copyright © 2017年 chen. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
func print1to1000() {
for number in 0...1000{
// print(number)
// print(Thread.current)
}
}
override func viewDidLoad() {
super.viewDidLoad()
DispatchQueue.global().sync {
[weak self] in
self?.print1to1000()
}
DispatchQueue.global().sync {
[weak self] in
self?.print1to1000()
}
// DispatchQueue.main.async {
// [weak self] in
// print(Thread.current)
// print(Thread.main)
// print(Thread.isMainThread)
// let controller = UIAlertController(title: "GCD", message: "GCD is amazing!", preferredStyle:.alert)
// controller.addAction(UIAlertAction(title: "OK", style: .default){ (action) in
// print(action)
// })
// self?.present(controller, animated: true, completion: nil)
// DispatchQueue.global().async {
// Thread.sleep(forTimeInterval: 4)
// DispatchQueue.main.async {
// [weak self] in
// self?.dismiss(animated: true, completion: nil)
//
// }
// }
//
// }
// Do any additional setup after loading the view, typically from a nib.
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let queue = DispatchQueue.global()
queue.async {
[weak self] in
var image: UIImage?
queue.sync {
//下载图片
let urlString = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1488174014&di=d631cff7d387c14a9e16f1acfba9c396&imgtype=jpg&er=1&src=http%3A%2F%2Fimage98.360doc.com%2FDownloadImg%2F2016%2F08%2F0522%2F77304096_1.jpg"
let url = URL(string: urlString)!
//
// let path = Bundle.main.path(forResource: "timg-1", ofType: "jpeg")
// let url = URL(fileURLWithPath: path!, relativeTo: nil)
do {
let data = try Data(contentsOf: url, options: .mappedIfSafe)
image = UIImage(data: data)
} catch{
print(error)
print(error.localizedDescription)
}
}
DispatchQueue.main.sync {
//设置图片
if let theImage = image{
let imageView = UIImageView(frame: self!.view.bounds)
imageView.contentMode = .scaleAspectFill
imageView.image = theImage
self?.view.addSubview(imageView)
}
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | f36ee9d25c821a7b4787acf743bb5112 | 29.480769 | 251 | 0.507256 | 4.439776 | false | false | false | false |
downie/swift-daily-programmer | SwiftDailyChallenge.playground/Pages/261 - Easy - Verify Magic Squares.xcplaygroundpage/Contents.swift | 1 | 7493 | /*:
# [2016-04-04] Challenge #261 [Easy] verifying 3x3 magic squares
Published on: 2016-04-04\
Difficulty: Easy\
[reddit link](https://www.reddit.com/r/dailyprogrammer/comments/4dccix/20160404_challenge_261_easy_verifying_3x3_magic/)
*/
import Foundation
struct MagicSquare {
let size : Int
let linearContents : [Int?]
let twoDimensionalContents : [[Int?]]
var targetSum : Int {
return size * (size * size + 1) / 2
}
}
// Not really needed to solve the problem, but I wanted to play with ArrayLiteralConvertable
extension MagicSquare : ArrayLiteralConvertible {
typealias Element = Int
init(arrayLiteral elements: Int...) {
self.init(withArray: elements)
}
init(withArray elements : [Int]) {
#if swift(>=3.0)
self.init(withArray: elements.map({ .some($0) }))
#else
self.init(withArray: elements.map({ .Some($0) }))
#endif
}
init(withArray elements : [Int?]) {
// Figure out the size of square
let actualSize = Int(ceil(sqrt(Double(elements.count))))
// Fill in any remaining squares if we weren't given sufficient information.
let paddedElements : [Int?]
if elements.count == actualSize {
paddedElements = elements
} else {
#if swift(>=3.0)
paddedElements = elements + Array(repeating: nil, count: actualSize)
#else
paddedElements = elements + Array(count: actualSize, repeatedValue: nil)
#endif
}
// Build the 2d contents
var twoDimensionalContents : [[Int?]] = []
var startingIndex = 0
#if swift(>=3.0)
let range = stride(from: actualSize, through: actualSize * actualSize, by: actualSize)
#else
let range = actualSize.stride(through: actualSize * actualSize, by: actualSize)
#endif
range.forEach { newIndex in
let subrange = paddedElements[startingIndex..<newIndex]
twoDimensionalContents.append(Array(subrange))
startingIndex = newIndex
}
// Save the properties
size = actualSize
linearContents = paddedElements
self.twoDimensionalContents = twoDimensionalContents
}
}
// This is the first problem, with the first bonus
extension MagicSquare {
func isValid() -> Bool {
let areAllRowsValid = self.twoDimensionalContents.reduce(true) { (isValidSoFar, row) -> Bool in
guard isValidSoFar else {
// short circuit if we already found an invalid row
return false
}
let areAnyValuesNil = row.reduce(true) { (isValidSoFar, value) -> Bool in
guard isValidSoFar else {
return false
}
return value != nil
}
guard areAnyValuesNil else {
return false
}
let rowSum = row.flatMap({ $0 }).reduce(0, combine: +)
return rowSum == targetSum
}
let areAllColumnsValid = (0..<size).reduce(true) { (isValidSoFar, columnIndex) -> Bool in
guard isValidSoFar else {
return false
}
var noNilsFound = true
let columnSum = twoDimensionalContents.reduce(0) { (sumSoFar, row) -> Int in
if let value = row[columnIndex] {
return sumSoFar + value
} else {
noNilsFound = false
return sumSoFar
}
}
guard noNilsFound else {
return false
}
return columnSum == targetSum
}
var noNilsFound = true
let uphillSum = (0..<size).reduce(0) { (sumSoFar, index) -> Int in
if let value = twoDimensionalContents[index][index] {
return sumSoFar + value
} else {
noNilsFound = false
return sumSoFar
}
}
let downhillSum = (0..<size).reduce(0) { (sumSoFar, index) -> Int in
if let value = twoDimensionalContents[index][size - index - 1] {
return sumSoFar + value
} else {
noNilsFound = false
return sumSoFar
}
}
guard noNilsFound else {
return false
}
let isUphillDiagonalValid = uphillSum == targetSum
let isDownhillDiagonalValid = downhillSum == targetSum
return areAllRowsValid
&& areAllColumnsValid
&& isUphillDiagonalValid
&& isDownhillDiagonalValid
}
}
// This is the first problem with the second bonus
extension MagicSquare {
func canRepairLastRow() -> Bool {
#if swift(>=3.0)
let columnSums = Array(repeating: targetSum, count: size)
#else
let columnSums = Array(count: size, repeatedValue: targetSum)
#endif
// Compute last row from columns
let possibleLastRow = twoDimensionalContents.reduce(columnSums) { (remainingSum, row) -> [Int] in
#if swift(>=3.0)
let enumeration = row.enumerated()
#else
let enumeration = row.enumerate()
#endif
return enumeration.map { (index, value) -> Int in
return remainingSum[index] - (value ?? 0)
}
}
let replaceRange = (size*size-size)..<(size*size)
var newLinearSquare = linearContents
#if swift(>=3.0)
newLinearSquare.replaceSubrange(replaceRange, with: possibleLastRow.map({ .some($0) }))
#else
newLinearSquare.replaceRange(replaceRange, with: possibleLastRow.map({ .Some($0) }))
#endif
let testMagicSquare = MagicSquare(withArray: newLinearSquare)
return testMagicSquare.isValid()
}
}
// Manual testing
let trueSquare1 : MagicSquare = [8, 1, 6, 3, 5, 7, 4, 9, 2]
trueSquare1.isValid()
//: ## Test run
//: This method is just needed to adapt the isValid method to something my testing functions can call
func verify(numbers : [Int]) -> Bool {
let magicSquare = MagicSquare(withArray: numbers)
return magicSquare.isValid()
}
let trueInput1 = [8, 1, 6, 3, 5, 7, 4, 9, 2]
let trueInput2 = [2, 7, 6, 9, 5, 1, 4, 3, 8]
let falseInput1 = [3, 5, 7, 8, 1, 6, 4, 9, 2]
let falseInput2 = [8, 1, 6, 7, 5, 3, 4, 9, 2]
testMethod(method: verify, withInput: trueInput1, expectingOutput: true)
testMethod(method: verify, withInput: trueInput2, expectingOutput: true)
testMethod(method: verify, withInput: falseInput1, expectingOutput: false)
testMethod(method: verify, withInput: falseInput2, expectingOutput: false)
//: Bonus 2
let validButMissingLastRow = [8, 1, 6, 3, 5, 7]
let invalidMissingLastRow = [3, 5, 7, 8, 1, 6]
func canRepairLastRow(numbers : [Int]) -> Bool {
let magicSquare = MagicSquare(withArray: numbers)
return magicSquare.canRepairLastRow()
}
testMethod(method: canRepairLastRow, withInput: validButMissingLastRow, expectingOutput: true)
testMethod(method: canRepairLastRow, withInput: invalidMissingLastRow, expectingOutput: false)
//: [Table of Contents](Table%20of%20Contents)
| mit | a240e657cf1c66f142a8c019750a000a | 31.720524 | 121 | 0.573735 | 4.436353 | false | false | false | false |
adly-holler/Bond | Bond/iOS/Bond+UILabel.swift | 8 | 3306 | //
// Bond+UILabel.swift
// Bond
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Srdan Rasic (@srdanrasic)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
private var textDynamicHandleUILabel: UInt8 = 0;
private var attributedTextDynamicHandleUILabel: UInt8 = 0;
private var textColorDynamicHandleUILabel: UInt8 = 0;
extension UILabel: Bondable {
public var dynText: Dynamic<String> {
if let d: AnyObject = objc_getAssociatedObject(self, &textDynamicHandleUILabel) {
return (d as? Dynamic<String>)!
} else {
let d = InternalDynamic<String>(self.text ?? "")
let bond = Bond<String>() { [weak self] v in if let s = self { s.text = v } }
d.bindTo(bond, fire: false, strongly: false)
d.retain(bond)
objc_setAssociatedObject(self, &textDynamicHandleUILabel, d, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
return d
}
}
public var dynAttributedText: Dynamic<NSAttributedString> {
if let d: AnyObject = objc_getAssociatedObject(self, &attributedTextDynamicHandleUILabel) {
return (d as? Dynamic<NSAttributedString>)!
} else {
let d = InternalDynamic<NSAttributedString>(self.attributedText ?? NSAttributedString(string: ""))
let bond = Bond<NSAttributedString>() { [weak self] v in if let s = self { s.attributedText = v } }
d.bindTo(bond, fire: false, strongly: false)
d.retain(bond)
objc_setAssociatedObject(self, &attributedTextDynamicHandleUILabel, d, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
return d
}
}
public var dynTextColor: Dynamic<UIColor> {
if let d: AnyObject = objc_getAssociatedObject(self, &textColorDynamicHandleUILabel) {
return (d as? Dynamic<UIColor>)!
} else {
let d = InternalDynamic<UIColor>(self.textColor ?? UIColor.blackColor())
let bond = Bond<UIColor>() { [weak self] v in if let s = self { s.textColor = v } }
d.bindTo(bond, fire: false, strongly: false)
d.retain(bond)
objc_setAssociatedObject(self, &textColorDynamicHandleUILabel, d, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
return d
}
}
public var designatedBond: Bond<String> {
return self.dynText.valueBond
}
}
| mit | 2120cebe6dbac6a8a8ed7bac4a931cc9 | 41.935065 | 135 | 0.710526 | 4.222222 | false | false | false | false |
cdebortoli/JsonManagedObject-Swift | JMODemo/JMODemo/ViewController.swift | 1 | 3487 | //
// ViewController.swift
// JMODemo
//
// Created by christophe on 21/06/14.
// Copyright (c) 2014 cdebortoli. All rights reserved.
//
import UIKit
import JsonManagedObject
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// ------------------ Configuration ------------------
JMOConfig.jsonWithEnvelope = true
JMOConfig.dateFormat = "yyyy-MM-dd"
JMOConfig.managedObjectContext = databaseManagerSharedInstance.databaseCore.managedObjectContext
JMOConfig.temporaryNSManagedObjectInstance = true
// ------------------ Get Aircraft from JSON ------------------
let dictOptional = dictionaryFromService("aircraftJsonWithEnvelope")
if let dict = dictOptional {
var aircraft:Aircraft? = jsonManagedObjectSharedInstance.analyzeJsonDictionary(dict, forClass:Aircraft.classForCoder()) as? Aircraft
println(aircraft)
// ------------------ Get JSON from Aircraft ------------------
let aircraftJsonRepresentation = aircraft?.getJson()
println(aircraftJsonRepresentation)
}
// ------------------ Get multiple Aircrafts from JSON ------------------
let aircraftArrayOptional = arrayFromJson("aircraftsJsonWithEnvelope")
if let aircraftArray = aircraftArrayOptional {
var aircrafts = jsonManagedObjectSharedInstance.analyzeJsonArray(aircraftArray, forClass: Aircraft.classForCoder()) as [Aircraft]
println(aircrafts)
}
// ------------------ Get Custom object from JSON ------------------
let customObjectDictOptional = dictionaryFromService("customObjectJson")
if let customObjectDict = customObjectDictOptional {
var customObject:CustomObject? = jsonManagedObjectSharedInstance.analyzeJsonDictionary(customObjectDict, forClass: CustomObject.self) as? CustomObject
println(customObject!.attrString)
println(customObject!.attrNumber)
println(customObject!.attrDate)
println(customObject!.attrArray![0].attrString)
println(customObject!.attrDictionary!["a"])
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func dictionaryFromService(service:String) -> [String: AnyObject]? {
let filepathOptional = NSBundle.mainBundle().pathForResource(service, ofType: "json")
if let filepath = filepathOptional {
let filecontent = NSData.dataWithContentsOfFile(filepath, options: nil, error: nil)
let json = NSJSONSerialization.JSONObjectWithData(filecontent, options: NSJSONReadingOptions.MutableContainers, error: nil) as [String: AnyObject]
return json
}
return nil
}
func arrayFromJson(service:String) -> [AnyObject]? {
let filepathOptional = NSBundle.mainBundle().pathForResource(service, ofType: "json")
if let filepath = filepathOptional {
let filecontent = NSData.dataWithContentsOfFile(filepath, options: nil, error: nil)
let json = NSJSONSerialization.JSONObjectWithData(filecontent, options: NSJSONReadingOptions.MutableContainers, error: nil) as [AnyObject]
return json
}
return nil
}
}
| mit | 2199dbc4330f7b1d85b4bef278f42a51 | 42.049383 | 162 | 0.635503 | 5.456964 | false | true | false | false |
iadmir/Signal-iOS | Signal/src/call/Speakerbox/CallKitCallUIAdaptee.swift | 1 | 13980 | //
// Copyright (c) 2017 Open Whisper Systems. All rights reserved.
//
import Foundation
import UIKit
import CallKit
import AVFoundation
/**
* Connects user interface to the CallService using CallKit.
*
* User interface is routed to the CallManager which requests CXCallActions, and if the CXProvider accepts them,
* their corresponding consequences are implmented in the CXProviderDelegate methods, e.g. using the CallService
*/
@available(iOS 10.0, *)
final class CallKitCallUIAdaptee: NSObject, CallUIAdaptee, CXProviderDelegate {
let TAG = "[CallKitCallUIAdaptee]"
private let callManager: CallKitCallManager
internal let callService: CallService
internal let notificationsAdapter: CallNotificationsAdapter
internal let contactsManager: OWSContactsManager
private let provider: CXProvider
// CallKit handles incoming ringer stop/start for us. Yay!
let hasManualRinger = false
// The app's provider configuration, representing its CallKit capabilities
static var providerConfiguration: CXProviderConfiguration {
let localizedName = NSLocalizedString("APPLICATION_NAME", comment: "Name of application")
let providerConfiguration = CXProviderConfiguration(localizedName: localizedName)
providerConfiguration.supportsVideo = true
providerConfiguration.maximumCallGroups = 1
providerConfiguration.maximumCallsPerCallGroup = 1
providerConfiguration.supportedHandleTypes = [.phoneNumber, .generic]
if let iconMaskImage = UIImage(named: "IconMask") {
providerConfiguration.iconTemplateImageData = UIImagePNGRepresentation(iconMaskImage)
}
providerConfiguration.ringtoneSound = "r.caf"
return providerConfiguration
}
init(callService: CallService, contactsManager: OWSContactsManager, notificationsAdapter: CallNotificationsAdapter) {
AssertIsOnMainThread()
Logger.debug("\(self.TAG) \(#function)")
self.callManager = CallKitCallManager()
self.callService = callService
self.contactsManager = contactsManager
self.notificationsAdapter = notificationsAdapter
self.provider = CXProvider(configuration: type(of: self).providerConfiguration)
super.init()
self.provider.setDelegate(self, queue: nil)
}
// MARK: CallUIAdaptee
func startOutgoingCall(handle: String) -> SignalCall {
AssertIsOnMainThread()
Logger.info("\(self.TAG) \(#function)")
let call = SignalCall.outgoingCall(localId: UUID(), remotePhoneNumber: handle)
// Add the new outgoing call to the app's list of calls.
// So we can find it in the provider delegate callbacks.
callManager.addCall(call)
callManager.startCall(call)
return call
}
// Called from CallService after call has ended to clean up any remaining CallKit call state.
func failCall(_ call: SignalCall, error: CallError) {
AssertIsOnMainThread()
Logger.info("\(self.TAG) \(#function)")
switch error {
case .timeout(description: _):
provider.reportCall(with: call.localId, endedAt: Date(), reason: CXCallEndedReason.unanswered)
default:
provider.reportCall(with: call.localId, endedAt: Date(), reason: CXCallEndedReason.failed)
}
self.callManager.removeCall(call)
}
func reportIncomingCall(_ call: SignalCall, callerName: String) {
AssertIsOnMainThread()
Logger.info("\(self.TAG) \(#function)")
// Construct a CXCallUpdate describing the incoming call, including the caller.
let update = CXCallUpdate()
if Environment.getCurrent().preferences.isCallKitPrivacyEnabled() {
let callKitId = CallKitCallManager.kAnonymousCallHandlePrefix + call.localId.uuidString
update.remoteHandle = CXHandle(type: .generic, value: callKitId)
TSStorageManager.shared().setPhoneNumber(call.remotePhoneNumber, forCallKitId:callKitId)
update.localizedCallerName = NSLocalizedString("CALLKIT_ANONYMOUS_CONTACT_NAME", comment: "The generic name used for calls if CallKit privacy is enabled")
} else {
update.localizedCallerName = self.contactsManager.stringForConversationTitle(withPhoneIdentifier: call.remotePhoneNumber)
update.remoteHandle = CXHandle(type: .phoneNumber, value: call.remotePhoneNumber)
}
update.hasVideo = call.hasLocalVideo
disableUnsupportedFeatures(callUpdate: update)
// Report the incoming call to the system
provider.reportNewIncomingCall(with: call.localId, update: update) { error in
/*
Only add incoming call to the app's list of calls if the call was allowed (i.e. there was no error)
since calls may be "denied" for various legitimate reasons. See CXErrorCodeIncomingCallError.
*/
guard error == nil else {
Logger.error("\(self.TAG) failed to report new incoming call")
return
}
self.callManager.addCall(call)
}
}
func answerCall(localId: UUID) {
AssertIsOnMainThread()
Logger.info("\(self.TAG) \(#function)")
owsFail("\(self.TAG) \(#function) CallKit should answer calls via system call screen, not via notifications.")
}
func answerCall(_ call: SignalCall) {
AssertIsOnMainThread()
Logger.info("\(self.TAG) \(#function)")
callManager.answer(call: call)
}
func declineCall(localId: UUID) {
AssertIsOnMainThread()
owsFail("\(self.TAG) \(#function) CallKit should decline calls via system call screen, not via notifications.")
}
func declineCall(_ call: SignalCall) {
AssertIsOnMainThread()
Logger.info("\(self.TAG) \(#function)")
callManager.localHangup(call: call)
}
func recipientAcceptedCall(_ call: SignalCall) {
AssertIsOnMainThread()
Logger.info("\(self.TAG) \(#function)")
self.provider.reportOutgoingCall(with: call.localId, connectedAt: nil)
let update = CXCallUpdate()
disableUnsupportedFeatures(callUpdate: update)
provider.reportCall(with: call.localId, updated: update)
}
func localHangupCall(_ call: SignalCall) {
AssertIsOnMainThread()
Logger.info("\(self.TAG) \(#function)")
callManager.localHangup(call: call)
}
func remoteDidHangupCall(_ call: SignalCall) {
AssertIsOnMainThread()
Logger.info("\(self.TAG) \(#function)")
provider.reportCall(with: call.localId, endedAt: nil, reason: CXCallEndedReason.remoteEnded)
}
func remoteBusy(_ call: SignalCall) {
AssertIsOnMainThread()
Logger.info("\(self.TAG) \(#function)")
provider.reportCall(with: call.localId, endedAt: nil, reason: CXCallEndedReason.unanswered)
}
func setIsMuted(call: SignalCall, isMuted: Bool) {
AssertIsOnMainThread()
Logger.info("\(self.TAG) \(#function)")
callManager.setIsMuted(call: call, isMuted: isMuted)
}
func setHasLocalVideo(call: SignalCall, hasLocalVideo: Bool) {
AssertIsOnMainThread()
Logger.debug("\(self.TAG) \(#function)")
let update = CXCallUpdate()
update.hasVideo = hasLocalVideo
// Update the CallKit UI.
provider.reportCall(with: call.localId, updated: update)
self.callService.setHasLocalVideo(hasLocalVideo: hasLocalVideo)
}
// MARK: CXProviderDelegate
func providerDidReset(_ provider: CXProvider) {
AssertIsOnMainThread()
Logger.info("\(self.TAG) \(#function)")
// Stop any in-progress WebRTC related audio.
PeerConnectionClient.stopAudioSession()
// End any ongoing calls if the provider resets, and remove them from the app's list of calls,
// since they are no longer valid.
callService.handleFailedCurrentCall(error: .providerReset)
// Remove all calls from the app's list of calls.
callManager.removeAllCalls()
}
func provider(_ provider: CXProvider, perform action: CXStartCallAction) {
AssertIsOnMainThread()
Logger.info("\(TAG) in \(#function) CXStartCallAction")
guard let call = callManager.callWithLocalId(action.callUUID) else {
Logger.error("\(TAG) unable to find call in \(#function)")
return
}
// We can't wait for long before fulfilling the CXAction, else CallKit will show a "Failed Call". We don't
// actually need to wait for the outcome of the handleOutgoingCall promise, because it handles any errors by
// manually failing the call.
let callPromise = self.callService.handleOutgoingCall(call)
callPromise.retainUntilComplete()
action.fulfill()
self.provider.reportOutgoingCall(with: call.localId, startedConnectingAt: nil)
if Environment.getCurrent().preferences.isCallKitPrivacyEnabled() {
// Update the name used in the CallKit UI for outgoing calls.
let update = CXCallUpdate()
update.localizedCallerName = NSLocalizedString("CALLKIT_ANONYMOUS_CONTACT_NAME",
comment: "The generic name used for calls if CallKit privacy is enabled")
provider.reportCall(with: call.localId, updated: update)
}
}
func provider(_ provider: CXProvider, perform action: CXAnswerCallAction) {
AssertIsOnMainThread()
Logger.info("\(TAG) Received \(#function) CXAnswerCallAction")
// Retrieve the instance corresponding to the action's call UUID
guard let call = callManager.callWithLocalId(action.callUUID) else {
action.fail()
return
}
self.callService.handleAnswerCall(call)
self.showCall(call)
action.fulfill()
}
public func provider(_ provider: CXProvider, perform action: CXEndCallAction) {
AssertIsOnMainThread()
Logger.info("\(TAG) Received \(#function) CXEndCallAction")
guard let call = callManager.callWithLocalId(action.callUUID) else {
Logger.error("\(self.TAG) in \(#function) trying to end unknown call with localId: \(action.callUUID)")
action.fail()
return
}
self.callService.handleLocalHungupCall(call)
// Signal to the system that the action has been successfully performed.
action.fulfill()
// Remove the ended call from the app's list of calls.
self.callManager.removeCall(call)
}
public func provider(_ provider: CXProvider, perform action: CXSetHeldCallAction) {
AssertIsOnMainThread()
Logger.info("\(TAG) Received \(#function) CXSetHeldCallAction")
guard let call = callManager.callWithLocalId(action.callUUID) else {
action.fail()
return
}
// Update the SignalCall's underlying hold state.
call.isOnHold = action.isOnHold
// Stop or start audio in response to holding or unholding the call.
if call.isOnHold {
// stopAudio() <-- SpeakerBox
PeerConnectionClient.stopAudioSession()
} else {
// startAudio() <-- SpeakerBox
// This is redundant with what happens in `provider(_:didActivate:)`
//PeerConnectionClient.startAudioSession()
}
// Signal to the system that the action has been successfully performed.
action.fulfill()
}
public func provider(_ provider: CXProvider, perform action: CXSetMutedCallAction) {
AssertIsOnMainThread()
Logger.info("\(TAG) Received \(#function) CXSetMutedCallAction")
guard callManager.callWithLocalId(action.callUUID) != nil else {
Logger.error("\(TAG) Failing CXSetMutedCallAction for unknown call: \(action.callUUID)")
action.fail()
return
}
self.callService.setIsMuted(isMuted: action.isMuted)
action.fulfill()
}
public func provider(_ provider: CXProvider, perform action: CXSetGroupCallAction) {
AssertIsOnMainThread()
Logger.warn("\(TAG) unimplemented \(#function) for CXSetGroupCallAction")
}
public func provider(_ provider: CXProvider, perform action: CXPlayDTMFCallAction) {
AssertIsOnMainThread()
Logger.warn("\(TAG) unimplemented \(#function) for CXPlayDTMFCallAction")
}
func provider(_ provider: CXProvider, timedOutPerforming action: CXAction) {
AssertIsOnMainThread()
owsFail("\(TAG) Timed out \(#function) while performing \(action)")
// React to the action timeout if necessary, such as showing an error UI.
}
func provider(_ provider: CXProvider, didActivate audioSession: AVAudioSession) {
AssertIsOnMainThread()
Logger.debug("\(TAG) Received \(#function)")
// Start recording
PeerConnectionClient.startAudioSession()
}
func provider(_ provider: CXProvider, didDeactivate audioSession: AVAudioSession) {
AssertIsOnMainThread()
Logger.debug("\(TAG) Received \(#function)")
/*
Restart any non-call related audio now that the app's audio session has been
de-activated after having its priority restored to normal.
*/
}
// MARK: - Util
private func disableUnsupportedFeatures(callUpdate: CXCallUpdate) {
// Call Holding is failing to restart audio when "swapping" calls on the CallKit screen
// until user returns to in-app call screen.
callUpdate.supportsHolding = false
// Not yet supported
callUpdate.supportsGrouping = false
callUpdate.supportsUngrouping = false
// Is there any reason to support this?
callUpdate.supportsDTMF = false
}
}
| gpl-3.0 | e2d627f55747959a0de6c4cb83656324 | 35.124031 | 166 | 0.664807 | 4.97155 | false | false | false | false |
ya-s-u/SimpleAlertView | Example/SCLAlertViewExample/ViewController.swift | 1 | 2911 | //
// ViewController.swift
// SCLAlertViewExample
//
// Created by Viktor Radchenko on 6/6/14.
// Copyright (c) 2014 Viktor Radchenko. All rights reserved.
//
import UIKit
let kSuccessTitle = "Congratulations"
let kErrorTitle = "Connection error"
let kNoticeTitle = "Notice"
let kWarningTitle = "Warning"
let kInfoTitle = "Info"
let kWaitTitle = "Wait"
let kSubtitle = "You've just displayed this awesome Pop Up View"
let kDefaultAnimationDuration = 2.0
class ViewController: UIViewController {
var wait = SCLAlertView()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func showSuccess(sender: AnyObject) {
let alert = SCLAlertView()
alert.addButton("First Button", target:self, selector:Selector("firstButton"))
alert.addButton("Second Button") {
println("Second button tapped")
}
alert.showAlert(kSuccessTitle, subTitle: kSubtitle)
}
@IBAction func showError(sender: AnyObject) {
SCLAlertView().showAlert("Hold On...", subTitle:"You have not saved your Submission yet. Please save the Submission before accessing the Responses list. Blah de blah de blah, blah. Blah de blah de blah, blah.Blah de blah de blah, blah.Blah de blah de blah, blah.Blah de blah de blah, blah.Blah de blah de blah, blah.", closeButtonTitle:"OK")
}
@IBAction func showNotice(sender: AnyObject) {
SCLAlertView().showAlert(kNoticeTitle, subTitle: kSubtitle)
}
@IBAction func showWarning(sender: AnyObject) {
SCLAlertView().showAlert(kWarningTitle, subTitle: kSubtitle)
}
@IBAction func showInfo(sender: AnyObject) {
SCLAlertView().showAlert("登録が完了しました", subTitle: "ありがとうございます。管理ページより内容を確認してください。", colorStyle: UIColor(red: 255/255, green: 193/255, blue: 33/255, alpha: 1.0))
}
@IBAction func showEdit(sender: AnyObject) {
let alert = SCLAlertView()
let txt = alert.addTextField(title:"Enter your name")
alert.addButton("Show Name") {
println("Text value: \(txt.text)")
}
alert.showAlert(kInfoTitle, subTitle:kSubtitle)
}
@IBAction func showWait(sender: AnyObject) {
println("start loading...")
wait.showLoading("ロード中です", subTitle: "データ通信をしています。しばらくお待ちください。")
NSTimer.scheduledTimerWithTimeInterval(3.0, target: self, selector:"hideWait:", userInfo: nil, repeats: false)
}
func hideWait(timer: NSTimer) {
println("finish loading...")
wait.hideView()
}
func firstButton() {
println("First button tapped")
}
}
| mit | 9bdc548e11795911ae5ef1efa4fda9c0 | 32.409639 | 343 | 0.686621 | 3.978479 | false | false | false | false |
RoRoche/iOSSwiftStarter | iOSSwiftStarter/Pods/CoreStore/CoreStore/Saving and Processing/SynchronousDataTransaction.swift | 2 | 9467 | //
// SynchronousDataTransaction.swift
// CoreStore
//
// Copyright © 2015 John Rommel Estropia
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import CoreData
#if USE_FRAMEWORKS
import GCDKit
#endif
// MARK: - SynchronousDataTransaction
/**
The `SynchronousDataTransaction` provides an interface for `NSManagedObject` creates, updates, and deletes. A transaction object should typically be only used from within a transaction block initiated from `DataStack.beginSynchronous(_:)`, or from `CoreStore.beginSynchronous(_:)`.
*/
public final class SynchronousDataTransaction: BaseDataTransaction {
/**
Saves the transaction changes and waits for completion synchronously. This method should not be used after the `commit()` method was already called once.
- returns: a `SaveResult` containing the success or failure information
*/
public func commitAndWait() -> SaveResult {
CoreStore.assert(
self.transactionQueue.isCurrentExecutionContext(),
"Attempted to commit a \(typeName(self)) outside its designated queue."
)
CoreStore.assert(
!self.isCommitted,
"Attempted to commit a \(typeName(self)) more than once."
)
self.isCommitted = true
let result = self.context.saveSynchronously()
self.result = result
return result
}
/**
Begins a child transaction synchronously where `NSManagedObject` creates, updates, and deletes can be made. This method should not be used after the `commit()` method was already called once.
- parameter closure: the block where creates, updates, and deletes can be made to the transaction. Transaction blocks are executed serially in a background queue, and all changes are made from a concurrent `NSManagedObjectContext`.
- returns: a `SaveResult` value indicating success or failure, or `nil` if the transaction was not comitted synchronously
*/
public func beginSynchronous(closure: (transaction: SynchronousDataTransaction) -> Void) -> SaveResult? {
CoreStore.assert(
self.transactionQueue.isCurrentExecutionContext(),
"Attempted to begin a child transaction from a \(typeName(self)) outside its designated queue."
)
CoreStore.assert(
!self.isCommitted,
"Attempted to begin a child transaction from an already committed \(typeName(self))."
)
return SynchronousDataTransaction(
mainContext: self.context,
queue: self.childTransactionQueue,
closure: closure).performAndWait()
}
// MARK: BaseDataTransaction
/**
Creates a new `NSManagedObject` with the specified entity type.
- parameter into: the `Into` clause indicating the destination `NSManagedObject` entity type and the destination configuration
- returns: a new `NSManagedObject` instance of the specified entity type.
*/
public override func create<T: NSManagedObject>(into: Into<T>) -> T {
CoreStore.assert(
!self.isCommitted,
"Attempted to create an entity of type \(typeName(T)) from an already committed \(typeName(self))."
)
return super.create(into)
}
/**
Returns an editable proxy of a specified `NSManagedObject`. This method should not be used after the `commit()` method was already called once.
- parameter object: the `NSManagedObject` type to be edited
- returns: an editable proxy for the specified `NSManagedObject`.
*/
@warn_unused_result
public override func edit<T: NSManagedObject>(object: T?) -> T? {
CoreStore.assert(
!self.isCommitted,
"Attempted to update an entity of type \(typeName(object)) from an already committed \(typeName(self))."
)
return super.edit(object)
}
/**
Returns an editable proxy of the object with the specified `NSManagedObjectID`. This method should not be used after the `commit()` method was already called once.
- parameter into: an `Into` clause specifying the entity type
- parameter objectID: the `NSManagedObjectID` for the object to be edited
- returns: an editable proxy for the specified `NSManagedObject`.
*/
@warn_unused_result
public override func edit<T: NSManagedObject>(into: Into<T>, _ objectID: NSManagedObjectID) -> T? {
CoreStore.assert(
!self.isCommitted,
"Attempted to update an entity of type \(typeName(T)) from an already committed \(typeName(self))."
)
return super.edit(into, objectID)
}
/**
Deletes a specified `NSManagedObject`. This method should not be used after the `commit()` method was already called once.
- parameter object: the `NSManagedObject` type to be deleted
*/
public override func delete(object: NSManagedObject?) {
CoreStore.assert(
!self.isCommitted,
"Attempted to delete an entity of type \(typeName(object)) from an already committed \(typeName(self))."
)
super.delete(object)
}
/**
Deletes the specified `NSManagedObject`s.
- parameter object1: the `NSManagedObject` to be deleted
- parameter object2: another `NSManagedObject` to be deleted
- parameter objects: other `NSManagedObject`s to be deleted
*/
public override func delete(object1: NSManagedObject?, _ object2: NSManagedObject?, _ objects: NSManagedObject?...) {
CoreStore.assert(
!self.isCommitted,
"Attempted to delete an entities from an already committed \(typeName(self))."
)
super.delete(([object1, object2] + objects).flatMap { $0 })
}
/**
Deletes the specified `NSManagedObject`s.
- parameter objects: the `NSManagedObject`s to be deleted
*/
public override func delete<S: SequenceType where S.Generator.Element: NSManagedObject>(objects: S) {
CoreStore.assert(
!self.isCommitted,
"Attempted to delete an entities from an already committed \(typeName(self))."
)
super.delete(objects)
}
/**
Rolls back the transaction by resetting the `NSManagedObjectContext`. After calling this method, all `NSManagedObjects` fetched within the transaction will become invalid. This method should not be used after the `commit()` method was already called once.
*/
@available(*, deprecated=1.3.4, message="Resetting the context is inherently unsafe. This method will be removed in the near future. Use `beginUnsafe()` to create transactions with `undo` support.")
public func rollback() {
CoreStore.assert(
!self.isCommitted,
"Attempted to rollback an already committed \(typeName(self))."
)
CoreStore.assert(
self.transactionQueue.isCurrentExecutionContext(),
"Attempted to rollback a \(typeName(self)) outside its designated queue."
)
self.context.reset()
}
@available(*, deprecated=1.5.2, renamed="commitAndWait")
public func commit() {
self.commitAndWait()
}
// MARK: Internal
internal init(mainContext: NSManagedObjectContext, queue: GCDQueue, closure: (transaction: SynchronousDataTransaction) -> Void) {
self.closure = closure
super.init(mainContext: mainContext, queue: queue, supportsUndo: false, bypassesQueueing: false)
}
internal func performAndWait() -> SaveResult? {
self.transactionQueue.sync {
self.closure(transaction: self)
if !self.isCommitted && self.hasChanges {
CoreStore.log(
.Warning,
message: "The closure for the \(typeName(self)) completed without being committed. All changes made within the transaction were discarded."
)
}
}
return self.result
}
// MARK: Private
private let closure: (transaction: SynchronousDataTransaction) -> Void
}
| apache-2.0 | b90e1f9f2a60c3303f65c0cf94c7aa7d | 38.115702 | 282 | 0.651067 | 5.19539 | false | false | false | false |
dataich/TypetalkSwift | Carthage/Checkouts/OAuth2/Sources/DataLoader/OAuth2DataLoader.swift | 1 | 7605 | //
// OAuth2DataLoader.swift
// OAuth2
//
// Created by Pascal Pfiffner on 8/31/16.
// Copyright 2016 Pascal Pfiffner
//
// 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
#if !NO_MODULE_IMPORT
import Base
import Flows
#endif
/**
A class that makes loading data from a protected endpoint easier.
*/
open class OAuth2DataLoader: OAuth2Requestable {
/// The OAuth2 instance used for OAuth2 access tokvarretrieval.
public let oauth2: OAuth2
/// If set to true, a 403 is treated as a 401. The default is false.
public var alsoIntercept403: Bool = false
/**
Designated initializer.
Provide `host` if 301 and 302 redirects should be followed automatically, as long as they appear on the same host.
- parameter oauth2: The OAuth2 instance to use for authorization when loading data.
- parameter host: If given will handle redirects within the same host by way of `OAuth2DataLoaderSessionTaskDelegate`
*/
public init(oauth2: OAuth2, host: String? = nil) {
self.oauth2 = oauth2
super.init(logger: oauth2.logger)
if let host = host {
sessionDelegate = OAuth2DataLoaderSessionTaskDelegate(loader: self, host: host)
}
}
// MARK: - Make Requests
/// Our FIFO queue.
private var enqueued: [OAuth2DataRequest]?
private var isAuthorizing = false
/**
Overriding this method: it intercepts `unauthorizedClient` errors, stops and enqueues all calls, starts the authorization and, upon
success, resumes all enqueued calls.
The callback is easy to use, like so:
perform(request: req) { dataStatusResponse in
do {
let (data, status) = try dataStatusResponse()
// do what you must with `data` as Data and `status` as Int
}
catch let error {
// the request failed because of `error`
}
}
- parameter request: The request to execute
- parameter callback: The callback to call when the request completes/fails. Looks terrifying, see above on how to use it
*/
override open func perform(request: URLRequest, callback: @escaping ((OAuth2Response) -> Void)) {
perform(request: request, retry: true, callback: callback)
}
/**
This method takes an additional `retry` flag, then uses the base implementation of `perform(request:callback:)` to perform the given
request. It intercepts 401 (and 403, if `alsoIntercept403` is true), enqueues the request and performs authorization. During
authorization, all requests to be performed are enqueued and they are all dequeued once authorization finishes, either by retrying
them on authorization success or by aborting them all with the same error.
The callback is easy to use, like so:
perform(request: req) { dataStatusResponse in
do {
let (data, status) = try dataStatusResponse()
// do what you must with `data` as Data and `status` as Int
}
catch let error {
// the request failed because of `error`
}
}
- parameter request: The request to execute
- parameter retry: Whether the request should be retried on 401 (and possibly 403)
- parameter callback: The callback to call when the request completes/fails
*/
open func perform(request: URLRequest, retry: Bool, callback: @escaping ((OAuth2Response) -> Void)) {
guard !isAuthorizing else {
enqueue(request: request, callback: callback)
return
}
super.perform(request: request) { response in
do {
if self.alsoIntercept403, 403 == response.response.statusCode {
throw OAuth2Error.unauthorizedClient
}
let _ = try response.responseData()
callback(response)
}
// not authorized; stop and enqueue all requests, start authorization once, then re-try all enqueued requests
catch OAuth2Error.unauthorizedClient {
if retry {
self.enqueue(request: request, callback: callback)
self.oauth2.clientConfig.accessToken = nil
self.attemptToAuthorize() { json, error in
// dequeue all if we're authorized, throw all away if something went wrong
if nil != json {
self.retryAll()
}
else {
self.throwAllAway(with: error ?? OAuth2Error.requestCancelled)
}
}
}
else {
callback(response)
}
}
// some other error, pass along
catch {
callback(response)
}
}
}
/**
If not already authorizing, will use its `oauth2` instance to start authorization after forgetting any tokens (!).
This method will ignore calls while authorization is ongoing, meaning you will only get the callback once per authorization cycle.
- parameter callback: The callback passed on from `authorize(callback:)`. Authorization finishes successfully (auth parameters will be
non-nil but may be an empty dict), fails (error will be non-nil) or is canceled (both params and error are nil)
*/
open func attemptToAuthorize(callback: @escaping ((OAuth2JSON?, OAuth2Error?) -> Void)) {
if !isAuthorizing {
isAuthorizing = true
oauth2.authorize() { authParams, error in
self.isAuthorizing = false
callback(authParams, error)
}
}
}
// MARK: - Queue
/**
Enqueues the given URLRequest and callback. You probably don't want to use this method yourself.
- parameter request: The URLRequest to enqueue for later execution
- parameter callback: The closure to call when the request has been executed
*/
public func enqueue(request: URLRequest, callback: @escaping ((OAuth2Response) -> Void)) {
enqueue(request: OAuth2DataRequest(request: request, callback: callback))
}
/**
Enqueues the given OAuth2DataRequest. You probably don't want to use this method yourself.
- parameter request: The OAuth2DataRequest to enqueue for later execution
*/
public func enqueue(request: OAuth2DataRequest) {
if nil == enqueued {
enqueued = [request]
}
else {
enqueued!.append(request)
}
}
/**
Dequeue all enqueued requests, applying the given closure to all of them. The queue will be empty by the time the closure is called.
- parameter closure: The closure to apply to each enqueued request
*/
public func dequeueAndApply(closure: ((OAuth2DataRequest) -> Void)) {
guard let enq = enqueued else {
return
}
enqueued = nil
enq.forEach(closure)
}
/**
Uses `dequeueAndApply()` by signing and re-performing all enqueued requests.
*/
func retryAll() {
dequeueAndApply() { req in
var request = req.request
do {
try request.sign(with: oauth2)
self.perform(request: request, retry: false, callback: req.callback)
}
catch let error {
NSLog("OAuth2.DataLoader.retryAll(): \(error)")
}
}
}
/**
Uses `dequeueAndApply()` to all enqueued requests, calling their callback with a response representing the given error.
- parameter error: The error with which to finalize all enqueued requests
*/
func throwAllAway(with error: OAuth2Error) {
dequeueAndApply() { req in
let res = OAuth2Response(data: nil, request: req.request, response: HTTPURLResponse(), error: error)
req.callback(res)
}
}
}
| mit | e240c5cce66186a572ba076065070b1c | 30.953782 | 135 | 0.700592 | 3.922125 | false | false | false | false |
morizotter/xcmultilingual | DemoApp/Pods/SwiftyDrop/SwiftyDrop/Drop.swift | 1 | 15510 | //
// Drop.swift
// SwiftyDrop
//
// Created by MORITANAOKI on 2015/06/18.
//
import UIKit
public enum DropState {
case Default, Info, Success, Warning, Error
private func backgroundColor() -> UIColor? {
switch self {
case Default: return UIColor(red: 41/255.0, green: 128/255.0, blue: 185/255.0, alpha: 1.0)
case Info: return UIColor(red: 52/255.0, green: 152/255.0, blue: 219/255.0, alpha: 1.0)
case Success: return UIColor(red: 39/255.0, green: 174/255.0, blue: 96/255.0, alpha: 1.0)
case Warning: return UIColor(red: 241/255.0, green: 196/255.0, blue: 15/255.0, alpha: 1.0)
case Error: return UIColor(red: 192/255.0, green: 57/255.0, blue: 43/255.0, alpha: 1.0)
}
}
}
public enum DropBlur {
case Light, ExtraLight, Dark
private func blurEffect() -> UIBlurEffect {
switch self {
case .Light: return UIBlurEffect(style: .Light)
case .ExtraLight: return UIBlurEffect(style: .ExtraLight)
case .Dark: return UIBlurEffect(style: .Dark)
}
}
}
public final class Drop: UIView {
private var backgroundView: UIView!
private var statusLabel: UILabel!
private var topConstraint: NSLayoutConstraint!
private var heightConstraint: NSLayoutConstraint!
private let statusTopMargin: CGFloat = 8.0
private let statusBottomMargin: CGFloat = 8.0
private var upTimer: NSTimer?
private var startTop: CGFloat?
override init(frame: CGRect) {
super.init(frame: frame)
heightConstraint = NSLayoutConstraint(
item: self,
attribute: .Height,
relatedBy: .Equal,
toItem: nil,
attribute: .Height,
multiplier: 1.0,
constant: 100.0
)
self.addConstraint(heightConstraint)
scheduleUpTimer(4.0)
NSNotificationCenter.defaultCenter().addObserverForName(UIApplicationDidEnterBackgroundNotification, object: nil, queue: nil) { [weak self] notification in
if let s = self {
s.stopUpTimer()
s.removeFromSuperview()
}
}
NSNotificationCenter.defaultCenter().addObserverForName(UIDeviceOrientationDidChangeNotification, object: nil, queue: nil) { [weak self] notification in
if let s = self {
s.updateHeight()
}
}
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
deinit {
stopUpTimer()
}
func up() {
scheduleUpTimer(0.0)
}
func upFromTimer(timer: NSTimer) {
if let interval = timer.userInfo as? Double {
Drop.up(self, interval: interval)
}
}
private func scheduleUpTimer(after: Double) {
scheduleUpTimer(after, interval: 0.25)
}
private func scheduleUpTimer(after: Double, interval: Double) {
stopUpTimer()
upTimer = NSTimer.scheduledTimerWithTimeInterval(after, target: self, selector: "upFromTimer:", userInfo: interval, repeats: false)
}
private func stopUpTimer() {
upTimer?.invalidate()
upTimer = nil
}
private func updateHeight() {
heightConstraint.constant = self.statusLabel.frame.size.height + Drop.statusBarHeight() + statusTopMargin + statusBottomMargin
self.layoutIfNeeded()
}
}
extension Drop {
public class func down(status: String) {
down(status, state: .Default)
}
public class func down(status: String, state: DropState) {
down(status, state: state, blur: nil)
}
public class func down(status: String, blur: DropBlur) {
down(status, state: nil, blur: blur)
}
private class func down(status: String, state: DropState?, blur: DropBlur?) {
self.upAll()
let drop = Drop(frame: CGRectZero)
Drop.window().addSubview(drop)
let sideConstraints = ([.Left, .Right] as [NSLayoutAttribute]).map {
return NSLayoutConstraint(
item: drop,
attribute: $0,
relatedBy: .Equal,
toItem: Drop.window(),
attribute: $0,
multiplier: 1.0,
constant: 0.0
)
}
drop.topConstraint = NSLayoutConstraint(
item: drop,
attribute: .Top,
relatedBy: .Equal,
toItem: Drop.window(),
attribute: .Top,
multiplier: 1.0,
constant: -drop.heightConstraint.constant
)
Drop.window().addConstraints(sideConstraints)
Drop.window().addConstraint(drop.topConstraint)
drop.setup(status, state: state, blur: blur)
drop.updateHeight()
drop.topConstraint.constant = 0.0
UIView.animateWithDuration(
NSTimeInterval(0.25),
delay: NSTimeInterval(0.0),
options: .AllowUserInteraction | .CurveEaseOut,
animations: { [weak drop] () -> Void in
if let drop = drop { drop.layoutIfNeeded() }
}, completion: nil
)
}
private class func up(drop: Drop, interval: NSTimeInterval) {
drop.topConstraint.constant = -drop.heightConstraint.constant
UIView.animateWithDuration(
interval,
delay: NSTimeInterval(0.0),
options: .AllowUserInteraction | .CurveEaseIn,
animations: { [weak drop] () -> Void in
if let drop = drop {
drop.layoutIfNeeded()
}
}) { [weak drop] finished -> Void in
if let drop = drop { drop.removeFromSuperview() }
}
}
public class func upAll() {
for view in Drop.window().subviews {
if let drop = view as? Drop {
drop.up()
}
}
}
}
extension Drop {
private func setup(status: String, state: DropState?, blur: DropBlur?) {
self.setTranslatesAutoresizingMaskIntoConstraints(false)
if let blur = blur {
let blurEffect = blur.blurEffect()
// Visual Effect View
let visualEffectView = UIVisualEffectView(effect: blurEffect)
visualEffectView.setTranslatesAutoresizingMaskIntoConstraints(false)
self.addSubview(visualEffectView)
let visualEffectViewConstraints = ([.Right, .Bottom, .Left] as [NSLayoutAttribute]).map {
return NSLayoutConstraint(
item: visualEffectView,
attribute: $0,
relatedBy: .Equal,
toItem: self,
attribute: $0,
multiplier: 1.0,
constant: 0.0
)
}
let topConstraint = NSLayoutConstraint(
item: visualEffectView,
attribute: .Top,
relatedBy: .Equal,
toItem: self,
attribute: .Top,
multiplier: 1.0,
constant: -UIScreen.mainScreen().bounds.height
)
self.addConstraints(visualEffectViewConstraints)
self.addConstraint(topConstraint)
self.backgroundView = visualEffectView
// Vibrancy Effect View
let vibrancyEffectView = UIVisualEffectView(effect: UIVibrancyEffect(forBlurEffect: blurEffect))
vibrancyEffectView.setTranslatesAutoresizingMaskIntoConstraints(false)
visualEffectView.contentView.addSubview(vibrancyEffectView)
let vibrancyLeft = NSLayoutConstraint(
item: vibrancyEffectView,
attribute: .Left,
relatedBy: .Equal,
toItem: visualEffectView.contentView,
attribute: .LeftMargin,
multiplier: 1.0,
constant: 0.0
)
let vibrancyRight = NSLayoutConstraint(
item: vibrancyEffectView,
attribute: .Right,
relatedBy: .Equal,
toItem: visualEffectView.contentView,
attribute: .RightMargin,
multiplier: 1.0,
constant: 0.0
)
let vibrancyTop = NSLayoutConstraint(
item: vibrancyEffectView,
attribute: .Top,
relatedBy: .Equal,
toItem: visualEffectView.contentView,
attribute: .Top,
multiplier: 1.0,
constant: 0.0
)
let vibrancyBottom = NSLayoutConstraint(
item: vibrancyEffectView,
attribute: .Bottom,
relatedBy: .Equal,
toItem: visualEffectView.contentView,
attribute: .Bottom,
multiplier: 1.0,
constant: 0.0
)
visualEffectView.contentView.addConstraints([vibrancyTop, vibrancyRight, vibrancyBottom, vibrancyLeft])
// STATUS LABEL
let statusLabel = createStatusLabel(status, isVisualEffect: true)
vibrancyEffectView.contentView.addSubview(statusLabel)
let statusLeft = NSLayoutConstraint(
item: statusLabel,
attribute: .Left,
relatedBy: .Equal,
toItem: vibrancyEffectView.contentView,
attribute: .Left,
multiplier: 1.0,
constant: 0.0
)
let statusRight = NSLayoutConstraint(
item: statusLabel,
attribute: .Right,
relatedBy: .Equal,
toItem: vibrancyEffectView.contentView,
attribute: .Right,
multiplier: 1.0,
constant: 0.0
)
let statusBottom = NSLayoutConstraint(
item: statusLabel,
attribute: .Bottom,
relatedBy: .Equal,
toItem: vibrancyEffectView.contentView,
attribute: .Bottom,
multiplier: 1.0,
constant: -statusBottomMargin
)
vibrancyEffectView.contentView.addConstraints([statusRight, statusLeft, statusBottom])
self.statusLabel = statusLabel
}
if let state = state {
// Background View
let backgroundView = UIView(frame: CGRectZero)
backgroundView.setTranslatesAutoresizingMaskIntoConstraints(false)
backgroundView.alpha = 0.9
backgroundView.backgroundColor = state.backgroundColor()
self.addSubview(backgroundView)
let backgroundConstraints = ([.Right, .Bottom, .Left] as [NSLayoutAttribute]).map {
return NSLayoutConstraint(
item: backgroundView,
attribute: $0,
relatedBy: .Equal,
toItem: self,
attribute: $0,
multiplier: 1.0,
constant: 0.0
)
}
let topConstraint = NSLayoutConstraint(
item: backgroundView,
attribute: .Top,
relatedBy: .Equal,
toItem: self,
attribute: .Top,
multiplier: 1.0,
constant: -UIScreen.mainScreen().bounds.height
)
self.addConstraints(backgroundConstraints)
self.addConstraint(topConstraint)
self.backgroundView = backgroundView
// Status Label
let statusLabel = createStatusLabel(status, isVisualEffect: false)
self.addSubview(statusLabel)
let statusLeft = NSLayoutConstraint(
item: statusLabel,
attribute: .Left,
relatedBy: .Equal,
toItem: self,
attribute: .LeftMargin,
multiplier: 1.0,
constant: 0.0
)
let statusRight = NSLayoutConstraint(
item: statusLabel,
attribute: .Right,
relatedBy: .Equal,
toItem: self,
attribute: .RightMargin,
multiplier: 1.0,
constant: 0.0
)
let statusBottom = NSLayoutConstraint(
item: statusLabel,
attribute: .Bottom,
relatedBy: .Equal,
toItem: self,
attribute: .Bottom,
multiplier: 1.0,
constant: -statusBottomMargin
)
self.addConstraints([statusLeft, statusRight, statusBottom])
self.statusLabel = statusLabel
}
self.layoutIfNeeded()
let tapRecognizer = UITapGestureRecognizer(target: self, action: "up:")
self.addGestureRecognizer(tapRecognizer)
let panRecognizer = UIPanGestureRecognizer(target: self, action: "pan:")
self.addGestureRecognizer(panRecognizer)
}
private func createStatusLabel(status: String, isVisualEffect: Bool) -> UILabel {
let label = UILabel(frame: CGRectZero)
label.setTranslatesAutoresizingMaskIntoConstraints(false)
label.numberOfLines = 0
label.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
label.textAlignment = .Center
label.text = status
if !isVisualEffect { label.textColor = UIColor.whiteColor() }
return label
}
}
extension Drop {
func up(sender: AnyObject) {
self.up()
}
func pan(sender: AnyObject) {
let pan = sender as! UIPanGestureRecognizer
switch pan.state {
case .Began:
stopUpTimer()
startTop = topConstraint.constant
case .Changed:
let location = pan.locationInView(Drop.window())
let translation = pan.translationInView(Drop.window())
let top = startTop! + translation.y
if top > 0.0 {
topConstraint.constant = top * 0.2
} else {
topConstraint.constant = top
}
case .Ended:
startTop = nil
if topConstraint.constant < 0.0 {
scheduleUpTimer(0.0, interval: 0.1)
} else {
scheduleUpTimer(4.0)
topConstraint.constant = 0.0
UIView.animateWithDuration(
NSTimeInterval(0.1),
delay: NSTimeInterval(0.0),
options: .AllowUserInteraction | .CurveEaseOut,
animations: { [weak self] () -> Void in
if let s = self { s.layoutIfNeeded() }
}, completion: nil
)
}
case .Failed, .Cancelled:
startTop = nil
scheduleUpTimer(2.0)
case .Possible: break
}
}
}
extension Drop {
private class func window() -> UIWindow {
return UIApplication.sharedApplication().keyWindow!
}
private class func statusBarHeight() -> CGFloat {
return UIApplication.sharedApplication().statusBarFrame.size.height
}
}
| mit | f9d94b8393a116331cb5d9a7ceab673c | 33.932432 | 163 | 0.542682 | 5.381679 | false | false | false | false |
lukya/HackerRankSwift | HackerRankPlayground/HackerRankPlayground/Algorithms/Warmup/6-PlusMinus.swift | 1 | 891 | //
// 6-PlusMinus.swift
// HackerRankPlayground
//
// Created by Swapnil Luktuke on 8/5/16.
// Copyright © 2016 lukya. All rights reserved.
//
import Foundation
func plusMinus () {
/// get number of elements
let n = Int(readLine()!)!
/// read array and map the elements to integer
let arr = readLine()!.characters.split(" ").map{Int(String($0))!}
/// initialize counts to 0
var positives : Int = 0
var negatives : Int = 0
var zeroes : Int = 0
/// loop through and update the counts
for i in 0 ..< n {
if arr[i] > 0 {
positives += 1
}
else if arr[i] < 0 {
negatives += 1
}
else {
zeroes += 1
}
}
/// print the fractions
print(Double(positives)/Double(n))
print(Double(negatives)/Double(n))
print(Double(zeroes)/Double(n))
}
| unlicense | f636627432dc1f2f3d537e3436a33d51 | 20.707317 | 69 | 0.54382 | 3.819742 | false | false | false | false |
practicalswift/swift | test/NameBinding/Dependencies/private-subscript.swift | 13 | 830 | // RUN: %target-swift-frontend -emit-silgen -primary-file %s %S/Inputs/InterestingType.swift -DOLD -emit-reference-dependencies-path %t.swiftdeps -module-name main | %FileCheck %s -check-prefix=CHECK-OLD
// RUN: %FileCheck -check-prefix=CHECK-DEPS %s < %t.swiftdeps
// RUN: %target-swift-frontend -emit-silgen -primary-file %s %S/Inputs/InterestingType.swift -DNEW -emit-reference-dependencies-path %t.swiftdeps -module-name main | %FileCheck %s -check-prefix=CHECK-NEW
// RUN: %FileCheck -check-prefix=CHECK-DEPS %s < %t.swiftdeps
struct Wrapper {
fileprivate subscript() -> InterestingType { fatalError() }
}
// CHECK-OLD: sil_global @$s4main1x{{[^ ]+}} : $Int
// CHECK-NEW: sil_global @$s4main1x{{[^ ]+}} : $Double
public var x = Wrapper()[] + 0
// CHECK-DEPS-LABEL: depends-top-level:
// CHECK-DEPS: - "InterestingType"
| apache-2.0 | 9faecb9a3920d1089bc4ae06ccafdcc8 | 50.875 | 203 | 0.708434 | 3.167939 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/BlockchainComponentLibrary/Sources/BlockchainComponentLibrary/3 - Compositions/PrimaryNavigation.swift | 1 | 15423 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import SwiftUI
#if canImport(UIKit)
import UIKit
#endif
// MARK: - Public
extension View {
/// Replacement for setting navigation items using component library styling.
/// - Parameters:
/// - icon: Optional leading icon displayed in the navigation bar
/// - title: Optional title displayed in the navigation bar
/// - trailing: Trailing views in navigation bar. Commonly `IconButton`, or `TextButton`.
/// Multiple views are auto distributed along an HStack.
/// - Returns: `self`, otherwise unmodified.
public func primaryNavigation<Leading: View, Trailing: View>(
@ViewBuilder leading: @escaping () -> Leading,
title: String? = nil,
@ViewBuilder trailing: @escaping () -> Trailing
) -> some View {
modifier(
PrimaryNavigationModifier<Leading, Trailing>(
leading: leading,
title: title,
trailing: trailing
)
)
}
/// Replacement for setting navigation items using component library styling.
/// - Parameters:
/// - title: Optional title displayed in the navigation bar
/// - trailing: Trailing views in navigation bar. Commonly `IconButton`, or `TextButton`.
/// Multiple views are auto distributed along an HStack.
/// - Returns: `self`, otherwise unmodified.
public func primaryNavigation<Trailing: View>(
title: String? = nil,
@ViewBuilder trailing: @escaping () -> Trailing
) -> some View {
modifier(
PrimaryNavigationModifier<EmptyView, Trailing>(
leading: nil,
title: title,
trailing: trailing
)
)
}
/// Replacement for setting navigation items using component library styling.
///
/// This function is specifically available for setting the title without changing trailing views.
///
/// - Parameters:
/// - icon: Optional leading icon displayed in the navigation bar
/// - title: Optional title displayed in the navigation bar
/// - Returns: `self`, otherwise unmodified.
public func primaryNavigation<Leading: View>(
@ViewBuilder leading: @escaping () -> Leading,
title: String?
) -> some View {
modifier(
PrimaryNavigationModifier<Leading, EmptyView>(
leading: leading,
title: title,
trailing: nil
)
)
}
/// Replacement for setting navigation items using component library styling.
///
/// This function is specifically available for setting the title without changing trailing views.
///
/// - Returns: `self`, otherwise unmodified.
public func primaryNavigation() -> some View {
modifier(
PrimaryNavigationModifier<EmptyView, EmptyView>(
leading: nil,
title: nil,
trailing: nil
)
)
}
/// Replacement for setting navigation items using component library styling.
///
/// This function is specifically available for setting the title without changing trailing views.
///
/// - Parameters:
/// - title: Optional title displayed in the navigation bar
/// - Returns: `self`, otherwise unmodified.
public func primaryNavigation(
title: String?
) -> some View {
modifier(
PrimaryNavigationModifier<EmptyView, EmptyView>(
leading: nil,
title: title,
trailing: nil
)
)
}
}
/// Replacement for `NavigationView` to fix a bug on iPhone
public struct PrimaryNavigationView<Content: View>: View {
@ViewBuilder private let content: Content
/// A `NavigationView` with a custom designed navigation bar
/// - Parameters:
/// - content: Content of navigation view. Use `.primaryNavigation(...)` for titles and trailing items, and `PrimaryNavigationLink` for links.
public init(@ViewBuilder _ content: () -> Content) {
self.content = content()
}
public var body: some View {
#if os(macOS)
NavigationView {
content
}
#else
NavigationView {
content
.background(NavigationConfigurator())
}
// StackNavigationViewStyle is to fix a bug on iPhone where the following
// console error appears, and the navigation bar goes blank.
//
// > [Assert] displayModeButtonItem is internally managed and not exposed for DoubleColumn style. Returning an empty, disconnected UIBarButtonItem to fulfill the non-null contract.
//
// If we add iPad layout, we can re-enable other styles conditionally.
.navigationViewStyle(StackNavigationViewStyle())
#endif
}
}
/// Replacement for `NavigationLink` which provides some private functionality for detecting
/// being a pushed view in the destination.
public struct PrimaryNavigationLink<Destination: View, Label: View>: View {
let destination: Destination
let isActive: Binding<Bool>?
@ViewBuilder let label: () -> Label
public init(
destination: Destination,
isActive: Binding<Bool>? = nil,
@ViewBuilder label: @escaping () -> Label
) {
self.destination = destination
self.isActive = isActive
self.label = label
}
public var body: some View {
if let isActive = isActive {
NavigationLink(
destination: destination,
isActive: isActive,
label: label
)
} else {
NavigationLink(
destination: destination,
label: label
)
}
}
}
extension EnvironmentValues {
/// Accent color for navigation bar back button in `PrimaryNavigation`
///
/// Defaults to `.semantic.primary` (Wallet)
public var navigationBackButtonColor: Color {
get { self[NavigationBackButtonColor.self] }
set { self[NavigationBackButtonColor.self] = newValue }
}
}
// MARK: - Private
/// Modifier which applies custom navigation bar styling
private struct PrimaryNavigationModifier<Leading: View, Trailing: View>: ViewModifier {
let leading: (() -> Leading)?
let title: String?
let trailing: (() -> Trailing)?
func body(content: Content) -> some View {
#if os(macOS)
content
.ifLet(title) { view, title in
view.navigationTitle(title)
}
.toolbar {
ToolbarItem {
leading?()
trailing?()
}
}
#else
content
.navigationBarTitleDisplayMode(.inline)
.ifLet(title) { view, title in
view.navigationTitle(title)
}
.navigationBarItems(
leading: HStack(spacing: Spacing.padding3) {
leading?()
},
trailing: HStack(spacing: Spacing.padding3) {
trailing?()
}
.accentColor(.semantic.muted)
)
#endif
}
}
/// Environment key set by `PrimaryNavigation`
private struct NavigationBackButtonColor: EnvironmentKey {
static var defaultValue = Color.semantic.primary
}
#if canImport(UIKit)
public private(set) var currentNavigationController: UINavigationController?
/// Customizing `UINavigationController` without using `UIAppearance`
private struct NavigationConfigurator: UIViewControllerRepresentable {
@Environment(\.navigationBackButtonColor) var navigationBackButtonColor
func makeUIViewController(context: Context) -> NavigationConfiguratorViewController {
NavigationConfiguratorViewController(
navigationBackButtonColor: navigationBackButtonColor
)
}
func updateUIViewController(_ uiViewController: NavigationConfiguratorViewController, context: Context) {
uiViewController.navigationBackButtonColor = navigationBackButtonColor
}
// swiftlint:disable line_length
final class NavigationConfiguratorViewController: UIViewController, UINavigationControllerDelegate, UIGestureRecognizerDelegate {
var navigationBackButtonColor: Color {
didSet { styleNavigationBar() }
}
init(navigationBackButtonColor: Color) {
self.navigationBackButtonColor = navigationBackButtonColor
super.init(nibName: nil, bundle: nil)
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
currentNavigationController = navigationController
}
// Must wait until the view controller is added to the hierarchy to customize the navigation bar.
// Otherwise `navigationController?` is nil.
override func didMove(toParent parent: UIViewController?) {
super.didMove(toParent: parent)
if let navigationItem = parent?.navigationItem {
navigationItem.backButtonDisplayMode = .minimal
}
styleNavigationBar()
guard navigationController?.delegate !== self else {
return
}
__proxy = __proxy ?? navigationController?.delegate
navigationController?.delegate = self
navigationController?.interactivePopGestureRecognizer?.delegate = self
}
func styleChildViewController(_ viewController: UIViewController) {
// Hide the back button title
viewController.navigationItem.backButtonDisplayMode = .minimal
}
// Customize the styling of the navigation bar
private func styleNavigationBar() {
if let navigationBar = navigationController?.navigationBar {
navigationBar.tintColor = UIColor(
Color(
light: .palette.grey400,
dark: .palette.grey400
)
)
navigationBar.barTintColor = UIColor(.semantic.background)
navigationBar.backgroundColor = UIColor(.semantic.background)
let image = Icon.chevronLeft.uiImage?
.padded(by: UIEdgeInsets(top: 0, left: Spacing.padding1, bottom: 0, right: 0))
navigationBar.backIndicatorImage = image
navigationBar.backIndicatorTransitionMaskImage = image
navigationBar.tintColor = UIColor(navigationBackButtonColor)
navigationBar.largeTitleTextAttributes = [
.foregroundColor: UIColor(.semantic.title),
.font: Typography.title2.uiFont as Any
]
navigationBar.titleTextAttributes = [
.foregroundColor: UIColor(.semantic.title),
.font: Typography.title3.uiFont as Any
]
UITableView.appearance().backgroundColor = .clear
}
}
weak var __proxy: UINavigationControllerDelegate?
func navigationController(
_ navigationController: UINavigationController,
willShow viewController: UIViewController,
animated: Bool
) {
__proxy?.navigationController?(navigationController, willShow: viewController, animated: animated)
styleChildViewController(viewController)
}
func navigationController(
_ navigationController: UINavigationController,
didShow viewController: UIViewController,
animated: Bool
) {
__proxy?.navigationController?(navigationController, didShow: viewController, animated: animated)
}
func navigationControllerSupportedInterfaceOrientations(
_ navigationController: UINavigationController
) -> UIInterfaceOrientationMask {
__proxy?.navigationControllerSupportedInterfaceOrientations?(navigationController) ?? .all
}
func navigationControllerPreferredInterfaceOrientationForPresentation(
_ navigationController: UINavigationController
) -> UIInterfaceOrientation {
__proxy?.navigationControllerPreferredInterfaceOrientationForPresentation?(
navigationController
) ?? .portrait
}
func navigationController(
_ navigationController: UINavigationController,
interactionControllerFor animationController: UIViewControllerAnimatedTransitioning
) -> UIViewControllerInteractiveTransitioning? {
__proxy?.navigationController?(navigationController, interactionControllerFor: animationController)
}
func navigationController(
_ navigationController: UINavigationController,
animationControllerFor operation: UINavigationController.Operation,
from fromVC: UIViewController,
to toVC: UIViewController
) -> UIViewControllerAnimatedTransitioning? {
__proxy?.navigationController?(
navigationController,
animationControllerFor: operation,
from: fromVC,
to: toVC
)
}
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
(navigationController?.viewControllers.count ?? 0) > 1
}
}
}
#endif
// MARK: - Previews
struct PrimaryNavigation_Previews: PreviewProvider {
static var previews: some View {
PreviewContainer()
.previewDisplayName("Wallet")
PreviewContainer()
.environment(\.navigationBackButtonColor, Color(light: .palette.dark400, dark: .palette.white))
.previewDisplayName("Exchange")
}
struct PreviewContainer: View {
@State var isActive: Bool = false
var body: some View {
PrimaryNavigationView {
primary
}
}
@ViewBuilder var primary: some View {
PrimaryNavigationLink(
destination: secondary,
isActive: $isActive,
label: { Text("Foo") }
)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color.green)
.primaryNavigation(
leading: {
IconButton(icon: .user) {}
},
title: "Foo",
trailing: {
IconButton(icon: .qrCode) {}
}
)
}
@ViewBuilder var secondary: some View {
ScrollView {
LazyVStack {
ForEach(0..<100, id: \.self) { value in
Text("\(value)")
.frame(maxWidth: .infinity)
.background(Color.blue)
}
}
}
.primaryNavigation(title: "Bar") {
IconButton(icon: .chat) {}
}
}
}
}
| lgpl-3.0 | 81de512b8450dcbbcc9604caa4c18b52 | 33.970522 | 188 | 0.59869 | 5.975203 | false | false | false | false |
faimin/ZDOpenSourceDemo | ZDOpenSourceSwiftDemo/Pods/GDPerformanceView-Swift/GDPerformanceView-Swift/GDPerformanceMonitoring/PerformanceView.swift | 1 | 13058 | //
// Copyright © 2017 Gavrilov Daniil
//
// 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
// MARK: Class Definition
/// Performance view. Displays performance information above status bar. Appearance and output can be changed via properties.
internal class PerformanceView: UIWindow, PerformanceViewConfigurator {
// MARK: Structs
private struct Constants {
static let prefferedHeight: CGFloat = 20.0
static let borderWidth: CGFloat = 1.0
static let cornerRadius: CGFloat = 5.0
static let pointSize: CGFloat = 8.0
static let defaultStatusBarHeight: CGFloat = 20.0
static let safeAreaInsetDifference: CGFloat = 11.0
}
// MARK: Public Properties
/// Allows to change the format of the displayed information.
public var options = PerformanceMonitor.DisplayOptions.default {
didSet {
self.configureStaticInformation()
}
}
public var userInfo = PerformanceMonitor.UserInfo.none {
didSet {
self.configureUserInformation()
}
}
/// Allows to change the appearance of the displayed information.
public var style = PerformanceMonitor.Style.dark {
didSet {
self.configureView(withStyle: self.style)
}
}
/// Allows to add gesture recognizers to the view.
public var interactors: [UIGestureRecognizer]? {
didSet {
self.configureView(withInteractors: self.interactors)
}
}
// MARK: Private Properties
private let monitoringTextLabel = MarginLabel()
private var staticInformation: String?
private var userInformation: String?
// MARK: Init Methods & Superclass Overriders
required internal init() {
super.init(frame: PerformanceView.windowFrame(withPrefferedHeight: Constants.prefferedHeight))
self.configureWindow()
self.configureMonitoringTextLabel()
self.subscribeToNotifications()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func layoutSubviews() {
super.layoutSubviews()
self.layoutWindow()
}
override func becomeKey() {
self.isHidden = true
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1)) {
self.showViewAboveStatusBarIfNeeded()
}
}
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
guard let interactors = self.interactors, interactors.count > 0 else {
return false
}
return super.point(inside: point, with: event)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
// MARK: Public Methods
internal extension PerformanceView {
/// Hides monitoring view.
func hide() {
self.monitoringTextLabel.isHidden = true
}
/// Shows monitoring view.
func show() {
self.monitoringTextLabel.isHidden = false
}
/// Updates monitoring label with performance report.
///
/// - Parameter report: Performance report.
func update(withPerformanceReport report: PerformanceReport) {
var monitoringTexts: [String] = []
if self.options.contains(.performance) {
let performance = String(format: "CPU: %.1f%%, FPS: %d", report.cpuUsage, report.fps)
monitoringTexts.append(performance)
}
if self.options.contains(.memory) {
let bytesInMegabyte = 1024.0 * 1024.0
let usedMemory = Double(report.memoryUsage.used) / bytesInMegabyte
let totalMemory = Double(report.memoryUsage.total) / bytesInMegabyte
let memory = String(format: "%.1f of %.0f MB used", usedMemory, totalMemory)
monitoringTexts.append(memory)
}
if let staticInformation = self.staticInformation {
monitoringTexts.append(staticInformation)
}
if let userInformation = self.userInformation {
monitoringTexts.append(userInformation)
}
self.monitoringTextLabel.text = (monitoringTexts.count > 0 ? monitoringTexts.joined(separator: "\n") : nil)
self.showViewAboveStatusBarIfNeeded()
self.layoutMonitoringLabel()
}
}
// MARK: Notifications & Observers
private extension PerformanceView {
func applicationWillChangeStatusBarFrame(notification: Notification) {
self.layoutWindow()
}
}
// MARK: Configurations
private extension PerformanceView {
func configureWindow() {
self.rootViewController = WindowViewController()
self.windowLevel = UIWindow.Level.statusBar + 1.0
self.backgroundColor = .clear
self.clipsToBounds = true
self.isHidden = true
}
func configureMonitoringTextLabel() {
self.monitoringTextLabel.textAlignment = NSTextAlignment.center
self.monitoringTextLabel.numberOfLines = 0
self.monitoringTextLabel.clipsToBounds = true
self.addSubview(self.monitoringTextLabel)
}
func configureStaticInformation() {
var staticInformations: [String] = []
if self.options.contains(.application) {
let applicationVersion = self.applicationVersion()
staticInformations.append(applicationVersion)
}
if self.options.contains(.device) {
let deviceModel = self.deviceModel()
staticInformations.append(deviceModel)
}
if self.options.contains(.system) {
let systemVersion = self.systemVersion()
staticInformations.append(systemVersion)
}
self.staticInformation = (staticInformations.count > 0 ? staticInformations.joined(separator: ", ") : nil)
}
func configureUserInformation() {
var staticInformation: String?
switch self.userInfo {
case .none:
break
case .custom(let string):
staticInformation = string
}
self.userInformation = staticInformation
}
func subscribeToNotifications() {
NotificationCenter.default.addObserver(forName: UIApplication.willChangeStatusBarFrameNotification, object: nil, queue: .main) { [weak self] (notification) in
self?.applicationWillChangeStatusBarFrame(notification: notification)
}
}
func configureView(withStyle style: PerformanceMonitor.Style) {
switch style {
case .dark:
self.monitoringTextLabel.backgroundColor = .black
self.monitoringTextLabel.layer.borderColor = UIColor.white.cgColor
self.monitoringTextLabel.layer.borderWidth = Constants.borderWidth
self.monitoringTextLabel.layer.cornerRadius = Constants.cornerRadius
self.monitoringTextLabel.textColor = .white
self.monitoringTextLabel.font = UIFont.systemFont(ofSize: Constants.pointSize)
case .light:
self.monitoringTextLabel.backgroundColor = .white
self.monitoringTextLabel.layer.borderColor = UIColor.black.cgColor
self.monitoringTextLabel.layer.borderWidth = Constants.borderWidth
self.monitoringTextLabel.layer.cornerRadius = Constants.cornerRadius
self.monitoringTextLabel.textColor = .black
self.monitoringTextLabel.font = UIFont.systemFont(ofSize: Constants.pointSize)
case .custom(let backgroundColor, let borderColor, let borderWidth, let cornerRadius, let textColor, let font):
self.monitoringTextLabel.backgroundColor = backgroundColor
self.monitoringTextLabel.layer.borderColor = borderColor.cgColor
self.monitoringTextLabel.layer.borderWidth = borderWidth
self.monitoringTextLabel.layer.cornerRadius = cornerRadius
self.monitoringTextLabel.textColor = textColor
self.monitoringTextLabel.font = font
}
}
func configureView(withInteractors interactors: [UIGestureRecognizer]?) {
if let recognizers = self.gestureRecognizers {
for recognizer in recognizers {
self.removeGestureRecognizer(recognizer)
}
}
if let recognizers = interactors {
for recognizer in recognizers {
self.addGestureRecognizer(recognizer)
}
}
}
}
// MARK: Layout View
private extension PerformanceView {
func layoutWindow() {
self.frame = PerformanceView.windowFrame(withPrefferedHeight: self.monitoringTextLabel.bounds.height)
self.layoutMonitoringLabel()
}
func layoutMonitoringLabel() {
let windowWidth = self.bounds.width
let windowHeight = self.bounds.height
let labelSize = self.monitoringTextLabel.sizeThatFits(CGSize(width: windowWidth, height: CGFloat.greatestFiniteMagnitude))
if windowHeight != labelSize.height {
self.frame = PerformanceView.windowFrame(withPrefferedHeight: self.monitoringTextLabel.bounds.height)
}
self.monitoringTextLabel.frame = CGRect(x: (windowWidth - labelSize.width) / 2.0, y: (windowHeight - labelSize.height) / 2.0, width: labelSize.width, height: labelSize.height)
}
}
// MARK: Support Methods
private extension PerformanceView {
func showViewAboveStatusBarIfNeeded() {
guard UIApplication.shared.applicationState == UIApplication.State.active, self.canBeVisible(), self.isHidden else {
return
}
self.isHidden = false
}
func applicationVersion() -> String {
var applicationVersion = "<null>"
var applicationBuildNumber = "<null>"
if let infoDictionary = Bundle.main.infoDictionary {
if let versionNumber = infoDictionary["CFBundleShortVersionString"] as? String {
applicationVersion = versionNumber
}
if let buildNumber = infoDictionary["CFBundleVersion"] as? String {
applicationBuildNumber = buildNumber
}
}
return "app v\(applicationVersion) (\(applicationBuildNumber))"
}
func deviceModel() -> String {
var systemInfo = utsname()
uname(&systemInfo)
let machineMirror = Mirror(reflecting: systemInfo.machine)
let model = machineMirror.children.reduce("") { identifier, element in
guard let value = element.value as? Int8, value != 0 else {
return identifier
}
return identifier + String(UnicodeScalar(UInt8(value)))
}
return model
}
func systemVersion() -> String {
let systemName = UIDevice.current.systemName
let systemVersion = UIDevice.current.systemVersion
return "\(systemName) v\(systemVersion)"
}
func canBeVisible() -> Bool {
if let window = UIApplication.shared.keyWindow, window.isKeyWindow, !window.isHidden {
return true
}
return false
}
}
// MARK: Class Methods
private extension PerformanceView {
class func windowFrame(withPrefferedHeight height: CGFloat) -> CGRect {
guard let window = UIApplication.shared.delegate?.window as? UIWindow else {
return .zero
}
var topInset: CGFloat = 0.0
if #available(iOS 11.0, *), let safeAreaTop = window.rootViewController?.view.safeAreaInsets.top {
if safeAreaTop > 0.0 {
if safeAreaTop > Constants.defaultStatusBarHeight {
topInset = safeAreaTop - Constants.safeAreaInsetDifference
} else {
topInset = safeAreaTop - Constants.defaultStatusBarHeight
}
} else {
topInset = safeAreaTop
}
}
return CGRect(x: 0.0, y: topInset, width: window.bounds.width, height: height)
}
}
| mit | 0a782d9cc40a83f479ff4656c0db1b29 | 35.472067 | 183 | 0.651528 | 5.179294 | false | false | false | false |
Miguel-Herrero/Swift | Landmarks/Landmarks/Profile/ProfileHost.swift | 1 | 1296 | //
// ProfileHost.swift
// Landmarks
//
// Created by Miguel Herrero Baena on 20/06/2019.
// Copyright © 2019 Miguel Herrero Baena. All rights reserved.
//
import SwiftUI
struct ProfileHost : View {
@Environment(\.editMode) var mode
@State private var profile = Profile.default
@State private var draftProfile = Profile.default
var body: some View {
VStack(alignment: .leading, spacing: 20) {
HStack {
if self.mode?.value == .active {
Button(action: {
self.profile = self.draftProfile
self.mode?.animation().value = .inactive
}) {
Text("Done")
}
}
Spacer()
EditButton()
}
if self.mode?.value == .inactive {
ProfileSummary(profile: profile)
} else {
ProfileEditor(profile: $draftProfile)
.onDisappear {
self.draftProfile = self.profile
}
}
}
.padding()
}
}
#if DEBUG
struct ProfileHost_Previews : PreviewProvider {
static var previews: some View {
ProfileHost()
}
}
#endif
| gpl-3.0 | d0422866a90ece13f9675bd27d960967 | 23.903846 | 64 | 0.488803 | 4.886792 | false | false | false | false |
guidomb/PortalView | Sources/Components/Table.swift | 2 | 4461 | //
// Table.swift
// PortalView
//
// Created by Guido Marucci Blas on 1/27/17.
//
//
import Foundation
public enum TableItemSelectionStyle {
case none
case `default`
case blue
case gray
}
public struct TableProperties<MessageType> {
public var items: [TableItemProperties<MessageType>]
public var showsVerticalScrollIndicator: Bool
public var showsHorizontalScrollIndicator: Bool
fileprivate init(
items: [TableItemProperties<MessageType>] = [],
showsVerticalScrollIndicator: Bool = true,
showsHorizontalScrollIndicator: Bool = true) {
self.items = items
self.showsHorizontalScrollIndicator = showsHorizontalScrollIndicator
self.showsVerticalScrollIndicator = showsVerticalScrollIndicator
}
public func map<NewMessageType>(_ transform: @escaping (MessageType) -> NewMessageType) -> TableProperties<NewMessageType> {
return TableProperties<NewMessageType>(items: self.items.map { $0.map(transform) })
}
}
public struct TableItemProperties<MessageType> {
public typealias Renderer = (UInt) -> TableItemRender<MessageType>
public let height: UInt
public let onTap: MessageType?
public let selectionStyle: TableItemSelectionStyle
public let renderer: Renderer
fileprivate init(
height: UInt,
onTap: MessageType?,
selectionStyle: TableItemSelectionStyle,
renderer: @escaping Renderer) {
self.height = height
self.onTap = onTap
self.selectionStyle = selectionStyle
self.renderer = renderer
}
}
extension TableItemProperties {
public func map<NewMessageType>(_ transform: @escaping (MessageType) -> NewMessageType) -> TableItemProperties<NewMessageType> {
return TableItemProperties<NewMessageType>(
height: height,
onTap: self.onTap.map(transform),
selectionStyle: selectionStyle,
renderer: { self.renderer($0).map(transform) }
)
}
}
public struct TableItemRender<MessageType> {
public let component: Component<MessageType>
public let typeIdentifier: String
public init(component: Component<MessageType>, typeIdentifier: String) {
self.component = component
self.typeIdentifier = typeIdentifier
}
}
extension TableItemRender {
public func map<NewMessageType>(_ transform: @escaping (MessageType) -> NewMessageType) -> TableItemRender<NewMessageType> {
return TableItemRender<NewMessageType>(
component: self.component.map(transform),
typeIdentifier: self.typeIdentifier
)
}
}
public func table<MessageType>(
properties: TableProperties<MessageType> = TableProperties(),
style: StyleSheet<TableStyleSheet> = TableStyleSheet.default,
layout: Layout = layout()) -> Component<MessageType> {
return .table(properties, style, layout)
}
public func table<MessageType>(
items: [TableItemProperties<MessageType>] = [],
style: StyleSheet<TableStyleSheet> = TableStyleSheet.default,
layout: Layout = layout()) -> Component<MessageType> {
return .table(TableProperties(items: items), style, layout)
}
public func tableItem<MessageType>(
height: UInt,
onTap: MessageType? = .none,
selectionStyle: TableItemSelectionStyle = .`default`,
renderer: @escaping TableItemProperties<MessageType>.Renderer) -> TableItemProperties<MessageType> {
return TableItemProperties(height: height, onTap: onTap, selectionStyle: selectionStyle, renderer: renderer)
}
public func properties<MessageType>(configure: (inout TableProperties<MessageType>) -> ()) -> TableProperties<MessageType> {
var properties = TableProperties<MessageType>()
configure(&properties)
return properties
}
// MARK: - Style sheet
public struct TableStyleSheet {
public static let `default` = StyleSheet<TableStyleSheet>(component: TableStyleSheet())
public var separatorColor: Color
fileprivate init(separatorColor: Color = Color.clear) {
self.separatorColor = separatorColor
}
}
public func tableStyleSheet(configure: (inout BaseStyleSheet, inout TableStyleSheet) -> () = { _ in }) -> StyleSheet<TableStyleSheet> {
var base = BaseStyleSheet()
var component = TableStyleSheet()
configure(&base, &component)
return StyleSheet(component: component, base: base)
}
| mit | 4514d3a95ec6fb41b81de7a130a4a769 | 29.554795 | 135 | 0.696032 | 5.001121 | false | false | false | false |
angmu/SwiftPlayCode | 00-Swift基础语法/09-swift类的定义.playground/Contents.swift | 1 | 914 | //: Playground - noun: a place where people can play
import Foundation
class Student : NSObject {
// 存储属性
var name: String?
var mathScore: Double = 0.0
var chineseScore: Double = 0.0
var averageScore:Double {
get {
return (mathScore + chineseScore) * 0.5
}
set {
print(newValue)
}
}
static var courseCount: Int = 0
}
//
//var stu = Student()
//stu.name = "junchen"
//stu.chineseScore = 89
//stu.mathScore = 92
//
//print(stu.averageScore)
//print(Student.courseCount)
class Person : NSObject {
var name: String? {
willSet {
print(name)
print(newValue)
}
didSet {
print(name)
print(oldValue)
}
}
var age : Int = 0
}
let p = Person()
p.name = "why"
print(p.name)
p.age = 18
| mit | d6a1d91288ce1f4b9e7eb7dfd723d0c8 | 15.178571 | 52 | 0.50883 | 3.759336 | false | false | false | false |
beeth0ven/BNKit | BNKit/Source/Rx+/SingleApiPaginationViewModel.swift | 1 | 2180 | //
// SingleApiPaginationViewModel.swift
// BNKit
//
// Created by luojie on 2017/5/19.
// Copyright © 2017年 LuoJie. All rights reserved.
//
import RxSwift
public struct SingleApiPaginationViewModel<Item, Param, Response, Cursor> {
// Input
public let reloadTrigger: PublishSubject<Void>
public let loadNextPageTrigger: PublishSubject<Void>
// Output
public let items: Observable<[Item]>
public let isReloading: Observable<Bool>
public let reloadError: Observable<Error>
public let isLoadingNextPage: Observable<Bool>
public let loadNextPageError: Observable<Error>
public let isEmpty: Observable<Bool>
public let hasNextPage: Observable<Bool>
public init(
getReloadParam: @escaping () -> Param,
mapToReloadResponse: @escaping (Param) -> Observable<Response>,
mapToReloadCursor: @escaping (Response) -> Cursor?,
mapToReloadItems: @escaping (Response) -> [Item],
getNextPageParam: @escaping (Cursor) -> Param
) {
(
self.reloadTrigger,
self.loadNextPageTrigger,
self.items,
self.isReloading,
self.reloadError,
self.isLoadingNextPage,
self.loadNextPageError,
self.isEmpty,
self.hasNextPage
) = SingleApiPaginationViewModel.create(
getReloadParam: getReloadParam,
mapToReloadResponse: mapToReloadResponse,
mapToReloadCursor: mapToReloadCursor,
mapToReloadItems: mapToReloadItems,
getNextPageParam: getNextPageParam,
mapToNextPageResponse: mapToReloadResponse,
mapToNextPageCursor: mapToReloadCursor,
mapToNextPageItems: mapToReloadItems
)
}
}
extension SingleApiPaginationViewModel: IsPaginationViewModel {
public typealias IsItem = Item
public typealias IsReloadParam = Param
public typealias IsReloadResponse = Response
public typealias IsCursor = Cursor
public typealias IsNextPageParam = Param
public typealias IsNextPageResponse = Response
}
| mit | 8a566b3feef0a9e653599f690b06700c | 31.492537 | 75 | 0.65503 | 5.027714 | false | false | false | false |
asashin227/LNKLabel | Example/LNKLabel/ViewController.swift | 1 | 4646 | //
// ViewController.swift
// LinkLabel
//
// Created by asashin227 on 09/13/2017.
// Copyright (c) 2017 asashin227. All rights reserved.
//
import UIKit
import LNKLabel
import SafariServices
import MessageUI
// MARK: - Custom pattern
public class CustomPattern: Pattern {
override public var regString: String {
return "hogehoge"
}
}
// MARK: - ViewController
class ViewController: UIViewController {
lazy var linkLabel: LNKLabel = {
let label = LNKLabel()
label.linkColor = .red
label.linkPatterns = [MailPattern(), URLPattern(), PhonePattern()]
label.linkPatterns?.append(CustomPattern())
label.text = "https://github.com/asashin227/LNKLabel\n09012345678\[email protected]\nhogehogefugafuga"
label.delegate = self
label.numberOfLines = 0
label.frame.size.width = UIScreen.main.bounds.size.width
label.sizeToFit()
return label
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
linkLabel.center = self.view.center
self.view.addSubview(linkLabel)
if self.traitCollection.forceTouchCapability == .available {
self.registerForPreviewing(with: self, sourceView: linkLabel)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController {
func getSafariViewController(with urlString: String) -> SFSafariViewController? {
guard let url = NSURL.init(string: urlString) else { return nil }
let safari = SFSafariViewController(url: url as URL)
return safari
}
func getMailViewController(with toAddress: String) -> MFMailComposeViewController? {
if !MFMailComposeViewController.canSendMail() { return nil }
let mailVC = MFMailComposeViewController()
mailVC.mailComposeDelegate = self
mailVC.setToRecipients([toAddress])
return mailVC
}
}
extension ViewController {
func openURL(_ urlString: String) {
guard let safari = getSafariViewController(with: urlString) else { return }
self.present(safari, animated: true, completion: nil)
}
func call(phoneNumberString: String) {
let scheme: URL = URL(string: String(format: "tel:%@", phoneNumberString))!
UIApplication.shared.openURL(scheme)
}
func openMailUI(mailAddressString: String) {
guard let mailVC = getMailViewController(with: mailAddressString) else { return }
self.present(mailVC, animated: true, completion: nil)
}
}
// MARK: - LNKLabelDelegate
extension ViewController: LNKLabelDelegate {
func didTaped(label: LNKLabel, pattern: Pattern, matchText: String, range: NSRange) {
switch pattern {
case is URLPattern:
print("taped url: \(matchText)")
openURL(matchText)
case is MailPattern:
print("taped mail address: \(matchText)")
openMailUI(mailAddressString: matchText)
case is PhonePattern:
print("taped phone number: \(matchText)")
call(phoneNumberString: matchText)
default:
print("taped custom pattern: \(matchText)")
}
}
}
// MARK: - MFMailComposeViewControllerDelegate
extension ViewController: MFMailComposeViewControllerDelegate {
public func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
controller.dismiss(animated: true)
}
}
// MARK: - UIViewControllerPreviewingDelegate
extension ViewController: UIViewControllerPreviewingDelegate {
func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
guard let hitLink = linkLabel.hitLink(at: location) else { return nil }
switch hitLink.pattern {
case is URLPattern:
guard let safari = getSafariViewController(with: hitLink.touchedText) else { return nil }
return safari
case is MailPattern:
guard let mailVC = getMailViewController(with: hitLink.touchedText) else { return nil }
return mailVC
default:
return nil
}
}
func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
self.present(viewControllerToCommit, animated: true)
}
}
| mit | 4731257bd260eccc0016183b4ae60d57 | 32.666667 | 143 | 0.670684 | 5.017279 | false | false | false | false |
acastano/swift-bootstrap | networkingkit/Sources/Classes/JSON/JSONValueExtractor.swift | 1 | 1940 |
import Foundation
private let kFirstKeyIndex = 0
private let kSecondKeyIndex = 1
open class JSONValueExtractor {
open class func valueForKeyPath(_ keyPath: String, data:[String:AnyObject]?) -> AnyObject? {
let keys = keyPath.characters.split {$0 == "."} .map(String.init)
let value = valueWithKeyPaths(keys, data:data as AnyObject?)
return value
}
class func valueWithKeyPaths(_ keys:[String], data:AnyObject?) -> AnyObject? {
var result: AnyObject?
var keysToRemove = 0
if let data = data as? [String:AnyObject] {
if keys.count > 0 {
keysToRemove = 1
let key = keys[kFirstKeyIndex];
result = data[key]
}
} else if let data = data as? [[String:AnyObject]] {
if keys.count > 1 {
keysToRemove = 2
let key = keys[kFirstKeyIndex]
let value = keys[kSecondKeyIndex]
result = valueForArray(data, key:key, value:value)
}
}
if keys.count == keysToRemove || data == nil {
return result
} else {
let newKeys = Array(keys[keysToRemove...keys.count - 1])
return valueWithKeyPaths(newKeys, data:result)
}
}
class func valueForArray(_ array:[[String:AnyObject]], key: String, value:String) -> AnyObject? {
let results = array.filter() { let result = $0[key] as? String; return result == value; }
return results.first as AnyObject?
}
}
| apache-2.0 | 03e57222d74b525b74aa80730f3786b2 | 24.866667 | 101 | 0.45567 | 5.480226 | false | false | false | false |
ello/ello-ios | Sources/Controllers/AutoComplete/AutoCompleteCellPresenter.swift | 1 | 732 | ////
/// AutoCompleteCellPresenter.swift
//
struct AutoCompleteCellPresenter {
static func configure(_ cell: AutoCompleteCell, item: AutoCompleteItem) {
if let resultName = item.result.name {
switch item.type {
case .emoji:
cell.name = ":\(resultName):"
case .username:
cell.name = "@\(resultName)"
case .location:
cell.name = resultName
}
}
else {
cell.name = ""
}
if let image = item.result.image {
cell.avatar.setUserAvatar(image)
}
else if let url = item.result.url {
cell.avatar.setUserAvatarURL(url)
}
}
}
| mit | da7a493a567e290424b9001eb2bde532 | 24.241379 | 77 | 0.504098 | 4.66242 | false | false | false | false |
raymondshadow/SwiftDemo | SwiftApp/SwiftApp/RxSwift/Demo1/Service/SearchService.swift | 1 | 1507 | //
// SearchService.swift
// SwiftApp
//
// Created by wuyp on 2017/7/4.
// Copyright © 2017年 raymond. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
class SearchService {
static let shareInstance = SearchService()
private init() {}
func getHeros() -> Observable<[Hero]> {
let herosString = Bundle.main.path(forResource: "heros", ofType: "plist")
let herosArray = NSArray(contentsOfFile: herosString!) as! Array<[String: String]>
var heros = [Hero]()
for heroDic in herosArray {
let hero = Hero(name: heroDic["name"]!, desc: heroDic["intro"]!, icon: heroDic["icon"]!)
heros.append(hero)
}
return Observable.just(heros)
.observeOn(MainScheduler.instance)
}
func getHeros(withName name: String) -> Observable<[Hero]> {
if name == "" {
return getHeros()
}
let herosString = Bundle.main.path(forResource: "heros", ofType: "plist")
let herosArray = NSArray(contentsOfFile: herosString!) as! Array<[String: String]>
var heros = [Hero]()
for heroDic in herosArray {
if heroDic["name"]!.contains(name) {
let hero = Hero(name: heroDic["name"]!, desc: heroDic["intro"]!, icon: heroDic["icon"]!)
heros.append(hero)
}
}
return Observable.just(heros)
.observeOn(MainScheduler.instance)
}
}
| apache-2.0 | 6b1a60f2564f7eca58da59fb24c4e741 | 28.490196 | 104 | 0.575798 | 4.154696 | false | false | false | false |
brave/browser-ios | ThirdParty/SQLiteSwift/Sources/SQLite/Typed/CoreFunctions.swift | 2 | 27220 | //
// SQLite.swift
// https://github.com/stephencelis/SQLite.swift
// Copyright © 2014-2015 Stephen Celis.
//
// 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
extension ExpressionType where UnderlyingType : Number {
/// Builds a copy of the expression wrapped with the `abs` function.
///
/// let x = Expression<Int>("x")
/// x.absoluteValue
/// // abs("x")
///
/// - Returns: A copy of the expression wrapped with the `abs` function.
public var absoluteValue : Expression<UnderlyingType> {
return "abs".wrap(self)
}
}
extension ExpressionType where UnderlyingType : _OptionalType, UnderlyingType.WrappedType : Number {
/// Builds a copy of the expression wrapped with the `abs` function.
///
/// let x = Expression<Int?>("x")
/// x.absoluteValue
/// // abs("x")
///
/// - Returns: A copy of the expression wrapped with the `abs` function.
public var absoluteValue : Expression<UnderlyingType> {
return "abs".wrap(self)
}
}
extension ExpressionType where UnderlyingType == Double {
/// Builds a copy of the expression wrapped with the `round` function.
///
/// let salary = Expression<Double>("salary")
/// salary.round()
/// // round("salary")
/// salary.round(2)
/// // round("salary", 2)
///
/// - Returns: A copy of the expression wrapped with the `round` function.
public func round(_ precision: Int? = nil) -> Expression<UnderlyingType> {
guard let precision = precision else {
return wrap([self])
}
return wrap([self, Int(precision)])
}
}
extension ExpressionType where UnderlyingType == Double? {
/// Builds a copy of the expression wrapped with the `round` function.
///
/// let salary = Expression<Double>("salary")
/// salary.round()
/// // round("salary")
/// salary.round(2)
/// // round("salary", 2)
///
/// - Returns: A copy of the expression wrapped with the `round` function.
public func round(_ precision: Int? = nil) -> Expression<UnderlyingType> {
guard let precision = precision else {
return wrap(self)
}
return wrap([self, Int(precision)])
}
}
extension ExpressionType where UnderlyingType : Value, UnderlyingType.Datatype == Int64 {
/// Builds an expression representing the `random` function.
///
/// Expression<Int>.random()
/// // random()
///
/// - Returns: An expression calling the `random` function.
public static func random() -> Expression<UnderlyingType> {
return "random".wrap([])
}
}
extension ExpressionType where UnderlyingType == Data {
/// Builds an expression representing the `randomblob` function.
///
/// Expression<Int>.random(16)
/// // randomblob(16)
///
/// - Parameter length: Length in bytes.
///
/// - Returns: An expression calling the `randomblob` function.
public static func random(_ length: Int) -> Expression<UnderlyingType> {
return "randomblob".wrap([])
}
/// Builds an expression representing the `zeroblob` function.
///
/// Expression<Int>.allZeros(16)
/// // zeroblob(16)
///
/// - Parameter length: Length in bytes.
///
/// - Returns: An expression calling the `zeroblob` function.
public static func allZeros(_ length: Int) -> Expression<UnderlyingType> {
return "zeroblob".wrap([])
}
/// Builds a copy of the expression wrapped with the `length` function.
///
/// let data = Expression<NSData>("data")
/// data.length
/// // length("data")
///
/// - Returns: A copy of the expression wrapped with the `length` function.
public var length: Expression<Int> {
return wrap(self)
}
}
extension ExpressionType where UnderlyingType == Data? {
/// Builds a copy of the expression wrapped with the `length` function.
///
/// let data = Expression<NSData?>("data")
/// data.length
/// // length("data")
///
/// - Returns: A copy of the expression wrapped with the `length` function.
public var length: Expression<Int?> {
return wrap(self)
}
}
extension ExpressionType where UnderlyingType == String {
/// Builds a copy of the expression wrapped with the `length` function.
///
/// let name = Expression<String>("name")
/// name.length
/// // length("name")
///
/// - Returns: A copy of the expression wrapped with the `length` function.
public var length: Expression<Int> {
return wrap(self)
}
/// Builds a copy of the expression wrapped with the `lower` function.
///
/// let name = Expression<String>("name")
/// name.lowercaseString
/// // lower("name")
///
/// - Returns: A copy of the expression wrapped with the `lower` function.
public var lowercaseString: Expression<UnderlyingType> {
return "lower".wrap(self)
}
/// Builds a copy of the expression wrapped with the `upper` function.
///
/// let name = Expression<String>("name")
/// name.uppercaseString
/// // lower("name")
///
/// - Returns: A copy of the expression wrapped with the `upper` function.
public var uppercaseString: Expression<UnderlyingType> {
return "upper".wrap(self)
}
/// Builds a copy of the expression appended with a `LIKE` query against the
/// given pattern.
///
/// let email = Expression<String>("email")
/// email.like("%@example.com")
/// // "email" LIKE '%@example.com'
/// email.like("99\\%@%", escape: "\\")
/// // "email" LIKE '99\%@%' ESCAPE '\'
///
/// - Parameters:
///
/// - pattern: A pattern to match.
///
/// - escape: An (optional) character designated for escaping
/// pattern-matching characters (*i.e.*, the `%` and `_` characters).
///
/// - Returns: A copy of the expression appended with a `LIKE` query against
/// the given pattern.
public func like(_ pattern: String, escape character: Character? = nil) -> Expression<Bool> {
guard let character = character else {
return "LIKE".infix(self, pattern)
}
return Expression("(\(template) LIKE ? ESCAPE ?)", bindings + [pattern, String(character)])
}
/// Builds a copy of the expression appended with a `LIKE` query against the
/// given pattern.
///
/// let email = Expression<String>("email")
/// let pattern = Expression<String>("pattern")
/// email.like(pattern)
/// // "email" LIKE "pattern"
///
/// - Parameters:
///
/// - pattern: A pattern to match.
///
/// - escape: An (optional) character designated for escaping
/// pattern-matching characters (*i.e.*, the `%` and `_` characters).
///
/// - Returns: A copy of the expression appended with a `LIKE` query against
/// the given pattern.
public func like(_ pattern: Expression<String>, escape character: Character? = nil) -> Expression<Bool> {
guard let character = character else {
return "LIKE".infix(self, pattern)
}
let like: Expression<Bool> = "LIKE".infix(self, pattern, wrap: false)
return Expression("(\(like.template) ESCAPE ?)", like.bindings + [String(character)])
}
/// Builds a copy of the expression appended with a `GLOB` query against the
/// given pattern.
///
/// let path = Expression<String>("path")
/// path.glob("*.png")
/// // "path" GLOB '*.png'
///
/// - Parameter pattern: A pattern to match.
///
/// - Returns: A copy of the expression appended with a `GLOB` query against
/// the given pattern.
public func glob(_ pattern: String) -> Expression<Bool> {
return "GLOB".infix(self, pattern)
}
/// Builds a copy of the expression appended with a `MATCH` query against
/// the given pattern.
///
/// let title = Expression<String>("title")
/// title.match("swift AND programming")
/// // "title" MATCH 'swift AND programming'
///
/// - Parameter pattern: A pattern to match.
///
/// - Returns: A copy of the expression appended with a `MATCH` query
/// against the given pattern.
public func match(_ pattern: String) -> Expression<Bool> {
return "MATCH".infix(self, pattern)
}
/// Builds a copy of the expression appended with a `REGEXP` query against
/// the given pattern.
///
/// - Parameter pattern: A pattern to match.
///
/// - Returns: A copy of the expression appended with a `REGEXP` query
/// against the given pattern.
public func regexp(_ pattern: String) -> Expression<Bool> {
return "REGEXP".infix(self, pattern)
}
/// Builds a copy of the expression appended with a `COLLATE` clause with
/// the given sequence.
///
/// let name = Expression<String>("name")
/// name.collate(.Nocase)
/// // "name" COLLATE NOCASE
///
/// - Parameter collation: A collating sequence.
///
/// - Returns: A copy of the expression appended with a `COLLATE` clause
/// with the given sequence.
public func collate(_ collation: Collation) -> Expression<UnderlyingType> {
return "COLLATE".infix(self, collation)
}
/// Builds a copy of the expression wrapped with the `ltrim` function.
///
/// let name = Expression<String>("name")
/// name.ltrim()
/// // ltrim("name")
/// name.ltrim([" ", "\t"])
/// // ltrim("name", ' \t')
///
/// - Parameter characters: A set of characters to trim.
///
/// - Returns: A copy of the expression wrapped with the `ltrim` function.
public func ltrim(_ characters: Set<Character>? = nil) -> Expression<UnderlyingType> {
guard let characters = characters else {
return wrap(self)
}
return wrap([self, String(characters)])
}
/// Builds a copy of the expression wrapped with the `rtrim` function.
///
/// let name = Expression<String>("name")
/// name.rtrim()
/// // rtrim("name")
/// name.rtrim([" ", "\t"])
/// // rtrim("name", ' \t')
///
/// - Parameter characters: A set of characters to trim.
///
/// - Returns: A copy of the expression wrapped with the `rtrim` function.
public func rtrim(_ characters: Set<Character>? = nil) -> Expression<UnderlyingType> {
guard let characters = characters else {
return wrap(self)
}
return wrap([self, String(characters)])
}
/// Builds a copy of the expression wrapped with the `trim` function.
///
/// let name = Expression<String>("name")
/// name.trim()
/// // trim("name")
/// name.trim([" ", "\t"])
/// // trim("name", ' \t')
///
/// - Parameter characters: A set of characters to trim.
///
/// - Returns: A copy of the expression wrapped with the `trim` function.
public func trim(_ characters: Set<Character>? = nil) -> Expression<UnderlyingType> {
guard let characters = characters else {
return wrap([self])
}
return wrap([self, String(characters)])
}
/// Builds a copy of the expression wrapped with the `replace` function.
///
/// let email = Expression<String>("email")
/// email.replace("@mac.com", with: "@icloud.com")
/// // replace("email", '@mac.com', '@icloud.com')
///
/// - Parameters:
///
/// - pattern: A pattern to match.
///
/// - replacement: The replacement string.
///
/// - Returns: A copy of the expression wrapped with the `replace` function.
public func replace(_ pattern: String, with replacement: String) -> Expression<UnderlyingType> {
return "replace".wrap([self, pattern, replacement])
}
public func substring(_ location: Int, length: Int? = nil) -> Expression<UnderlyingType> {
guard let length = length else {
return "substr".wrap([self, location])
}
return "substr".wrap([self, location, length])
}
public subscript(range: Range<Int>) -> Expression<UnderlyingType> {
return substring(range.lowerBound, length: range.upperBound - range.lowerBound)
}
}
extension ExpressionType where UnderlyingType == String? {
/// Builds a copy of the expression wrapped with the `length` function.
///
/// let name = Expression<String?>("name")
/// name.length
/// // length("name")
///
/// - Returns: A copy of the expression wrapped with the `length` function.
public var length: Expression<Int?> {
return wrap(self)
}
/// Builds a copy of the expression wrapped with the `lower` function.
///
/// let name = Expression<String?>("name")
/// name.lowercaseString
/// // lower("name")
///
/// - Returns: A copy of the expression wrapped with the `lower` function.
public var lowercaseString: Expression<UnderlyingType> {
return "lower".wrap(self)
}
/// Builds a copy of the expression wrapped with the `upper` function.
///
/// let name = Expression<String?>("name")
/// name.uppercaseString
/// // lower("name")
///
/// - Returns: A copy of the expression wrapped with the `upper` function.
public var uppercaseString: Expression<UnderlyingType> {
return "upper".wrap(self)
}
/// Builds a copy of the expression appended with a `LIKE` query against the
/// given pattern.
///
/// let email = Expression<String?>("email")
/// email.like("%@example.com")
/// // "email" LIKE '%@example.com'
/// email.like("99\\%@%", escape: "\\")
/// // "email" LIKE '99\%@%' ESCAPE '\'
///
/// - Parameters:
///
/// - pattern: A pattern to match.
///
/// - escape: An (optional) character designated for escaping
/// pattern-matching characters (*i.e.*, the `%` and `_` characters).
///
/// - Returns: A copy of the expression appended with a `LIKE` query against
/// the given pattern.
public func like(_ pattern: String, escape character: Character? = nil) -> Expression<Bool?> {
guard let character = character else {
return "LIKE".infix(self, pattern)
}
return Expression("(\(template) LIKE ? ESCAPE ?)", bindings + [pattern, String(character)])
}
/// Builds a copy of the expression appended with a `LIKE` query against the
/// given pattern.
///
/// let email = Expression<String>("email")
/// let pattern = Expression<String>("pattern")
/// email.like(pattern)
/// // "email" LIKE "pattern"
///
/// - Parameters:
///
/// - pattern: A pattern to match.
///
/// - escape: An (optional) character designated for escaping
/// pattern-matching characters (*i.e.*, the `%` and `_` characters).
///
/// - Returns: A copy of the expression appended with a `LIKE` query against
/// the given pattern.
public func like(_ pattern: Expression<String>, escape character: Character? = nil) -> Expression<Bool?> {
guard let character = character else {
return "LIKE".infix(self, pattern)
}
let like: Expression<Bool> = "LIKE".infix(self, pattern, wrap: false)
return Expression("(\(like.template) ESCAPE ?)", like.bindings + [String(character)])
}
/// Builds a copy of the expression appended with a `GLOB` query against the
/// given pattern.
///
/// let path = Expression<String?>("path")
/// path.glob("*.png")
/// // "path" GLOB '*.png'
///
/// - Parameter pattern: A pattern to match.
///
/// - Returns: A copy of the expression appended with a `GLOB` query against
/// the given pattern.
public func glob(_ pattern: String) -> Expression<Bool?> {
return "GLOB".infix(self, pattern)
}
/// Builds a copy of the expression appended with a `MATCH` query against
/// the given pattern.
///
/// let title = Expression<String?>("title")
/// title.match("swift AND programming")
/// // "title" MATCH 'swift AND programming'
///
/// - Parameter pattern: A pattern to match.
///
/// - Returns: A copy of the expression appended with a `MATCH` query
/// against the given pattern.
public func match(_ pattern: String) -> Expression<Bool> {
return "MATCH".infix(self, pattern)
}
/// Builds a copy of the expression appended with a `REGEXP` query against
/// the given pattern.
///
/// - Parameter pattern: A pattern to match.
///
/// - Returns: A copy of the expression appended with a `REGEXP` query
/// against the given pattern.
public func regexp(_ pattern: String) -> Expression<Bool?> {
return "REGEXP".infix(self, pattern)
}
/// Builds a copy of the expression appended with a `COLLATE` clause with
/// the given sequence.
///
/// let name = Expression<String?>("name")
/// name.collate(.Nocase)
/// // "name" COLLATE NOCASE
///
/// - Parameter collation: A collating sequence.
///
/// - Returns: A copy of the expression appended with a `COLLATE` clause
/// with the given sequence.
public func collate(_ collation: Collation) -> Expression<UnderlyingType> {
return "COLLATE".infix(self, collation)
}
/// Builds a copy of the expression wrapped with the `ltrim` function.
///
/// let name = Expression<String?>("name")
/// name.ltrim()
/// // ltrim("name")
/// name.ltrim([" ", "\t"])
/// // ltrim("name", ' \t')
///
/// - Parameter characters: A set of characters to trim.
///
/// - Returns: A copy of the expression wrapped with the `ltrim` function.
public func ltrim(_ characters: Set<Character>? = nil) -> Expression<UnderlyingType> {
guard let characters = characters else {
return wrap(self)
}
return wrap([self, String(characters)])
}
/// Builds a copy of the expression wrapped with the `rtrim` function.
///
/// let name = Expression<String?>("name")
/// name.rtrim()
/// // rtrim("name")
/// name.rtrim([" ", "\t"])
/// // rtrim("name", ' \t')
///
/// - Parameter characters: A set of characters to trim.
///
/// - Returns: A copy of the expression wrapped with the `rtrim` function.
public func rtrim(_ characters: Set<Character>? = nil) -> Expression<UnderlyingType> {
guard let characters = characters else {
return wrap(self)
}
return wrap([self, String(characters)])
}
/// Builds a copy of the expression wrapped with the `trim` function.
///
/// let name = Expression<String?>("name")
/// name.trim()
/// // trim("name")
/// name.trim([" ", "\t"])
/// // trim("name", ' \t')
///
/// - Parameter characters: A set of characters to trim.
///
/// - Returns: A copy of the expression wrapped with the `trim` function.
public func trim(_ characters: Set<Character>? = nil) -> Expression<UnderlyingType> {
guard let characters = characters else {
return wrap(self)
}
return wrap([self, String(characters)])
}
/// Builds a copy of the expression wrapped with the `replace` function.
///
/// let email = Expression<String?>("email")
/// email.replace("@mac.com", with: "@icloud.com")
/// // replace("email", '@mac.com', '@icloud.com')
///
/// - Parameters:
///
/// - pattern: A pattern to match.
///
/// - replacement: The replacement string.
///
/// - Returns: A copy of the expression wrapped with the `replace` function.
public func replace(_ pattern: String, with replacement: String) -> Expression<UnderlyingType> {
return "replace".wrap([self, pattern, replacement])
}
/// Builds a copy of the expression wrapped with the `substr` function.
///
/// let title = Expression<String?>("title")
/// title.substr(-100)
/// // substr("title", -100)
/// title.substr(0, length: 100)
/// // substr("title", 0, 100)
///
/// - Parameters:
///
/// - location: The substring’s start index.
///
/// - length: An optional substring length.
///
/// - Returns: A copy of the expression wrapped with the `substr` function.
public func substring(_ location: Int, length: Int? = nil) -> Expression<UnderlyingType> {
guard let length = length else {
return "substr".wrap([self, location])
}
return "substr".wrap([self, location, length])
}
/// Builds a copy of the expression wrapped with the `substr` function.
///
/// let title = Expression<String?>("title")
/// title[0..<100]
/// // substr("title", 0, 100)
///
/// - Parameter range: The character index range of the substring.
///
/// - Returns: A copy of the expression wrapped with the `substr` function.
public subscript(range: Range<Int>) -> Expression<UnderlyingType> {
return substring(range.lowerBound, length: range.upperBound - range.lowerBound)
}
}
extension Collection where Iterator.Element : Value {
/// Builds a copy of the expression prepended with an `IN` check against the
/// collection.
///
/// let name = Expression<String>("name")
/// ["alice", "betty"].contains(name)
/// // "name" IN ('alice', 'betty')
///
/// - Parameter pattern: A pattern to match.
///
/// - Returns: A copy of the expression prepended with an `IN` check against
/// the collection.
public func contains(_ expression: Expression<Iterator.Element>) -> Expression<Bool> {
let templates = [String](repeating: "?", count: count).joined(separator: ", ")
return "IN".infix(expression, Expression<Void>("(\(templates))", map { $0.datatypeValue }))
}
/// Builds a copy of the expression prepended with an `IN` check against the
/// collection.
///
/// let name = Expression<String?>("name")
/// ["alice", "betty"].contains(name)
/// // "name" IN ('alice', 'betty')
///
/// - Parameter pattern: A pattern to match.
///
/// - Returns: A copy of the expression prepended with an `IN` check against
/// the collection.
public func contains(_ expression: Expression<Iterator.Element?>) -> Expression<Bool?> {
let templates = [String](repeating: "?", count: count).joined(separator: ", ")
return "IN".infix(expression, Expression<Void>("(\(templates))", map { $0.datatypeValue }))
}
}
extension String {
/// Builds a copy of the expression appended with a `LIKE` query against the
/// given pattern.
///
/// let email = "[email protected]"
/// let pattern = Expression<String>("pattern")
/// email.like(pattern)
/// // '[email protected]' LIKE "pattern"
///
/// - Parameters:
///
/// - pattern: A pattern to match.
///
/// - escape: An (optional) character designated for escaping
/// pattern-matching characters (*i.e.*, the `%` and `_` characters).
///
/// - Returns: A copy of the expression appended with a `LIKE` query against
/// the given pattern.
public func like(_ pattern: Expression<String>, escape character: Character? = nil) -> Expression<Bool> {
guard let character = character else {
return "LIKE".infix(self, pattern)
}
let like: Expression<Bool> = "LIKE".infix(self, pattern, wrap: false)
return Expression("(\(like.template) ESCAPE ?)", like.bindings + [String(character)])
}
}
/// Builds a copy of the given expressions wrapped with the `ifnull` function.
///
/// let name = Expression<String?>("name")
/// name ?? "An Anonymous Coward"
/// // ifnull("name", 'An Anonymous Coward')
///
/// - Parameters:
///
/// - optional: An optional expression.
///
/// - defaultValue: A fallback value for when the optional expression is
/// `nil`.
///
/// - Returns: A copy of the given expressions wrapped with the `ifnull`
/// function.
public func ??<V : Value>(optional: Expression<V?>, defaultValue: V) -> Expression<V> {
return "ifnull".wrap([optional, defaultValue])
}
/// Builds a copy of the given expressions wrapped with the `ifnull` function.
///
/// let nick = Expression<String?>("nick")
/// let name = Expression<String>("name")
/// nick ?? name
/// // ifnull("nick", "name")
///
/// - Parameters:
///
/// - optional: An optional expression.
///
/// - defaultValue: A fallback expression for when the optional expression is
/// `nil`.
///
/// - Returns: A copy of the given expressions wrapped with the `ifnull`
/// function.
public func ??<V : Value>(optional: Expression<V?>, defaultValue: Expression<V>) -> Expression<V> {
return "ifnull".wrap([optional, defaultValue])
}
/// Builds a copy of the given expressions wrapped with the `ifnull` function.
///
/// let nick = Expression<String?>("nick")
/// let name = Expression<String?>("name")
/// nick ?? name
/// // ifnull("nick", "name")
///
/// - Parameters:
///
/// - optional: An optional expression.
///
/// - defaultValue: A fallback expression for when the optional expression is
/// `nil`.
///
/// - Returns: A copy of the given expressions wrapped with the `ifnull`
/// function.
public func ??<V : Value>(optional: Expression<V?>, defaultValue: Expression<V?>) -> Expression<V> {
return "ifnull".wrap([optional, defaultValue])
}
| mpl-2.0 | a8d5bb5964b90d15263fd2200e239fc8 | 34.717848 | 110 | 0.589374 | 4.294935 | false | false | false | false |
PrashantMangukiya/SwiftUIDemo | Demo6-UISlider/Demo6-UISlider/ViewController.swift | 1 | 1475 | //
// ViewController.swift
// Demo6-UISlider
//
// Created by Prashant on 27/09/15.
// Copyright © 2015 PrashantKumar Mangukiya. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
// outlet & action - slider1
@IBOutlet var mySlider1: UISlider!
@IBAction func mySlider1Action(_ sender: UISlider) {
self.myLabel1.text = "\(Int(sender.value))"
}
// outlet - label1
@IBOutlet var myLabel1: UILabel!
// outlet & action - slider2
@IBOutlet var mySlider2: UISlider!
@IBAction func mySlider2Action(_ sender: UISlider) {
let currentValue = CGFloat(sender.value)
self.myLabel2.font = UIFont(name: self.myLabel2.font.fontName, size: currentValue)
}
// outlet - label2
@IBOutlet var myLabel2: UILabel!
// MARK: - View functions
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// set value for label1
self.myLabel1.text = "\(Int(mySlider1.value))"
// set font size for label2
let currentValue = CGFloat(self.mySlider2.value)
self.myLabel2.font = UIFont(name: self.myLabel2.font.fontName, size: currentValue)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 192b9a870a83e247e910c2c87699a5c8 | 24.859649 | 98 | 0.628223 | 4.360947 | false | false | false | false |
lobodart/CheatyXML | CheatyXML/CXMLParser.swift | 1 | 3784 | //
// CXMLParser.swift
// CheatyXML
//
// Created by Louis BODART on 14/03/2015.
// Copyright (c) 2015 Louis BODART. All rights reserved.
//
import Foundation
// MARK: - CXMLParser Class
public class CXMLParser: NSObject, XMLParserDelegate {
open var rootElement: CXMLTag! {
get {
return self._rootElement
}
}
fileprivate let _xmlParser: Foundation.XMLParser!
fileprivate var _pointerTree: [OpaquePointer]!
fileprivate var _rootElement: CXMLTag!
fileprivate var _allocatedPointersList: [UnsafeMutablePointer<CXMLTag>] = []
public init?(contentsOfURL: URL) {
self._xmlParser = Foundation.XMLParser(contentsOf: contentsOfURL)
super.init()
if !self.initXMLParser() {
return nil
}
}
public init?(data: Data?) {
guard let data = data else {
return nil
}
self._xmlParser = Foundation.XMLParser(data: data)
super.init()
guard let _ = self._xmlParser else {
return nil
}
if !self.initXMLParser() {
return nil
}
}
public convenience init?(string: String) {
self.init(data: string.data(using: String.Encoding.utf8))
}
deinit {
for pointer in self._allocatedPointersList {
pointer.deallocate()
}
}
fileprivate func initXMLParser() -> Bool {
guard let _ = self._xmlParser else {
return false
}
self._xmlParser.delegate = self
return self._xmlParser.parse()
}
public final func parser(_ parser: Foundation.XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
let newElement: CXMLTag = CXMLTag(tagName: elementName)
if self._rootElement == nil {
self._rootElement = newElement
}
if !attributeDict.isEmpty {
newElement._attributes = attributeDict.map({ (name: String, value: String) -> CXMLAttribute in
return CXMLAttribute(name: name, value: value)
})
}
if self._pointerTree == nil {
self._pointerTree = []
} else {
let nps = UnsafeMutablePointer<CXMLTag>(self._pointerTree.last!)
newElement._parentElement = nps.pointee
nps.pointee.addSubElement(newElement)
}
let ps = UnsafeMutablePointer<CXMLTag>.allocate(capacity: 1)
ps.initialize(to: newElement)
self._allocatedPointersList.append(ps)
let cps = OpaquePointer(ps)
self._pointerTree.append(cps)
}
public final func parser(_ parser: Foundation.XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
self._pointerTree.removeLast()
}
public final func parser(_ parser: Foundation.XMLParser, foundCharacters string: String) {
let nps = UnsafeMutablePointer<CXMLTag>(self._pointerTree.last!)
var tmpString: String! = nps.pointee._content ?? ""
tmpString! += string
let regex: NSRegularExpression = try! NSRegularExpression(pattern: "[^\\n\\s]+", options: [])
if regex.matches(in: tmpString, options: [], range: NSMakeRange(0, tmpString.count)).count <= 0 {
tmpString = nil
}
nps.pointee._content = tmpString
}
open subscript(tagName: String) -> CXMLTag! {
return self._rootElement[tagName]
}
open subscript(tagName: String, index: Int) -> CXMLTag! {
return self._rootElement[tagName, index]
}
}
| mit | 7f4248d0569481161a7471b59caf2900 | 30.016393 | 197 | 0.591966 | 4.712329 | false | false | false | false |
apple/swift | test/SourceKit/CodeComplete/complete_sequence_accessor.swift | 22 | 4448 | class Foo {
var x: Int = 0
var y: Int = 0
func fooMethod() {}
}
struct Bar {
var a: Int = 0
var b: Int = 0
func barMethod() {}
}
var globalValImplicit: Foo {
Bar().
}
var globalValGetSet: Foo {
get { Foo(). }
set { Bar(). }
}
enum S {
var foo: Foo
var bar: Bar
var propertyImplicit: Foo {
foo.
}
var propertyGetSet: Foo {
get { bar. }
set { foo. }
}
subscript(idx: Foo) -> Foo {
idx.
}
subscript(idx: Bar) -> Foo {
get { idx. }
set { idx. }
}
}
// Enabled.
// RUN: %sourcekitd-test \
// RUN: -req=complete -pos=12:9 %s -- %s -parse-as-library == \
// RUN: -req=complete -pos=15:15 %s -- %s -parse-as-library == \
// RUN: -req=complete -pos=16:15 %s -- %s -parse-as-library == \
// RUN: -req=complete -pos=23:9 %s -- %s -parse-as-library == \
// RUN: -req=complete -pos=26:15 %s -- %s -parse-as-library == \
// RUN: -req=complete -pos=27:15 %s -- %s -parse-as-library == \
// RUN: -req=complete -pos=30:9 %s -- %s -parse-as-library == \
// RUN: -req=complete -pos=33:15 %s -- %s -parse-as-library == \
// RUN: -req=complete -pos=34:15 %s -- %s -parse-as-library == \
// RUN: -req=complete -pos=12:1 %s -- %s -parse-as-library == \
// RUN: -req=complete -pos=23:1 %s -- %s -parse-as-library == \
// RUN: -req=complete -pos=16:1 %s -- %s -parse-as-library > %t.response
// RUN: %FileCheck --check-prefix=RESULT %s < %t.response
// globalValImplicit
// RESULT-LABEL: key.results: [
// RESULT-DAG: key.name: "barMethod()"
// RESULT-DAG: key.name: "self"
// RESULT-DAG: key.name: "a"
// RESULT-DAG: key.name: "b"
// RESULT: ]
// RESULT-NOT: key.reusingastcontext: 1
// globalValGetSet(get)
// RESULT-LABEL: key.results: [
// RESULT-DAG: key.name: "fooMethod()"
// RESULT-DAG: key.name: "self"
// RESULT-DAG: key.name: "x"
// RESULT-DAG: key.name: "y"
// RESULT: ]
// RESULT: key.reusingastcontext: 1
// globalValGetSet(set)
// RESULT-LABEL: key.results: [
// RESULT-DAG: key.name: "barMethod()"
// RESULT-DAG: key.name: "self"
// RESULT-DAG: key.name: "a"
// RESULT-DAG: key.name: "b"
// RESULT: ]
// RESULT: key.reusingastcontext: 1
// propertyImplicit
// RESULT-LABEL: key.results: [
// RESULT-DAG: key.name: "fooMethod()"
// RESULT-DAG: key.name: "self"
// RESULT-DAG: key.name: "x"
// RESULT-DAG: key.name: "y"
// RESULT: ]
// RESULT: key.reusingastcontext: 1
// propertyGetSet(get)
// RESULT-LABEL: key.results: [
// RESULT-DAG: key.name: "barMethod()"
// RESULT-DAG: key.name: "self"
// RESULT-DAG: key.name: "a"
// RESULT-DAG: key.name: "b"
// RESULT: ]
// RESULT: key.reusingastcontext: 1
// propertyGetSet(set)
// RESULT-LABEL: key.results: [
// RESULT-DAG: key.name: "fooMethod()"
// RESULT-DAG: key.name: "self"
// RESULT-DAG: key.name: "x"
// RESULT-DAG: key.name: "y"
// RESULT: ]
// RESULT: key.reusingastcontext: 1
// subscript(implicit getter)
// RESULT-LABEL: key.results: [
// RESULT-DAG: key.name: "fooMethod()"
// RESULT-DAG: key.name: "self"
// RESULT-DAG: key.name: "x"
// RESULT-DAG: key.name: "y"
// RESULT: ]
// RESULT: key.reusingastcontext: 1
// subscript(get)
// RESULT-LABEL: key.results: [
// RESULT-DAG: key.name: "barMethod()"
// RESULT-DAG: key.name: "self"
// RESULT-DAG: key.name: "a"
// RESULT-DAG: key.name: "b"
// RESULT: ]
// RESULT: key.reusingastcontext: 1
// subscript(set)
// RESULT-LABEL: key.results: [
// RESULT-DAG: key.name: "barMethod()"
// RESULT-DAG: key.name: "self"
// RESULT-DAG: key.name: "a"
// RESULT-DAG: key.name: "b"
// RESULT: ]
// RESULT: key.reusingastcontext: 1
// accessor top (global var)
// RESULT-LABEL: key.results: [
// RESULT-DAG: key.description: "get"
// RESULT-DAG: key.description: "set"
// RESULT-DAG: key.description: "willSet"
// RESULT-DAG: key.description: "didSet"
// RESULT-DAG: key.description: "Foo"
// RESULT: ]
// RESULT: key.reusingastcontext: 1
// accessor top (property)
// RESULT-LABEL: key.results: [
// RESULT-DAG: key.description: "get"
// RESULT-DAG: key.description: "set"
// RESULT-DAG: key.description: "willSet"
// RESULT-DAG: key.description: "didSet"
// RESULT-DAG: key.description: "Foo"
// RESULT: ]
// RESULT: key.reusingastcontext: 1
// accessor second (global var)
// RESULT-LABEL: key.results: [
// RESULT-NOT: key.description: "Foo"
// RESULT-DAG: key.description: "get"
// RESULT-DAG: key.description: "set"
// RESULT-DAG: key.description: "willSet"
// RESULT-DAG: key.description: "didSet"
// RESULT: ]
// RESULT-NOT: key.reusingastcontext: 1
| apache-2.0 | ad7bb7f07b1cd86e925e9d3926cef807 | 26.121951 | 74 | 0.621178 | 2.761018 | false | false | false | false |
ProteanBear/ProteanBear_Swift | library/pb.swift.data/PbDataAppController.swift | 1 | 28023 | //
// PbDataAppController.swift
// swiftPbTest
// Description:应用数据层控制器
// Created by Maqiang on 15/6/15.
// Copyright (c) 2015年 Maqiang. All rights reserved.
//
import Foundation
import UIKit
import CoreLocation
import ReachabilitySwift
import CryptoSwift
/**枚举类型,数据更新模式
* first:第一次载入数据
* update:更新数据
* nextPage:下一页数据
*/
public enum PbDataUpdateMode:Int
{
case first,update,nextPage
}
/**枚举类型,数据获取模式
* fromNet:网络获取
* fromLocalOrNet:先从缓存读取,无缓存则从网络读取
* fromLocal:本地缓存获取
*/
public enum PbDataGetMode:Int
{
case fromNet,fromLocalOrNet,fromLocal
}
/**枚举类型,定位获取模式
* none:不获取
* inUse:使用时获取
* always:一直获取
*/
public enum PbDataLocationMode:Int
{
case none,inUse,always
}
/// 应用数据层控制器
open class PbDataAppController:NSObject,CLLocationManagerDelegate
{
/*-----------------------开始:静态常量*/
/// KEY_RESPONSE:控制器返回内容
open static let KEY_RESPONSE="PbDataResponse"
/// KEY_NETWORK:控制器返回内容-网络状态
open static let KEY_NETWORK="network"
/// KEY_SUCCESS:控制器返回内容-请求状态
open static let KEY_SUCCESS="success"
/*-----------------------结束:静态常量*/
/*-----------------------开始:静态方法,实现单例模式*/
open class var instance:PbDataAppController{
return Inner.instance;
}
struct Inner
{
static let instance:PbDataAppController=PbDataAppController();
}
/*-----------------------结束:静态方法,实现单例模式*/
/*-----------------------开始:声明属性*/
//调试定位信息
fileprivate let logPre="PbDataAppController:";
/// config:Plist保存的相关URL访问及数据存储的配置
var config=NSDictionary()
/// 服务地址(server)
var server=""
/// 备用服务地址(alterServer)
var alterServer=""
/// 全局参数字典(global)
var global:NSDictionary?=NSDictionary()
/// 访问协议(netProtocol)
var netProtocol="HTTPS"
/// 请求方式(method)
var method="POST"
/// 返回类型(responseType)
var responseType="JSON"
/// 超时时间(timeOut,单位为秒)
var timeOut=10
/// HTTPS协议下服务端的证书资源名称
var certNameOfServer=""
/// HTTPS协议下客户端的证书资源名称
var certNameOfClient=""
/// HTTPS协议下客户端的证书访问密码
var certPassOfClient=""
/// 是否启用本地缓存(isActiveLocalCache)
var isActiveLocalCache=true
/// 本地目录(cachePath)
var cachePath="localCache"
/// 资源子目录(resourceSubPath)
var resourceSubPath="resources"
/// 数据子目录(dataSubPath)
var dataSubPath="localData"
/// 超时时间(expireTime)
var expireTime=0
/// 请求接口(interface)
var interface:NSDictionary?
/// 本地菜单(localMenu)
// var localMenu:NSDictionary?
/*网络情况记录*/
/// reachability:网络连接测试对象
var reachability:Reachability!
/// networkStatus:网络连接状态
var networkStatus=Reachability.NetworkStatus.notReachable{didSet{PbLog.debug(logPre+"NetworkStatus:网络状态:"+self.networkStatus.description)}}
/*当前设备相关信息*/
/// reachability:设备相关信息
var deviceParams:Dictionary<String,String>=Dictionary()
/*应用处理器*/
/// requester:请求处理器对象
var requester:PbDataRequester?
/// parser:结果解析器对象
var parser:PbDataParser?
/// cacheManager:缓存管理器对象
var cacheManager:PbDataCacheFile?
/*定位相关*/
/// locationManager:定位管理器对象
var locationManager:CLLocationManager?
/// lastLocation:最新定位地址
var lastLocation:CLLocation?
/*-----------------------结束:声明私有属性*/
/*-----------------------开始:对象初始化相关方法*/
/// 使用配置文件初始化应用数据控制器,读取相应的URL访问及数据存储相关配置
/// - parameter plistName:配置文件资源名称
open func initWithPlistName(_ plistName:String)
{
self.initWithPlistName(plistName, initLocationManager:.inUse)
}
/// 使用配置文件初始化应用数据控制器,读取相应的URL访问及数据存储相关配置
/// - parameter plistName:配置文件资源名称
/// - parameter initLocationManager:初始化时开启定位
open func initWithPlistName(_ plistName:String,initLocationManager:PbDataLocationMode)
{
/*载入plist配置文件*/
self.loadPlist(plistName)
/*读取配置信息*/
self.readConfig()
/*判断当前网络连接情况*/
self.loadNetworkStatus()
/*根据配置信息初始化当前的处理对象*/
self.createProcessObjects()
/*读取相关设备信息*/
self.loadDeviceInfo()
/*创建定位管理器*/
self.createLocationManager(initLocationManager)
}
/// 重新载入配置文件并重新初始化内部处理器对象
/// - parameter plistName:配置文件资源名称
open func reloadByPlistName(_ plistName:String)
{
}
/// 载入指定的PList文件
/// - parameter plistName:配置文件资源名称
fileprivate func loadPlist(_ plistName:String)
{
//调试信息前缀
let logPre=self.logPre+"loadPlist:"
/*读取Plist*/
let path:String?=Bundle.main.path(forResource: plistName,ofType:"plist")
if((path) != nil)
{
PbLog.debug(logPre+"开始读取Plist资源(Path:"+path!+")")
self.config=NSDictionary(contentsOfFile:path!)!
PbLog.debug(logPre+"读取完成")
}
}
/// 读取相应的配置信息
fileprivate func readConfig()
{
//调试信息前缀
let logPre=self.logPre+"readConfig:"
/*读取配置信息*/
PbLog.debug(logPre+"开始读取配置信息")
let keys:NSArray=self.config.allKeys as NSArray
let count:Int=self.config.count
for i in 0 ..< count
{
let key:String=keys.object(at: i) as! String
let value:AnyObject=self.config.object(forKey: key)! as AnyObject;
//服务地址(server)
if(key=="server")
{
server=value as! String
PbLog.debug(logPre+"服务地址:"+server)
}
//备用服务地址(alterServer)
if(key=="alterServer")
{
alterServer=value as! String
PbLog.debug(logPre+"备用服务地址:"+alterServer)
}
//全局参数字典(global)
if(key=="global")
{
global=value as? NSDictionary
PbLog.debug(logPre+"全局参数:总数("+global!.count.description+")")
}
//通讯协议(communication)
if(key=="communication")
{
let communication:NSDictionary=value as! NSDictionary
//访问协议(netProtocol)
netProtocol=communication.object(forKey: "protocol") as! String
PbLog.debug(logPre+"访问协议:"+netProtocol)
//请求方式(method)
method=communication.object(forKey: "method") as! String
PbLog.debug(logPre+"请求方式:"+method)
//返回类型(responseType)
responseType=communication.object(forKey: "responseType") as! String
PbLog.debug(logPre+"返回类型:"+responseType)
//超时时间(timeOut)
timeOut=communication.object(forKey: "timeOut") as! Int
PbLog.debug(logPre+"超时时间:"+timeOut.description)
//HTTPS协议下服务端的证书资源名称
if let name=communication.object(forKey: "certNameOfServer")
{
certNameOfServer=name as! String
}
//HTTPS协议下客户端的证书资源名称
if let name=communication.object(forKey: "certNameOfClient")
{
certNameOfClient=name as! String
}
//HTTPS协议下客户端的证书访问密码
if let name=communication.object(forKey: "certPassOfClient")
{
certPassOfClient=name as! String
}
}
//文件缓存(localCache)
if(key=="localCache")
{
let localCache:NSDictionary=value as! NSDictionary
//是否激活(isActiveLocalCache)
isActiveLocalCache=localCache.object(forKey: "isActive") as! Bool
PbLog.debug(logPre+"文件缓存:是否激活:"+isActiveLocalCache.description)
//本地目录(cachePath)
cachePath=localCache.object(forKey: "cachePath") as! String
PbLog.debug(logPre+"文件缓存:本地目录:"+cachePath)
//资源子目录(resourceSubPath)
resourceSubPath=localCache.object(forKey: "subResourcePath") as! String
PbLog.debug(logPre+"文件缓存:资源目录:"+resourceSubPath)
//数据子目录(dataSubPath)
dataSubPath=localCache.object(forKey: "subDataPath") as! String
PbLog.debug(logPre+"文件缓存:数据目录:"+dataSubPath)
//超时时间(expireTime)
expireTime=localCache.object(forKey: "expireTime") as! Int;
PbLog.debug(logPre+"文件缓存:超时时间:"+expireTime.description)
}
//数据接口(interface)
if(key=="interface")
{
interface=value as? NSDictionary
PbLog.debug(logPre+"数据接口:总数("+interface!.count.description+")")
}
//本地菜单(localMenu)
// if(key=="localMenu")
// {
// localMenu=value as? NSDictionary
// PbLog.debug(logPre+"本地菜单:总数("+localMenu!.count.description+")")
// }
}
PbLog.debug(logPre+"结束配置信息读取")
}
/// 判断当前的网络状态
fileprivate func loadNetworkStatus()
{
//调试信息前缀
let logPre=self.logPre+"loadNetworkStatus:"
do
{
self.reachability = Reachability()
self.networkStatus=reachability.currentReachabilityStatus
NotificationCenter.default.addObserver(self, selector: #selector(PbDataAppController.doWhenNetworkStatusChange(_:)), name: ReachabilityChangedNotification, object: reachability)
try reachability.startNotifier()
}
catch
{
PbLog.error(logPre+"创建Reachability或启动监听(startNotifier)失败!")
self.networkStatus=Reachability.NetworkStatus.notReachable
}
}
/// 网络状态变化时记录当前的状态
func doWhenNetworkStatusChange(_ note:Notification)
{
self.networkStatus=reachability.currentReachabilityStatus
}
/// 根据配置信息初始化当前的处理对象
fileprivate func createProcessObjects()
{
/*根据配置信息初始化远程服务请求处理对象*/
//http协议
if(netProtocol=="HTTP")
{
self.requester=PbDataRequesterHttp(isGet: method=="GET")
PbLog.debug(logPre+"createProcessObjects:应用处理器:"+"HTTP请求处理器")
}
//https协议
if(netProtocol=="HTTPS")
{
self.requester=PbDataRequesterHttp(isGet: method=="GET", certNameOfServer: certNameOfServer, certNameOfClient: certNameOfClient, certPassOfClient: certPassOfClient)
PbLog.debug(logPre+"createProcessObjects:应用处理器:"+"HTTPS请求处理器")
}
/*根据配置信息初始化远程服务结果处理对象*/
//JSON数据格式
if(responseType=="JSON")
{
self.parser=PbDataParserJson()
PbLog.debug(logPre+"createProcessObjects:应用处理器:"+"JSON返回解析器")
}
/*根据配置信息初始化本地缓存处理对象*/
self.cacheManager=PbDataCacheFile(cachePathName:cachePath)
PbLog.debug(logPre+"createProcessObjects:应用处理器:"+"本地缓存管理器")
if(isActiveLocalCache)
{
cacheManager?.createSubCachePath(resourceSubPath)
cacheManager?.createSubCachePath(dataSubPath)
PbLog.debug(logPre+"createProcessObjects:应用处理器:"+"本地缓存管理器激活(创建子目录-"+resourceSubPath+"和"+dataSubPath)
}
else
{
cacheManager?.clearDataForSubPath(resourceSubPath)
cacheManager?.clearDataForSubPath(dataSubPath)
PbLog.debug(logPre+"createProcessObjects:应用处理器:"+"未激活本地缓存管理器,清空缓存目录-"+cachePath)
}
}
/// 载入设备相关信息
fileprivate func loadDeviceInfo()
{
//获取当前设备
let device=(UIDevice.current)
//获取当前屏幕
let screen=(UIScreen.main)
//设置设备参数
self.deviceParams["deviceName"]=device.model
self.deviceParams["deviceSystem"]=device.systemName
self.deviceParams["deviceVersion"]=device.systemVersion
self.deviceParams["deviceWidth"]=(NSString(string:screen.bounds.width.description).intValue).description
self.deviceParams["deviceHeight"]=(NSString(string:screen.bounds.height.description).intValue).description
self.deviceParams["deviceUuid"]=device.identifierForVendor!.uuidString.md5()
// self.deviceParams["appVersion"]=NSBundle.mainBundle().infoDictionary![kCFBundleVersionKey as String]!.description
//输出当前设备信息
PbLog.debug(logPre+"loadDeviceInfo:设备名称:"+self.deviceParams["deviceName"]!)
PbLog.debug(logPre+"loadDeviceInfo:系统名称:"+self.deviceParams["deviceSystem"]!)
PbLog.debug(logPre+"loadDeviceInfo:系统版本:"+self.deviceParams["deviceVersion"]!)
PbLog.debug(logPre+"loadDeviceInfo:屏幕宽度:"+self.deviceParams["deviceWidth"]!)
PbLog.debug(logPre+"loadDeviceInfo:屏幕高度:"+self.deviceParams["deviceHeight"]!)
PbLog.debug(logPre+"loadDeviceInfo:唯一标识:"+self.deviceParams["deviceUuid"]!)
// PbLog.debug(logPre+"loadDeviceInfo:应用版本:"+self.deviceParams["appVersion"]!)
}
/// 创建并配置定位管理器对象
/// - parameter locationMode:指定定位模式
fileprivate func createLocationManager(_ locationMode:PbDataLocationMode)
{
if((locationManager) == nil&&locationMode != PbDataLocationMode.none)
{
locationManager=CLLocationManager()
locationManager?.delegate=self
locationManager?.desiredAccuracy=kCLLocationAccuracyBest
locationManager?.distanceFilter=1000
lastLocation=nil
PbLog.debug(logPre+"createLocationManager:创建定位管理器")
//iOS8下询问用户
if(PbSystem.osUp8)
{
if(locationMode == PbDataLocationMode.always)
{
locationManager?.requestAlwaysAuthorization()
}
if(locationMode == PbDataLocationMode.inUse)
{
locationManager?.requestWhenInUseAuthorization()
}
}
locationManager?.startUpdatingLocation()
}
}
/*-----------------------结束:对象初始化相关方法*/
/*-----------------------开始:业务处理相关方法*/
/// 是否连接网络
open func isNetworkConnected() -> Bool
{
return networkStatus != Reachability.NetworkStatus.notReachable
}
/// 是否连接网络
open func isNetworkConnected(_ statusDescription:String) -> Bool
{
return statusDescription != Reachability.NetworkStatus.notReachable.description
}
/// 获取指定的设备唯一编号
open var deviceUuid:String{
return deviceParams["uuid"]!
}
/// 通过指定接口标识,获取对应的数据信息
/// - parameter key :接口标识
/// - parameter params :传递参数
/// - parameter callback :回调方法
/// - parameter getMode :请求模式,包括网络、本地缓存或网络、本地
open func request(_ key:String,params:NSDictionary,callback:@escaping (_ data:NSDictionary?,_ error:NSError?,_ property:NSDictionary?) -> Void,getMode:PbDataGetMode)
{
request(key, params: params, callback: callback, getMode: getMode, property: nil,useAlterServer:false,dataType:false)
}
/// 通过指定接口标识,获取对应的数据信息
/// - parameter key :接口标识
/// - parameter params :传递参数
/// - parameter callback :回调方法
/// - parameter getMode :请求模式,包括网络、本地缓存或网络、本地
/// - parameter property :回传属性
open func request(_ key:String,params:NSDictionary,callback:@escaping (_ data:NSDictionary?,_ error:NSError?,_ property:NSDictionary?) -> Void,getMode:PbDataGetMode,property:NSDictionary?)
{
request(key, params: params, callback: callback, getMode: getMode, property: property,useAlterServer:false,dataType:false)
}
/// 通过指定接口标识,获取对应的数据信息
/// - parameter key :接口标识
/// - parameter params :传递参数
/// - parameter callback :回调方法
/// - parameter getMode :请求模式,包括网络、本地缓存或网络、本地
/// - parameter property :回传属性
/// - parameter useAlterServer :是否使用备用服务地址
open func request(_ key:String,params:NSDictionary,callback:@escaping (_ data:NSDictionary?,_ error:NSError?,_ property:NSDictionary?) -> Void,getMode:PbDataGetMode,property:NSDictionary?,useAlterServer:Bool)
{
request(key, params: params, callback: callback, getMode: getMode, property: property,useAlterServer:useAlterServer,dataType:false)
}
/// 通过指定接口标识,获取对应的数据信息
/// - parameter key :接口标识
/// - parameter params :传递参数
/// - parameter callback :回调方法
/// - parameter getMode :请求模式,包括网络、本地缓存或网络、本地
/// - parameter sourceType :是否数据上传类型
open func request(_ key:String,params:NSDictionary,callback:@escaping (_ data:NSDictionary?,_ error:NSError?,_ property:NSDictionary?) -> Void,getMode:PbDataGetMode,dataType:Bool)
{
request(key, params: params, callback: callback, getMode: getMode, property: nil,useAlterServer:false,dataType:dataType)
}
/// 通过指定接口标识,获取对应的数据信息
/// - parameter key :接口标识
/// - parameter params :传递参数
/// - parameter callback :回调方法
/// - parameter getMode :请求模式,包括网络、本地缓存或网络、本地
/// - parameter property :回传属性
/// - parameter sourceType :是否数据上传类型
open func request(_ key:String,params:NSDictionary,callback:@escaping (_ data:NSDictionary?,_ error:NSError?,_ property:NSDictionary?) -> Void,getMode:PbDataGetMode,property:NSDictionary?,dataType:Bool)
{
request(key, params: params, callback: callback, getMode: getMode, property: property,useAlterServer:false,dataType:dataType)
}
///通过指定接口标识,获取对应的数据信息
/// - parameter key :接口标识
/// - parameter params :传递参数
/// - parameter callback :回调方法
/// - parameter getMode :请求模式,包括网络、本地缓存或网络、本地
/// - parameter property :回传属性
/// - parameter useAlterServer :是否使用备用服务地址
/// - parameter sourceType :是否数据上传类型
open func request(_ key:String,params:NSDictionary,callback:@escaping (_ data:NSDictionary?,_ error:NSError?,_ property:NSDictionary?) -> Void,getMode:PbDataGetMode,property:NSDictionary?,useAlterServer:Bool,dataType:Bool)
{
//调试信息前缀
let curLogPre=logPre+"request:"
//根据指定的接口标示获取接口信息
let attributes=interface?.object(forKey: key) as! NSDictionary
//获取远程接口链接地址
let url:String=((!alterServer.isEmpty&&useAlterServer) ?alterServer:server)+(attributes.object(forKey: "url")as! String)
PbLog.debug(curLogPre+"请求地址:"+url)
//获取请求参数
let configParams=attributes.object(forKey: "params") as! NSDictionary
let sendParams=NSMutableDictionary(dictionary: configParams)
sendParams.setValuesForKeys(params as! [String : AnyObject])
sendParams.setValuesForKeys(global as! [String : AnyObject])
PbLog.debug(curLogPre+"请求参数:"+requester!.paramString(sendParams))
//记录本地资源是否存在
var isExist=false
//记录返回数据信息
//let resCount:Int=((property) == nil) ?1:(property!.count+1)
//记录返回数据
var resData:Data?=nil
//记录文件缓存对应的文件名
let fileKey=String(url+"?"+requester!.paramString(sendParams)).md5()
//非纯网络模式,先读取本地缓存数据
if(getMode != PbDataGetMode.fromNet && isActiveLocalCache)
{
PbLog.debug(curLogPre+"缓存文件:"+fileKey)
resData=cacheManager?.dataForKey(fileKey, subPath: dataSubPath)
isExist=(resData != nil)
}
//非纯本地模式,并本地数据不存在,请求网络
if(self.isNetworkConnected()
&& (!isExist
|| (isExist && getMode == PbDataGetMode.fromNet)))
{
//添加设备信息参数
sendParams.setValuesForKeys(deviceParams)
//添加定位信息参数
if(lastLocation != nil)
{
sendParams.setValue(lastLocation!.coordinate.longitude.description,
forKey:"longitude")
sendParams.setValue(lastLocation!.coordinate.latitude.description,
forKey:"latitude")
}
PbLog.debug(curLogPre+"请求内容:"+requester!.paramString(sendParams))
//发送请求
requester?.request(url, data: sendParams,callback: {
(data, response, error) -> Void in
//返回数据存在则存入缓存
if(self.isActiveLocalCache)
{
if(data != nil)
{
resData=data
self.cacheManager?.setData(data!, key: fileKey, subPath: self.dataSubPath)
}
//如果网络请求数据不存在,则临时读取缓存数据
else
{
resData=self.cacheManager?.dataForKey(fileKey, subPath: self.dataSubPath)
}
}
self.handleResponse(resData, callback: callback, error: error, property: property)
},isMultipart:dataType)
}
//非请求网络则直接处理返回数据
else
{
self.handleResponse(resData, callback: callback, error: nil, property: property)
}
}
/// 读取本地缓存的图片
/// - parameter imageUrl:图片的链接地址
open func imageInLocalCache(_ imageUrl:String) -> UIImage?
{
let data=cacheManager?.dataForKey(imageUrl.md5(),subPath:resourceSubPath)
return (data == nil) ? nil : UIImage(data:data!)
}
/// 写入图片到本地缓存中
/// - parameter imageData:图片数据
/// - parameter forUrl:对应的链接地址
open func saveImageIntoLocalCache(_ imageData:Data,forUrl:String)
{
if(isActiveLocalCache)
{
cacheManager?.setData(imageData, key: forUrl.md5(), subPath: resourceSubPath)
}
}
/// 获取本地缓存数据大小
open func sizeOfCacheDataInLocal() -> String
{
var size:UInt64=0
//计算缓存文件夹的大小
size+=cacheManager!.sizeOfSubPath(dataSubPath)
size+=cacheManager!.sizeOfSubPath(resourceSubPath)
let sizef:Float64=Float64(size)
//转换为文字描述
var result=""
if(size>1024*1024*1024)
{
result=NSString(format:"%.2f GB",sizef/(1024*1024*1024)) as String
}
else if(size>1024*1024)
{
result=NSString(format:"%.2f MB",sizef/(1024*1024)) as String
}
else if(size>1024)
{
result=NSString(format:"%.2f KB",sizef/(1024)) as String
}
else
{
result=NSString(format:"%.0f byte",sizef) as String
}
return result
}
/// 清理缓存数据
open func clearCacheDataInLocal() -> String
{
cacheManager?.clearDataForSubPath(dataSubPath)
cacheManager?.clearDataForSubPath(resourceSubPath)
return self.sizeOfCacheDataInLocal()
}
/// 获取完整路径
/// - parameter url:链接地址
open func fullUrl(_ url:String) -> String
{
return url.hasPrefix("http") ? url:(self.server+url)
}
/*-----------------------结束:业务处理相关方法*/
/*-----------------------开始:业务处理相关私有方法*/
/// 处理返回数据内容
fileprivate func handleResponse(_ data:Data?,callback:(_ data:NSDictionary?,_ error:NSError?,_ property:NSDictionary?) -> Void,error:NSError?,property:NSDictionary?)
{
var response:NSMutableDictionary? = parser?.dictionaryByData(data)
let success=(response != nil)
response=(response == nil) ? NSMutableDictionary():response
//为结果数据添加控制器相关回复值
response!.setValue([PbDataAppController.KEY_NETWORK:networkStatus.description,PbDataAppController.KEY_SUCCESS:success.description],forKey: PbDataAppController.KEY_RESPONSE)
//回调反馈方法
callback(response,error,property)
}
/*-----------------------结束:业务处理相关私有方法*/
/*-----------------------开始:实现CLLocationManagerDelegate委托*/
// 更新到最新的位置
public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
lastLocation=locations[locations.count-1]
PbLog.debug(logPre+"locationManager:最新定位:经度("+lastLocation!.coordinate.longitude.description+"),纬度("+lastLocation!.coordinate.latitude.description+")")
}
/*-----------------------结束:实现CLLocationManagerDelegate委托*/
}
| apache-2.0 | d243ca972c6c8b8376f398a576aae38f | 34.095791 | 226 | 0.593234 | 4.243025 | false | false | false | false |
debugsquad/nubecero | nubecero/View/PhotosAlbumPhotoSettings/VPhotosAlbumPhotoSettings.swift | 1 | 6461 | import UIKit
class VPhotosAlbumPhotoSettings:UIView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout
{
private weak var controller:CPhotosAlbumPhotoSettings!
private weak var collectionView:UICollectionView!
private let kDeselectTime:TimeInterval = 1
private let kBarHeight:CGFloat = 120
private let kCollectionBottom:CGFloat = 20
private let kInterLine:CGFloat = 1
convenience init(controller:CPhotosAlbumPhotoSettings)
{
self.init()
clipsToBounds = true
backgroundColor = UIColor.background
translatesAutoresizingMaskIntoConstraints = false
self.controller = controller
let bar:VPhotosAlbumPhotoSettingsBar = VPhotosAlbumPhotoSettingsBar(
controller:controller)
let flow:UICollectionViewFlowLayout = UICollectionViewFlowLayout()
flow.headerReferenceSize = CGSize.zero
flow.footerReferenceSize = CGSize.zero
flow.minimumLineSpacing = kInterLine
flow.minimumInteritemSpacing = 0
flow.scrollDirection = UICollectionViewScrollDirection.vertical
flow.sectionInset = UIEdgeInsets(
top:0,
left:0,
bottom:kCollectionBottom,
right:0)
let collectionView:UICollectionView = UICollectionView(
frame:CGRect.zero,
collectionViewLayout:flow)
collectionView.clipsToBounds = true
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.backgroundColor = UIColor.clear
collectionView.showsHorizontalScrollIndicator = false
collectionView.showsVerticalScrollIndicator = false
collectionView.alwaysBounceVertical = true
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(
VPhotosAlbumPhotoSettingsCellPixels.self,
forCellWithReuseIdentifier:
VPhotosAlbumPhotoSettingsCellPixels.reusableIdentifier)
collectionView.register(
VPhotosAlbumPhotoSettingsCellSize.self,
forCellWithReuseIdentifier:
VPhotosAlbumPhotoSettingsCellSize.reusableIdentifier)
collectionView.register(
VPhotosAlbumPhotoSettingsCellTaken.self,
forCellWithReuseIdentifier:
VPhotosAlbumPhotoSettingsCellTaken.reusableIdentifier)
collectionView.register(
VPhotosAlbumPhotoSettingsCellAdded.self,
forCellWithReuseIdentifier:
VPhotosAlbumPhotoSettingsCellAdded.reusableIdentifier)
collectionView.register(
VPhotosAlbumPhotoSettingsCellAlbum.self,
forCellWithReuseIdentifier:
VPhotosAlbumPhotoSettingsCellAlbum.reusableIdentifier)
self.collectionView = collectionView
addSubview(collectionView)
addSubview(bar)
let views:[String:UIView] = [
"bar":bar,
"collectionView":collectionView]
let metrics:[String:CGFloat] = [
"barHeight":kBarHeight]
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"H:|-0-[bar]-0-|",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"H:|-0-[collectionView]-0-|",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"V:|-0-[bar(barHeight)]-0-[collectionView]-0-|",
options:[],
metrics:metrics,
views:views))
}
override func layoutSubviews()
{
collectionView.collectionViewLayout.invalidateLayout()
super.layoutSubviews()
}
//MARK: private
private func modelAtIndex(index:IndexPath) -> MPhotosAlbumPhotoSettingsItem
{
let item:MPhotosAlbumPhotoSettingsItem = controller.model.items[index.item]
return item
}
//MARK: collectionView delegate
func collectionView(_ collectionView:UICollectionView, layout collectionViewLayout:UICollectionViewLayout, sizeForItemAt indexPath:IndexPath) -> CGSize
{
let item:MPhotosAlbumPhotoSettingsItem = modelAtIndex(index:indexPath)
let width:CGFloat = collectionView.bounds.maxX
let size:CGSize = CGSize(
width:width,
height:item.cellHeight)
return size
}
func numberOfSections(in collectionView:UICollectionView) -> Int
{
return 1
}
func collectionView(_ collectionView:UICollectionView, numberOfItemsInSection section:Int) -> Int
{
let count:Int = controller.model.items.count
return count
}
func collectionView(_ collectionView:UICollectionView, cellForItemAt indexPath:IndexPath) -> UICollectionViewCell
{
let item:MPhotosAlbumPhotoSettingsItem = modelAtIndex(index:indexPath)
let cell:VPhotosAlbumPhotoSettingsCell = collectionView.dequeueReusableCell(
withReuseIdentifier:
item.reusableIdentifier,
for:indexPath) as! VPhotosAlbumPhotoSettingsCell
cell.config(controller:controller, model:item)
return cell
}
func collectionView(_ collectionView:UICollectionView, shouldSelectItemAt indexPath:IndexPath) -> Bool
{
let item:MPhotosAlbumPhotoSettingsItem = modelAtIndex(index:indexPath)
return item.selectable
}
func collectionView(_ collectionView:UICollectionView, shouldHighlightItemAt indexPath:IndexPath) -> Bool
{
let item:MPhotosAlbumPhotoSettingsItem = modelAtIndex(index:indexPath)
return item.selectable
}
func collectionView(_ collectionView:UICollectionView, didSelectItemAt indexPath:IndexPath)
{
let item:MPhotosAlbumPhotoSettingsItem = modelAtIndex(index:indexPath)
item.selected(controller:controller)
DispatchQueue.main.asyncAfter(
deadline:DispatchTime.now() + kDeselectTime)
{ [weak collectionView] in
collectionView?.selectItem(
at:nil,
animated:false,
scrollPosition:UICollectionViewScrollPosition())
}
}
}
| mit | fccf772150b2beec927627713a448407 | 35.710227 | 155 | 0.668008 | 6.346758 | false | false | false | false |
Ben21hao/edx-app-ios-enterprise-new | Source/CoursesTableViewController.swift | 2 | 4378 | //
// CoursesTableViewController.swift
// edX
//
// Created by Anna Callahan on 10/15/15.
// Copyright © 2015 edX. All rights reserved.
//
import UIKit
class CourseCardCell : UITableViewCell {
static let margin = StandardVerticalMargin
private static let cellIdentifier = "CourseCardCell"
private let courseView = CourseCardView(frame: CGRectZero)
private var course : OEXCourse?
private let courseCardBorderStyle = BorderStyle()
override init(style : UITableViewCellStyle, reuseIdentifier : String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.contentView.addSubview(courseView)
courseView.snp_makeConstraints {make in
make.top.equalTo(self.contentView).offset(CourseCardCell.margin)
make.bottom.equalTo(self.contentView)
make.leading.equalTo(self.contentView).offset(CourseCardCell.margin)
make.trailing.equalTo(self.contentView).offset(-CourseCardCell.margin)
}
courseView.applyBorderStyle(courseCardBorderStyle)
self.contentView.backgroundColor = OEXStyles.sharedStyles().neutralXLight()
self.selectionStyle = .None
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
protocol CoursesTableViewControllerDelegate : class {
func coursesTableChoseCourse(course : OEXCourse)
}
class CoursesTableViewController: UITableViewController {
enum Context {
case CourseCatalog
case EnrollmentList
}
typealias Environment = protocol<NetworkManagerProvider>
private let environment : Environment
private let context: Context
weak var delegate : CoursesTableViewControllerDelegate?
var courses : [OEXCourse] = []
let insetsController = ContentInsetsController()
init(environment : Environment, context: Context) {
self.context = context
self.environment = environment
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
self.tableView.separatorStyle = .None
self.tableView.backgroundColor = OEXStyles.sharedStyles().neutralXLight()
self.tableView.accessibilityIdentifier = "courses-table-view"
self.tableView.snp_makeConstraints {make in
make.edges.equalTo(self.view)
}
tableView.estimatedRowHeight = 200
tableView.rowHeight = UITableViewAutomaticDimension
tableView.registerClass(CourseCardCell.self, forCellReuseIdentifier: CourseCardCell.cellIdentifier)
self.insetsController.addSource(
ConstantInsetsSource(insets: UIEdgeInsets(top: 0, left: 0, bottom: StandardVerticalMargin, right: 0), affectsScrollIndicators: false)
)
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.courses.count ?? 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let course = self.courses[indexPath.row]
let cell = tableView.dequeueReusableCellWithIdentifier(CourseCardCell.cellIdentifier, forIndexPath: indexPath) as! CourseCardCell
cell.accessibilityLabel = cell.courseView.updateAcessibilityLabel()
cell.accessibilityHint = Strings.accessibilityShowsCourseContent
cell.courseView.tapAction = {[weak self] card in
self?.delegate?.coursesTableChoseCourse(course)
}
switch context {
case .CourseCatalog:
CourseCardViewModel.onCourseCatalog(course).apply(cell.courseView, networkManager: self.environment.networkManager)
case .EnrollmentList:
CourseCardViewModel.onHome(course).apply(cell.courseView, networkManager: self.environment.networkManager)
}
cell.course = course
return cell
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.insetsController.updateInsets()
}
}
| apache-2.0 | 52dacd688002824aebfa805be4f07997 | 34.298387 | 145 | 0.687914 | 5.331303 | false | false | false | false |
brentdax/swift | test/refactoring/RefactoringKind/trailingclosure.swift | 8 | 2939 | struct Foo {
static func foo(a: () -> Int) {}
func qux(x: Int, y: () -> Int ) {}
}
func testTrailingClosure() -> String {
Foo.foo(a: { 1 })
Foo.bar(a: { print(3); return 1 })
Foo().qux(x: 1, y: { 1 })
let _ = Foo().quux(x: 1, y: { 1 })
[1,2,3]
.filter({ $0 % 2 == 0 })
.map({ $0 + 1 })
Foo.foo { 1 }
Foo.bar { print(3); return 1 }
Foo().qux(x: 1) { 1 }
}
// RUN: %refactor -source-filename %s -pos=7:3 | %FileCheck %s -check-prefix=CHECK-TRAILING-CLOSURE
// RUN: %refactor -source-filename %s -pos=7:6 | %FileCheck %s -check-prefix=CHECK-TRAILING-CLOSURE
// RUN: %refactor -source-filename %s -pos=7:7 | %FileCheck %s -check-prefix=CHECK-TRAILING-CLOSURE
// RUN: %refactor -source-filename %s -pos=7:10 | %FileCheck %s -check-prefix=CHECK-TRAILING-CLOSURE
// RUN: %refactor -source-filename %s -pos=7:11 | %FileCheck %s -check-prefix=CHECK-TRAILING-CLOSURE
// RUN: %refactor -source-filename %s -pos=7:12 | %FileCheck %s -check-prefix=CHECK-TRAILING-CLOSURE
// RUN: %refactor -source-filename %s -pos=7:14 | %FileCheck %s -check-prefix=CHECK-TRAILING-CLOSURE
// RUN: %refactor -source-filename %s -pos=7:16 | %FileCheck %s -check-prefix=CHECK-NO-TRAILING-CLOSURE
// RUN: %refactor -source-filename %s -pos=7:18 | %FileCheck %s -check-prefix=CHECK-TRAILING-CLOSURE
// RUN: %refactor -source-filename %s -pos=7:19 | %FileCheck %s -check-prefix=CHECK-TRAILING-CLOSURE
// RUN: %refactor -source-filename %s -pos=8:3 | %FileCheck %s -check-prefix=CHECK-TRAILING-CLOSURE
// RUN: %refactor -source-filename %s -pos=8:11 | %FileCheck %s -check-prefix=CHECK-TRAILING-CLOSURE
// RUN: %refactor -source-filename %s -pos=9:3 | %FileCheck %s -check-prefix=CHECK-NO-TRAILING-CLOSURE
// RUN: %refactor -source-filename %s -pos=9:8 | %FileCheck %s -check-prefix=CHECK-TRAILING-CLOSURE
// RUN: %refactor -source-filename %s -pos=10:3 | %FileCheck %s -check-prefix=CHECK-NO-TRAILING-CLOSURE
// RUN: %refactor -source-filename %s -pos=10:9 | %FileCheck %s -check-prefix=CHECK-NO-TRAILING-CLOSURE
// RUN: %refactor -source-filename %s -pos=10:17 | %FileCheck %s -check-prefix=CHECK-TRAILING-CLOSURE
// RUN: %refactor -source-filename %s -pos=12:4 | %FileCheck %s -check-prefix=CHECK-NO-TRAILING-CLOSURE
// RUN: %refactor -source-filename %s -pos=13:5 | %FileCheck %s -check-prefix=CHECK-TRAILING-CLOSURE
// RUN: %refactor -source-filename %s -pos=14:5 | %FileCheck %s -check-prefix=CHECK-TRAILING-CLOSURE
// RUN: %refactor -source-filename %s -pos=16:7 | %FileCheck %s -check-prefix=CHECK-NO-TRAILING-CLOSURE
// RUN: %refactor -source-filename %s -pos=17:7 | %FileCheck %s -check-prefix=CHECK-NO-TRAILING-CLOSURE
// RUN: %refactor -source-filename %s -pos=18:9 | %FileCheck %s -check-prefix=CHECK-NO-TRAILING-CLOSURE
// CHECK-TRAILING-CLOSURE: Convert To Trailing Closure
// CHECK-NO-TRAILING-CLOSURE: Action begins
// CHECK-NO-TRAILING-CLOSURE-NOT: Convert To Trailing Closure
// CHECK-NO-TRAILING-CLOSURE: Action ends
| apache-2.0 | beb7d080121d422cc4e09390a3d25c74 | 53.425926 | 103 | 0.688329 | 2.95674 | false | false | false | false |
backslash-f/paintcode-kony | iOS/SwiftFFI/Supporting Files/StyleKit.swift | 1 | 15412 | //
// StyleKit.swift
// PaintCodeKony
//
// Created by Fernando Fernandes on 09/03/17.
// Copyright © 2017 backslash-f. All rights reserved.
//
// Generated by PaintCode
// http://www.paintcodeapp.com
//
import UIKit
public class StyleKit : NSObject {
//// Cache
private struct Cache {
static let green: UIColor = UIColor(red: 0.153, green: 0.608, blue: 0.220, alpha: 1.000)
static let background: UIColor = UIColor(red: 0.933, green: 0.933, blue: 0.933, alpha: 1.000)
static let white: UIColor = UIColor(red: 1.000, green: 1.000, blue: 1.000, alpha: 1.000)
}
//// Colors
public dynamic class var green: UIColor { return Cache.green }
public dynamic class var background: UIColor { return Cache.background }
public dynamic class var white: UIColor { return Cache.white }
//// Drawing Methods
public dynamic class func drawGoal(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 132, height: 176), resizing: ResizingBehavior = .aspectFit, goalProgress: CGFloat = 1) {
//// General Declarations
let context = UIGraphicsGetCurrentContext()!
//// Resize to Target Frame
context.saveGState()
let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 132, height: 176), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 132, y: resizedFrame.height / 176)
//// Variable Declarations
let goalCompleted = goalProgress == 1 ? true : false
let goalPercentageVisible = goalProgress == 0 ? false : true
let goalPercentNumber: CGFloat = goalProgress * 100
let goalPercentText = "\(Int(round(goalPercentNumber)))" + "%"
let goalResultAngle: CGFloat = -1 * goalProgress * 279
//// GoalGroup
//// CircleBackgroundBezier Drawing
let circleBackgroundBezierPath = UIBezierPath(ovalIn: CGRect(x: 7, y: 41.75, width: 118, height: 117))
StyleKit.background.setStroke()
circleBackgroundBezierPath.lineWidth = 10
circleBackgroundBezierPath.stroke()
if (goalPercentageVisible) {
//// CircleProgressStroke Drawing
let circleProgressStrokeRect = CGRect(x: 7, y: 41.75, width: 118, height: 117)
let circleProgressStrokePath = UIBezierPath()
circleProgressStrokePath.addArc(withCenter: CGPoint.zero, radius: circleProgressStrokeRect.width / 2, startAngle: 133 * CGFloat.pi/180, endAngle: -(goalResultAngle + 227) * CGFloat.pi/180, clockwise: true)
var circleProgressStrokeTransform = CGAffineTransform(translationX: circleProgressStrokeRect.midX, y: circleProgressStrokeRect.midY)
circleProgressStrokeTransform = circleProgressStrokeTransform.scaledBy(x: 1, y: circleProgressStrokeRect.height / circleProgressStrokeRect.width)
circleProgressStrokePath.apply(circleProgressStrokeTransform)
StyleKit.green.setStroke()
circleProgressStrokePath.lineWidth = 11
circleProgressStrokePath.lineCapStyle = .round
circleProgressStrokePath.stroke()
}
//// BaseBezier Drawing
let baseBezierPath = UIBezierPath()
baseBezierPath.move(to: CGPoint(x: 29.01, y: 138.28))
baseBezierPath.addLine(to: CGPoint(x: 110.36, y: 138.28))
baseBezierPath.addCurve(to: CGPoint(x: 117.09, y: 139.47), controlPoint1: CGPoint(x: 109.43, y: 138.28), controlPoint2: CGPoint(x: 113.46, y: 138.28))
baseBezierPath.addLine(to: CGPoint(x: 117.79, y: 139.64))
baseBezierPath.addCurve(to: CGPoint(x: 129, y: 155.6), controlPoint1: CGPoint(x: 124.52, y: 142.09), controlPoint2: CGPoint(x: 129, y: 148.46))
baseBezierPath.addCurve(to: CGPoint(x: 129, y: 156.51), controlPoint1: CGPoint(x: 129, y: 156.51), controlPoint2: CGPoint(x: 129, y: 156.51))
baseBezierPath.addLine(to: CGPoint(x: 129, y: 156.51))
baseBezierPath.addLine(to: CGPoint(x: 129, y: 156.51))
baseBezierPath.addLine(to: CGPoint(x: 129, y: 157.43))
baseBezierPath.addCurve(to: CGPoint(x: 117.79, y: 173.38), controlPoint1: CGPoint(x: 129, y: 164.57), controlPoint2: CGPoint(x: 124.52, y: 170.94))
baseBezierPath.addCurve(to: CGPoint(x: 101.38, y: 174.75), controlPoint1: CGPoint(x: 113.46, y: 174.75), controlPoint2: CGPoint(x: 109.43, y: 174.75))
baseBezierPath.addLine(to: CGPoint(x: 23.64, y: 174.75))
baseBezierPath.addCurve(to: CGPoint(x: 16.91, y: 173.56), controlPoint1: CGPoint(x: 24.57, y: 174.75), controlPoint2: CGPoint(x: 20.54, y: 174.75))
baseBezierPath.addLine(to: CGPoint(x: 16.21, y: 173.38))
baseBezierPath.addCurve(to: CGPoint(x: 5, y: 157.43), controlPoint1: CGPoint(x: 9.48, y: 170.94), controlPoint2: CGPoint(x: 5, y: 164.57))
baseBezierPath.addCurve(to: CGPoint(x: 5, y: 156.51), controlPoint1: CGPoint(x: 5, y: 156.51), controlPoint2: CGPoint(x: 5, y: 156.51))
baseBezierPath.addLine(to: CGPoint(x: 5, y: 156.51))
baseBezierPath.addLine(to: CGPoint(x: 5, y: 156.51))
baseBezierPath.addLine(to: CGPoint(x: 5, y: 155.6))
baseBezierPath.addCurve(to: CGPoint(x: 16.21, y: 139.64), controlPoint1: CGPoint(x: 5, y: 148.46), controlPoint2: CGPoint(x: 9.48, y: 142.09))
baseBezierPath.addCurve(to: CGPoint(x: 32.62, y: 138.28), controlPoint1: CGPoint(x: 20.54, y: 138.28), controlPoint2: CGPoint(x: 24.57, y: 138.28))
baseBezierPath.addLine(to: CGPoint(x: 23.64, y: 138.28))
baseBezierPath.addLine(to: CGPoint(x: 29.01, y: 138.28))
baseBezierPath.close()
StyleKit.green.setFill()
baseBezierPath.fill()
//// GoalPercentageText Drawing
let goalPercentageTextRect = CGRect(x: 5, y: 138.75, width: 124, height: 36)
let goalPercentageTextStyle = NSMutableParagraphStyle()
goalPercentageTextStyle.alignment = .center
let goalPercentageTextFontAttributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 20), NSForegroundColorAttributeName: StyleKit.white, NSParagraphStyleAttributeName: goalPercentageTextStyle]
let goalPercentageTextTextHeight: CGFloat = goalPercentText.boundingRect(with: CGSize(width: goalPercentageTextRect.width, height: CGFloat.infinity), options: .usesLineFragmentOrigin, attributes: goalPercentageTextFontAttributes, context: nil).height
context.saveGState()
context.clip(to: goalPercentageTextRect)
goalPercentText.draw(in: CGRect(x: goalPercentageTextRect.minX, y: goalPercentageTextRect.minY + (goalPercentageTextRect.height - goalPercentageTextTextHeight) / 2, width: goalPercentageTextRect.width, height: goalPercentageTextTextHeight), withAttributes: goalPercentageTextFontAttributes)
context.restoreGState()
//// GoalIconFlightBezier Drawing
context.saveGState()
context.translateBy(x: 42.8, y: 77.31)
context.scaleBy(x: 1.1, y: 1.1)
let goalIconFlightBezierPath = UIBezierPath()
goalIconFlightBezierPath.move(to: CGPoint(x: 39.61, y: 36.1))
goalIconFlightBezierPath.addLine(to: CGPoint(x: 42.51, y: 33.32))
goalIconFlightBezierPath.addLine(to: CGPoint(x: 31.43, y: 16.17))
goalIconFlightBezierPath.addCurve(to: CGPoint(x: 40.58, y: 1.85), controlPoint1: CGPoint(x: 41.07, y: 6.84), controlPoint2: CGPoint(x: 42.15, y: 3.36))
goalIconFlightBezierPath.addCurve(to: CGPoint(x: 25.64, y: 10.62), controlPoint1: CGPoint(x: 39.01, y: 0.35), controlPoint2: CGPoint(x: 35.37, y: 1.38))
goalIconFlightBezierPath.addLine(to: CGPoint(x: 7.73, y: 0))
goalIconFlightBezierPath.addLine(to: CGPoint(x: 4.83, y: 2.78))
goalIconFlightBezierPath.addLine(to: CGPoint(x: 19.45, y: 16.78))
goalIconFlightBezierPath.addCurve(to: CGPoint(x: 7.46, y: 30.4), controlPoint1: CGPoint(x: 14.91, y: 21.49), controlPoint2: CGPoint(x: 10.46, y: 26.52))
goalIconFlightBezierPath.addLine(to: CGPoint(x: 1.66, y: 28.03))
goalIconFlightBezierPath.addLine(to: CGPoint(x: 0, y: 29.62))
goalIconFlightBezierPath.addLine(to: CGPoint(x: 4.77, y: 34.19))
goalIconFlightBezierPath.addCurve(to: CGPoint(x: 3.86, y: 37.03), controlPoint1: CGPoint(x: 3.87, y: 35.67), controlPoint2: CGPoint(x: 3.5, y: 36.68))
goalIconFlightBezierPath.addCurve(to: CGPoint(x: 6.82, y: 36.16), controlPoint1: CGPoint(x: 4.23, y: 37.37), controlPoint2: CGPoint(x: 5.28, y: 37.02))
goalIconFlightBezierPath.addLine(to: CGPoint(x: 11.59, y: 40.73))
goalIconFlightBezierPath.addLine(to: CGPoint(x: 13.25, y: 39.14))
goalIconFlightBezierPath.addLine(to: CGPoint(x: 10.78, y: 33.58))
goalIconFlightBezierPath.addCurve(to: CGPoint(x: 25, y: 22.1), controlPoint1: CGPoint(x: 14.84, y: 30.71), controlPoint2: CGPoint(x: 20.08, y: 26.45))
goalIconFlightBezierPath.addLine(to: CGPoint(x: 39.61, y: 36.1))
goalIconFlightBezierPath.close()
goalIconFlightBezierPath.usesEvenOddFillRule = true
StyleKit.green.setFill()
goalIconFlightBezierPath.fill()
context.restoreGState()
if (goalCompleted) {
//// StarsGroup
//// Star3Bezier Drawing
let star3BezierPath = UIBezierPath()
star3BezierPath.move(to: CGPoint(x: 96.5, y: 10.88))
star3BezierPath.addLine(to: CGPoint(x: 99.55, y: 16.76))
star3BezierPath.addLine(to: CGPoint(x: 106.37, y: 17.7))
star3BezierPath.addLine(to: CGPoint(x: 101.43, y: 22.28))
star3BezierPath.addLine(to: CGPoint(x: 102.6, y: 28.74))
star3BezierPath.addLine(to: CGPoint(x: 96.5, y: 25.69))
star3BezierPath.addLine(to: CGPoint(x: 90.4, y: 28.74))
star3BezierPath.addLine(to: CGPoint(x: 91.57, y: 22.28))
star3BezierPath.addLine(to: CGPoint(x: 86.63, y: 17.7))
star3BezierPath.addLine(to: CGPoint(x: 93.45, y: 16.76))
star3BezierPath.close()
StyleKit.green.setFill()
star3BezierPath.fill()
//// Star2Bezier Drawing
let star2BezierPath = UIBezierPath()
star2BezierPath.move(to: CGPoint(x: 66, y: 1))
star2BezierPath.addLine(to: CGPoint(x: 70.04, y: 9.19))
star2BezierPath.addLine(to: CGPoint(x: 79.08, y: 10.5))
star2BezierPath.addLine(to: CGPoint(x: 72.54, y: 16.87))
star2BezierPath.addLine(to: CGPoint(x: 74.08, y: 25.87))
star2BezierPath.addLine(to: CGPoint(x: 66, y: 21.62))
star2BezierPath.addLine(to: CGPoint(x: 57.92, y: 25.87))
star2BezierPath.addLine(to: CGPoint(x: 59.46, y: 16.87))
star2BezierPath.addLine(to: CGPoint(x: 52.92, y: 10.5))
star2BezierPath.addLine(to: CGPoint(x: 61.96, y: 9.19))
star2BezierPath.close()
StyleKit.green.setFill()
star2BezierPath.fill()
//// Star1Bezier Drawing
let star1BezierPath = UIBezierPath()
star1BezierPath.move(to: CGPoint(x: 35.5, y: 10.88))
star1BezierPath.addLine(to: CGPoint(x: 38.55, y: 16.76))
star1BezierPath.addLine(to: CGPoint(x: 45.37, y: 17.7))
star1BezierPath.addLine(to: CGPoint(x: 40.43, y: 22.28))
star1BezierPath.addLine(to: CGPoint(x: 41.6, y: 28.74))
star1BezierPath.addLine(to: CGPoint(x: 35.5, y: 25.69))
star1BezierPath.addLine(to: CGPoint(x: 29.4, y: 28.74))
star1BezierPath.addLine(to: CGPoint(x: 30.57, y: 22.28))
star1BezierPath.addLine(to: CGPoint(x: 25.63, y: 17.7))
star1BezierPath.addLine(to: CGPoint(x: 32.45, y: 16.76))
star1BezierPath.close()
StyleKit.green.setFill()
star1BezierPath.fill()
}
context.restoreGState()
}
public dynamic class func drawResizableGoal(frame: CGRect = CGRect(x: 1, y: 1, width: 130, height: 174), resizableGoalProgress: CGFloat = 0) {
//// General Declarations
let context = UIGraphicsGetCurrentContext()!
// This non-generic function dramatically improves compilation times of complex expressions.
func fastFloor(_ x: CGFloat) -> CGFloat { return floor(x) }
//// Symbol Drawing
let symbolRect = CGRect(x: frame.minX + 1, y: frame.minY + 1, width: fastFloor((frame.width - 1) * 0.99225 + 0.5), height: fastFloor((frame.height - 1) * 0.99422 + 0.5))
context.saveGState()
context.clip(to: symbolRect)
context.translateBy(x: symbolRect.minX, y: symbolRect.minY)
StyleKit.drawGoal(frame: CGRect(origin: .zero, size: symbolRect.size), resizing: .stretch, goalProgress: resizableGoalProgress)
context.restoreGState()
}
//// Generated Images
public dynamic class func imageOfGoal(goalProgress: CGFloat = 1) -> UIImage {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 132, height: 176), false, 0)
StyleKit.drawGoal(goalProgress: goalProgress)
let imageOfGoal = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return imageOfGoal
}
public dynamic class func imageOfResizableGoal(imageSize: CGSize = CGSize(width: 130, height: 174), resizableGoalProgress: CGFloat = 0) -> UIImage {
UIGraphicsBeginImageContextWithOptions(imageSize, false, 0)
StyleKit.drawResizableGoal(frame: CGRect(x: 0, y: 0, width: imageSize.width, height: imageSize.height), resizableGoalProgress: resizableGoalProgress)
let imageOfResizableGoal = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return imageOfResizableGoal
}
@objc(StyleKitResizingBehavior)
public enum ResizingBehavior: Int {
case aspectFit /// The content is proportionally resized to fit into the target rectangle.
case aspectFill /// The content is proportionally resized to completely fill the target rectangle.
case stretch /// The content is stretched to match the entire target rectangle.
case center /// The content is centered in the target rectangle, but it is NOT resized.
public func apply(rect: CGRect, target: CGRect) -> CGRect {
if rect == target || target == CGRect.zero {
return rect
}
var scales = CGSize.zero
scales.width = abs(target.width / rect.width)
scales.height = abs(target.height / rect.height)
switch self {
case .aspectFit:
scales.width = min(scales.width, scales.height)
scales.height = scales.width
case .aspectFill:
scales.width = max(scales.width, scales.height)
scales.height = scales.width
case .stretch:
break
case .center:
scales.width = 1
scales.height = 1
}
var result = rect.standardized
result.size.width *= scales.width
result.size.height *= scales.height
result.origin.x = target.minX + (target.width - result.width) / 2
result.origin.y = target.minY + (target.height - result.height) / 2
return result
}
}
}
| mit | b602a2a7492a236f05b024f3c9059f4b | 51.777397 | 298 | 0.649731 | 3.808006 | false | false | false | false |
twtstudio/WePeiYang-iOS | WePeiYang/LostFound/Model/LostFoundItem.swift | 1 | 776 | //
// LostFoundItem.swift
// WePeiYang
//
// Created by Qin Yubo on 16/4/22.
// Copyright © 2016年 Qin Yubo. All rights reserved.
//
import UIKit
import ObjectMapper
class LostFoundItem: NSObject, Mappable {
var index = 0
var name = ""
var title = ""
var place = ""
var time = ""
var phone = ""
var lostType = 0
var otherTag = ""
var foundPic = ""
required init?(_ map: Map) {
}
func mapping(map: Map) {
index <- map["id"]
name <- map["name"]
title <- map["title"]
place <- map["place"]
time <- map["time"]
phone <- map["phone"]
lostType <- map["lost_type"]
otherTag <- map["other_tag"]
foundPic <- map["found_pic"]
}
}
| mit | 0ebc5c547070cd619ed1cb02d92b6fc7 | 18.820513 | 52 | 0.510996 | 3.716346 | false | false | false | false |
darthpelo/SurviveAmsterdam | mobile/Pods/QuadratTouch/Source/Shared/Endpoints/Settings.swift | 4 | 1232 | //
// Settings.swift
// Quadrat
//
// Created by Constantine Fry on 06/11/14.
// Copyright (c) 2014 Constantine Fry. All rights reserved.
//
import Foundation
public class Settings: Endpoint {
override var endpoint: String {
return "settings"
}
/** https://developer.foursquare.com/docs/settings/settings */
public func get(settingId: String, completionHandler: ResponseClosure? = nil) -> Task {
return self.getWithPath(settingId, parameters: nil, completionHandler: completionHandler)
}
// MARK: - General
/** https://developer.foursquare.com/docs/settings/all */
public func all(completionHandler: ResponseClosure? = nil) -> Task {
let path = "all"
return self.getWithPath(path, parameters: nil, completionHandler: completionHandler)
}
// MARK: - Actions
/** https://developer.foursquare.com/docs/settings/set */
public func set(settingId: String, value: Bool, completionHandler: ResponseClosure? = nil) -> Task {
let path = settingId + "/set"
let parameters = [Parameter.value: (value) ? "1":"0"]
return self.postWithPath(path, parameters: parameters, completionHandler: completionHandler)
}
}
| mit | 8f6691e2829ca3ef18040340015c13c7 | 32.297297 | 104 | 0.663961 | 4.353357 | false | false | false | false |
mrdepth/EVEUniverse | Neocom/Neocom/Utility/Alamofire+Extensions.swift | 2 | 1537 | //
// Alamofire+Extensions.swift
// Neocom
//
// Created by Artem Shimanski on 5/17/20.
// Copyright © 2020 Artem Shimanski. All rights reserved.
//
import Foundation
import Alamofire
import Combine
extension NetworkReachabilityManager {
class func publisher() -> AnyPublisher<NetworkReachabilityStatus, Never> {
let manager = NetworkReachabilityManager()
let subject = CurrentValueSubject<NetworkReachabilityStatus, Never>(manager?.status ?? NetworkReachabilityStatus.unknown)
// let subject = PassthroughSubject<NetworkReachabilityStatus, Never>()
return subject.handleEvents(receiveSubscription: { (_) in
manager?.startListening(onUpdatePerforming: { [weak subject] (status) in
subject?.send(status)
})
}, receiveCompletion: { (c) in
manager?.stopListening()
}, receiveCancel: {
manager?.stopListening()
}).eraseToAnyPublisher()
}
}
extension NetworkReachabilityManager.NetworkReachabilityStatus {
var isReachable: Bool {
switch self {
case .reachable:
return true
default:
return false
}
}
}
extension AFError {
var notConnectedToInternet: Bool {
guard let error = underlyingError else {return false}
if let error = error as? AFError {
return error.notConnectedToInternet
}
else {
return (error as? URLError)?.code == .notConnectedToInternet
}
}
}
| lgpl-2.1 | a2ee1858f291f0f428cd7c9b1616412c | 28.538462 | 129 | 0.63737 | 5.485714 | false | false | false | false |
XCEssentials/ProjectGenerator | Sources/Project/Project.swift | 1 | 1275 | //
// Project.swift
// MKHProjGen
//
// Created by Maxim Khatskevich on 3/15/17.
// Copyright © 2017 Maxim Khatskevich. All rights reserved.
//
public
struct Project
{
public
final
class BuildConfigurations
{
public
var all = BuildConfiguration.Base()
public
var debug = BuildConfiguration.Defaults.General.debug()
public
var release = BuildConfiguration.Defaults.General.release()
}
//---
public
let name: String
//---
public
let configurations = BuildConfigurations()
public private(set)
var targets: [Target] = []
//---
public
init(
_ name: String,
_ configureProject: (inout Project) -> Void
)
{
self.name = name
//---
configureProject(&self)
}
//===
public
mutating
func target(
_ name: String,
_ platform: Platform,
_ type: Target.InternalType,
_ configureTarget: (inout Target) -> Void
)
{
targets
.append(Target(platform, name, type, configureTarget))
}
//===
public
var variants: [Project.Variant] = []
}
| mit | 7cb3e76fd2e0611e2497f7de9d2b59ab | 16.452055 | 67 | 0.514914 | 4.753731 | false | true | false | false |
EclipseSoundscapes/EclipseSoundscapes | EclipseSoundscapes/Features/RumbleMap/RumbleMapInteractiveViewController.swift | 1 | 5546 | //
// RumbleMapInteractiveViewController.swift
// EclipseSoundscapes
//
// Created by Arlindo Goncalves on 8/8/17.
//
// Copyright © 2017 Arlindo Goncalves.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see [http://www.gnu.org/licenses/].
//
// For Contact email: [email protected]
import UIKit
import BRYXBanner
class RumbleMapInteractiveViewController: BaseViewController {
var event : RumbleEvent?
var rumbleMap : RumbleMap!
let closeBtn : UIButton = {
var btn = UIButton(type: .system)
btn.addSqueeze()
btn.addTarget(self, action: #selector(close), for: .touchUpInside)
btn.setTitle(localizedString(key: "InteractiveRubmleMapCloseButtonTitle"), for: .normal)
btn.setTitleColor(.white, for: .normal)
btn.titleLabel?.font = UIFont.getDefautlFont(.bold, size: 22)
btn.backgroundColor = .black
return btn
}()
let instructionBtn : UIButton = {
var btn = UIButton(type: .system)
btn.addSqueeze()
btn.addTarget(self, action: #selector(openInstructions), for: .touchUpInside)
btn.setTitle(localizedString(key: "InteractiveRubmleMapInstructionButtonTitle"), for: .normal)
btn.setTitleColor(.white, for: .normal)
btn.titleLabel?.font = UIFont.getDefautlFont(.bold, size: 22)
btn.backgroundColor = .black
return btn
}()
let lineSeparatorView1: UIView = {
let view = UIView()
view.isAccessibilityElement = false
view.backgroundColor = UIColor(white: 0.5, alpha: 0.5)
return view
}()
let lineSeparatorView2: UIView = {
let view = UIView()
view.isAccessibilityElement = false
view.backgroundColor = UIColor(white: 0.5, alpha: 0.5)
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
rumbleMap = RumbleMap()
rumbleMap.event = event
setupView()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
rumbleMap.setSession(active: true)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
rumbleMap.setSession(active: false)
}
func setupView() {
rumbleMap.target = { [weak self] in
self?.switchFocus()
}
view.addSubview(rumbleMap)
view.addSubview(closeBtn)
view.addSubview(instructionBtn)
view.addSubview(lineSeparatorView1)
view.addSubview(lineSeparatorView2)
rumbleMap.anchorToTop(view.topAnchor, left: view.leftAnchor, bottom: closeBtn.topAnchor, right: view.rightAnchor)
if #available(iOS 11.0, *) {
closeBtn.anchor(nil, left: view.leftAnchor, bottom: view.safeAreaLayoutGuide.bottomAnchor, right: view.centerXAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0.5, widthConstant: 0, heightConstant: 50)
instructionBtn.anchor(nil, left: view.centerXAnchor, bottom: view.safeAreaLayoutGuide.bottomAnchor, right: view.rightAnchor, topConstant: 0, leftConstant: 0.5, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 50)
} else {
closeBtn.anchor(nil, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.centerXAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0.5, widthConstant: 0, heightConstant: 50)
instructionBtn.anchor(nil, left: view.centerXAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, topConstant: 0, leftConstant: 0.5, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 50)
}
lineSeparatorView1.anchor(nil, left: view.leftAnchor, bottom: closeBtn.topAnchor, right: view.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 1)
lineSeparatorView2.anchor(closeBtn.topAnchor, left: closeBtn.rightAnchor, bottom: closeBtn.bottomAnchor, right: instructionBtn.leftAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0)
}
func switchFocus() {
rumbleMap.isActive = false
if closeBtn.accessibilityElementIsFocused() {
UIAccessibility.post(notification: .layoutChanged, argument: closeBtn)
} else {
UIAccessibility.post(notification: .layoutChanged, argument: instructionBtn)
}
}
@objc func close() {
self.dismiss(animated: true, completion: nil)
}
@objc func openInstructions() {
self.present(IntructionsViewController(), animated: true, completion: nil)
}
override var prefersStatusBarHidden: Bool {
return true
}
override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation {
return .slide
}
}
| gpl-3.0 | 4f0a041ccfaa1bf5b19602570e57acd3 | 40.074074 | 253 | 0.675023 | 4.497161 | false | false | false | false |
isunimp/ModelUtility | Swift Examples/Swift Examples/ViewController.swift | 1 | 3206 | //
// ViewController.swift
// Swift Examples
//
// Created by 任贵权 on 16/5/10.
// Copyright © 2016年 任贵权. All rights reserved.
//
import UIKit
import ModelUtility
import CoreData
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let objectContext = appDelegate.managedObjectContext
let JSON: [NSObject : AnyObject] = [
"ID":123,
"userInfo":[
"names":[
"nowName":"isunimp",
"oldNames":[
"resolutelyyy",
"visitors"]],
"age":22,
"gender":Gender.Man.rawValue,
"height":"1.74",
"date":"1993-11-01",
"adult":true],
"phones":[
["phoneNumber":"123456789"],
["phoneNumber":"987654321"]],
"object":"这是一个字符串对象"]
User.mu_setupPropertyKeyMapper { //() -> [NSObject : AnyObject]! in
return ["id":"ID"]
}
UserInfo.mu_setupPropertyKeyMapper { //() -> [NSObject : AnyObject]! in
return ["name":"names.oldNames.[0]"]
}
UserInfo.mu_setupCustomModelTransform {
let propertyInfo = $0.0
if propertyInfo.name == "date"{
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
return dateFormatter.dateFromString($0.1 as! String)
}else {return nil}
}
let _ = User.mu_modelWithDictionary(JSON, inContext: objectContext)
do{
try objectContext.save()
}catch{
assert(false, "保存失败")
}
let fetchRequest = NSFetchRequest(entityName: "User")
var result: [User]? = nil
do{
result = try objectContext.executeFetchRequest(fetchRequest) as? [User]
}catch{
assert(false, "查询失败")
}
// 输出值
let user = result![0] as User
print(user.id)
print(user.object)
print(user.phones?.count)
for phone in user.phones! {
print(phone.phoneNumber)
}
print(user.userInfo?.name)
print(user.userInfo?.age)
print(user.userInfo?.height)
print(user.userInfo?.date)
switch user.userInfo!.gender
{
case .Unknown:
print("Unknown")
case .Man:
print("Man")
case .Woman:
print("Woman")
}
UserInfo.mu_setupCustomJSONTransform {
let propertyInfo = $0.0
if propertyInfo.name == "date"{
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
return dateFormatter.stringFromDate($0.1 as! NSDate)
}else {return nil}
}
let JOSNString = user.mu_toJSONString()
print(JOSNString)
}
}
| mit | ac87deeb3de0e1c4cbc340e83808fa17 | 28.726415 | 84 | 0.504602 | 4.781487 | false | false | false | false |
mobgeek/swift | Swift em 4 Semanas/Swift4Semanas (7.0).playground/Pages/S1 - Fluxo de Controle.xcplaygroundpage/Contents.swift | 1 | 3098 | //: [Anterior: Operadores Básicos](@previous)
// Playground - noun: a place where people can play
import UIKit
// Controle Condicional
var temperatura = 35
if temperatura >= 35 {
print("Tá quente! Partiu Praia!")
} else if temperatura <= 25 {
print("Cariocas! preparem os seus casacos!")
} else {
print("Pessoal, ainda não esquentou de verdade.")
}
// Operadores Lógicos:
var permitirJogar = false
if !permitirJogar {
print("Video-game suspenso!")
}
// &&: ambos os valores precisam ser true para expressão inteira ser verdadeira.
var jantouTudo = true
var fezDever = false
if jantouTudo && fezDever {
print("Playstation ligando...")
} else {
print("Vamos cumprir os deveres primeiro?")
}
// ||: apenas um dos valores precisa ser true para toda a expressão ser true.
var temIngresso = false
var conheceFulanoDaOrganizacao = false
if temIngresso || conheceFulanoDaOrganizacao {
print("Seja bem vindo!")
} else {
print("O jogo passa na tv!")
}
var daImprensa = false
var temCracha = true
if temIngresso || conheceFulanoDaOrganizacao || daImprensa && temCracha {
print("Seja bem vindo!")
} else {
print("O jogo passa na tv!")
}
// Switch
var caller = ""
caller = "Mãe"
switch caller {
case "Pai":
print("Pai, já te ligo!")
case "Amor":
print("\(caller), to acabando de me arrumar.")
case "Mãe":
print("Mãe, retorno assim que puder.")
default:
print("Você ligou para o Fabio. Deixe o seu recado após o PIPS!")
}
// Séries (Operadores Range)
1...5
1..<5
var ligações = 11
var contadorNatural: String
switch ligações {
case 0...9:
contadorNatural = "algumas vezes"
case 10...99:
contadorNatural = "dezenas de vezes"
default:
contadorNatural = "um monte de vezes"
}
let mensagem = "Você me ligou \(contadorNatural)"
// Guard
/*: Para falarmos sobre a estrutura condicional guard, precisaremos primeiro estudar optionals e funções.
Aqui está um link direto para os arquivos:
[Optionals - Semana 2](Optionals)
---
[Funções - Semana 2](Funções)
---
[Guard - Semana 2](Guard)
*/
// Loops
// For-in
for elemento in 1...9 {
print("\(elemento) vezes 6 é \(elemento * 6)")
}
for letra in "Cafe".characters {
print("Letra é \(letra)")
}
// For-condição-incremento
for var tentativa = 0; tentativa < 3; ++tentativa {
print("Tentativa número: \(tentativa)")
}
// While
var dinheiro = 5
while dinheiro > 3 {
print("Pode pedir a última! Saldo: \(dinheiro)")
--dinheiro
}
dinheiro = 10
// Do-While
repeat {
print("Pode pedir a última! Saldo: \(dinheiro)")
--dinheiro
} while dinheiro > 3
dinheiro
//Extra: é possível verificar por condições ao final de um loop for-in usando a cláusula 'where'
for par in 0...10 where par % 2 == 0 {
par
}
//: [Próximo: Continue & Break](@next)
| mit | f615b1bee86eae498c106377c704f59f | 12.904545 | 105 | 0.615234 | 2.89678 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/WordPressShareExtension/AppExtensionsService.swift | 1 | 23875 | import Aztec
import CoreData
import WordPressKit
/// Provides site fetching and post/media uploading functionality to app extensions.
///
class AppExtensionsService {
typealias CompletionBlock = () -> Void
typealias FailureBlock = () -> Void
typealias FailureWithErrorBlock = (_ error: Error?) -> Void
// MARK: - Private Properties
/// Unique identifier a group of upload operations
///
fileprivate lazy var groupIdentifier: String = {
let groupIdentifier = UUID().uuidString
return groupIdentifier
}()
/// Unique identifier for background sessions
///
fileprivate lazy var backgroundSessionIdentifier: String = {
let identifier = WPAppGroupName + "." + UUID().uuidString
return identifier
}()
/// WordPress.com OAuth Token
///
fileprivate lazy var oauth2Token: String? = {
ShareExtensionService.retrieveShareExtensionToken()
}()
/// Simple Rest API (no backgrounding)
///
fileprivate lazy var simpleRestAPI: WordPressComRestApi = {
WordPressComRestApi(oAuthToken: oauth2Token,
userAgent: nil,
backgroundUploads: false,
backgroundSessionIdentifier: backgroundSessionIdentifier,
sharedContainerIdentifier: WPAppGroupName)
}()
/// Backgrounding Rest API
///
fileprivate lazy var backgroundRestAPI: WordPressComRestApi = {
return WordPressComRestApi(oAuthToken: oauth2Token,
userAgent: nil,
backgroundUploads: true,
backgroundSessionIdentifier: backgroundSessionIdentifier,
sharedContainerIdentifier: WPAppGroupName)
}()
/// Tracks Instance
///
fileprivate lazy var tracks: Tracks = {
Tracks(appGroupName: WPAppGroupName)
}()
/// WordPress.com Username
///
internal lazy var wpcomUsername: String? = {
ShareExtensionService.retrieveShareExtensionUsername()
}()
/// Core Data stack for application extensions
///
fileprivate lazy var coreDataStack = SharedCoreDataStack()
fileprivate var managedContext: NSManagedObjectContext!
// MARK: - Initializers
@objc required init() {
// Tracker
tracks.wpcomUsername = wpcomUsername
// Core Data
managedContext = coreDataStack.managedContext
}
deinit {
coreDataStack.saveContext()
}
}
// MARK: - Sites
extension AppExtensionsService {
/// Fetches the primary blog + recent sites + remaining visible blogs for the current account.
///
/// - Parameters:
/// - onSuccess: Completion handler executed after a successful fetch.
/// - onFailure: The failure handler.
///
func fetchSites(onSuccess: @escaping ([RemoteBlog]?) -> (), onFailure: @escaping FailureBlock) {
let remote = AccountServiceRemoteREST(wordPressComRestApi: simpleRestAPI)
var filterJetpackSites = false
#if JETPACK
filterJetpackSites = true
#endif
remote.getBlogs(filterJetpackSites, success: { blogs in
guard let blogs = blogs as? [RemoteBlog] else {
DDLogError("Error parsing returned sites.")
onFailure()
return
}
let primary = self.primarySites(with: blogs)
let recents = self.recentSites(with: blogs, ignoring: primary)
let combinedSiteList = primary + recents + self.remainingSites(with: blogs, ignoring: (primary + recents))
onSuccess(combinedSiteList)
}, failure: { error in
DDLogError("Error retrieving sites: \(String(describing: error))")
onFailure()
})
}
/// Filters the list of sites and returns if a user is allowed to upload media for the selected site
///
/// - Parameters:
/// - sites: the list of sites to filter.
/// - selectedSiteID: the current site the user wants to upload media to.
///
func isAuthorizedToUploadMedia(in sites: [RemoteBlog], for selectedSiteID: Int) -> Bool {
let siteID = NSNumber(value: selectedSiteID)
guard let isAuthorizedToUploadFiles = sites.filter({$0.blogID == siteID}).first?.isUploadingFilesAllowed() else {
return false
}
return isAuthorizedToUploadFiles
}
private func primarySites(with blogs: [RemoteBlog]) -> [RemoteBlog] {
// Find the primary site (even if it's not visible)
let primarySiteID = ShareExtensionService.retrieveShareExtensionPrimarySite()?.siteID ?? 0
return blogs.filter({ $0.blogID.intValue == primarySiteID })
}
private func recentSites(with sites: [RemoteBlog], ignoring excludedSites: [RemoteBlog]? = nil) -> [RemoteBlog] {
let visibleSites = sites.filter({ $0.visible })
var filteredVisibleSites: [RemoteBlog]
if let excludedSites = excludedSites {
filteredVisibleSites = visibleSites.filter({ site in
!excludedSites.contains(site)
})
} else {
filteredVisibleSites = visibleSites
}
let recentSiteURLs = ShareExtensionService.retrieveShareExtensionRecentSites() ?? [String()]
return recentSiteURLs.compactMap({ url in
return filteredVisibleSites.first(where: { $0.url == url })
})
}
private func remainingSites(with sites: [RemoteBlog], ignoring excludedSites: [RemoteBlog]? = nil) -> [RemoteBlog] {
let visibleSites = sites.filter({ $0.visible })
guard let excludedSites = excludedSites else {
return visibleSites
}
return visibleSites.filter({ site in
!excludedSites.contains(site)
})
}
}
// MARK: - Blog Settings
extension AppExtensionsService {
/// Retrieves the site settings for a site — the default CategoryID is contained within.
///
/// - Parameters:
/// - siteID: Site ID to fetch settings for
/// - onSuccess: Completion handler executed after a successful fetch
/// - onFailure: The failure handler
func fetchSettingsForSite(_ siteID: Int, onSuccess: @escaping (RemoteBlogSettings?) -> (), onFailure: @escaping FailureWithErrorBlock) {
let remote = BlogServiceRemoteREST(wordPressComRestApi: simpleRestAPI, siteID: NSNumber(value: siteID))
remote.syncBlogSettings(success: { settings in
onSuccess(settings)
}, failure: { error in
DDLogError("Error retrieving settings for site ID \(siteID): \(String(describing: error))")
onFailure(error)
})
}
}
// MARK: - Taxonomy
extension AppExtensionsService {
/// Retrieves the most used tags for a site.
///
/// - Parameters:
/// - siteID: Site ID to fetch tags for
/// - onSuccess: Completion handler executed after a successful fetch
/// - onFailure: The failure handler
///
func fetchTopTagsForSite(_ siteID: Int, onSuccess: @escaping ([RemotePostTag]) -> (), onFailure: @escaping FailureWithErrorBlock) {
let remote = TaxonomyServiceRemoteREST(wordPressComRestApi: simpleRestAPI, siteID: NSNumber(value: siteID))
let paging = RemoteTaxonomyPaging()
paging.orderBy = .byCount
paging.order = .orderDescending
remote.getTagsWith(paging, success: { tags in
onSuccess(tags)
}, failure: { error in
DDLogError("Error retrieving tags for site ID \(siteID): \(String(describing: error))")
onFailure(error)
})
}
/// Retrieves the all categories for a site.
///
/// - Parameters:
/// - siteID: Site ID to fetch tags for
/// - onSuccess: Completion handler executed after a successful fetch
/// - onFailure: The failure handler
///
func fetchCategoriesForSite(_ siteID: Int, onSuccess: @escaping ([RemotePostCategory]) -> (), onFailure: @escaping FailureWithErrorBlock) {
let remote = TaxonomyServiceRemoteREST(wordPressComRestApi: simpleRestAPI, siteID: NSNumber(value: siteID))
remote.getCategoriesWithSuccess({ categories in
onSuccess(categories)
}, failure: { error in
DDLogError("Error retrieving categories for site ID \(siteID): \(String(describing: error))")
onFailure(error)
})
}
}
// MARK: - Uploading Posts
extension AppExtensionsService {
/// Saves a new post to the share container db and then uploads it synchronously. This function
/// WILL schedule a local notification to fire upon success or failure.
///
/// - Parameters:
/// - shareData: The shareData with which to create the post
/// - siteID: Site ID the post will be uploaded to
/// - onComplete: Completion handler executed after a post is uploaded to the server
/// - onFailure: The (optional) failure handler.
///
func saveAndUploadPost(shareData: ShareData,
siteID: Int,
onComplete: CompletionBlock?,
onFailure: FailureBlock?) {
let remotePost = RemotePost(shareData: shareData, siteID: siteID)
let uploadPostOpID = coreDataStack.savePostOperation(remotePost, groupIdentifier: groupIdentifier, with: .pending)
uploadPost(forUploadOpWithObjectID: uploadPostOpID, onComplete: {
// Schedule a local success notification
if let uploadPostOp = self.coreDataStack.fetchPostUploadOp(withObjectID: uploadPostOpID) {
ExtensionNotificationManager.scheduleSuccessNotification(postUploadOpID: uploadPostOp.objectID.uriRepresentation().absoluteString,
postID: String(uploadPostOp.remotePostID),
blogID: String(uploadPostOp.siteID),
postStatus: remotePost.status)
}
onComplete?()
}, onFailure: {
// Schedule a local failure notification
if let uploadPostOp = self.coreDataStack.fetchPostUploadOp(withObjectID: uploadPostOpID) {
ExtensionNotificationManager.scheduleFailureNotification(postUploadOpID: uploadPostOp.objectID.uriRepresentation().absoluteString,
postID: String(uploadPostOp.remotePostID),
blogID: String(uploadPostOp.siteID),
postStatus: remotePost.status)
}
// Error is already logged in coredata so no need to do it here.
onFailure?()
})
}
/// Saves a new post + media items to the shared container db and then uploads it in the background.
///
/// - Parameters:
/// - shareData: The shareData with which to create the post
/// - siteID: Site ID the post will be uploaded to
/// - localMediaFileURLs: An array of local URLs containing the media files to upload
/// - requestEnqueued: Completion handler executed when the media has been processed and background upload is scheduled.
/// - onFailure: The failure handler.
///
func saveAndUploadPostWithMedia(shareData: ShareData,
siteID: Int,
localMediaFileURLs: [URL],
requestEnqueued: @escaping CompletionBlock,
onFailure: @escaping FailureBlock) {
guard !localMediaFileURLs.isEmpty else {
DDLogError("No media is attached to this upload request")
onFailure()
return
}
let remotePost = RemotePost(shareData: shareData, siteID: siteID)
// Create the post & media upload ops
let uploadPostOpID = coreDataStack.savePostOperation(remotePost, groupIdentifier: groupIdentifier, with: .pending)
let (uploadMediaOpIDs, allRemoteMedia) = createAndSaveRemoteMediaWithLocalURLs(localMediaFileURLs, siteID: NSNumber(value: siteID))
// NOTE: The success and error closures **may** get called here - it’s non-deterministic as to whether WPiOS
// or the extension gets the "did complete" callback. So unfortunately, we need to have the logic to complete
// post share here as well as WPiOS.
let remote = mediaService(siteID: siteID, api: backgroundRestAPI)
remote.uploadMedia(allRemoteMedia, requestEnqueued: { taskID in
uploadMediaOpIDs.forEach({ uploadMediaOpID in
self.coreDataStack.updateStatus(.inProgress, forUploadOpWithObjectID: uploadMediaOpID)
if let taskID = taskID {
self.coreDataStack.updateTaskID(taskID, forUploadOpWithObjectID: uploadMediaOpID)
}
})
requestEnqueued()
}, success: { remoteMedia in
guard let returnedMedia = remoteMedia as? [RemoteMedia],
returnedMedia.count > 0,
let mediaUploadOps = self.coreDataStack.fetchMediaUploadOps(for: self.groupIdentifier) else {
DDLogError("Error creating post in share extension. RemoteMedia info not returned from server.")
return
}
mediaUploadOps.forEach({ mediaUploadOp in
returnedMedia.forEach({ remoteMedia in
if let remoteMediaID = remoteMedia.mediaID?.int64Value,
let remoteMediaURLString = remoteMedia.url?.absoluteString,
let localFileName = mediaUploadOp.fileName,
let remoteFileName = remoteMedia.file,
let localFileNoExt = URL(string: localFileName)?.deletingPathExtension().lastPathComponent {
// sometimes the remote file name has been altered, such as `localfile.jpg` becoming `localfile-1.jpg`
if remoteFileName.lowercased().trim().contains(localFileNoExt.lowercased()) {
mediaUploadOp.remoteURL = remoteMediaURLString
mediaUploadOp.remoteMediaID = remoteMediaID
mediaUploadOp.currentStatus = .complete
if let width = remoteMedia.width?.int32Value,
let height = remoteMedia.width?.int32Value {
mediaUploadOp.width = width
mediaUploadOp.height = height
}
ShareMediaFileManager.shared.removeFromUploadDirectory(fileName: localFileName)
}
}
})
})
self.coreDataStack.saveContext()
// Now upload the post
self.combinePostWithMediaAndUpload(forPostUploadOpWithObjectID: uploadPostOpID, postStatus: remotePost.status, media: allRemoteMedia)
}) { error in
guard let error = error as NSError? else {
return
}
DDLogError("Error creating post in share extension: \(error.localizedDescription)")
uploadMediaOpIDs.forEach({ uploadMediaOpID in
self.coreDataStack.updateStatus(.error, forUploadOpWithObjectID: uploadMediaOpID)
})
onFailure()
}
}
}
// MARK: - Private Helpers
fileprivate extension AppExtensionsService {
func createAndSaveRemoteMediaWithLocalURLs(_ localMediaFileURLs: [URL], siteID: NSNumber) -> ([NSManagedObjectID], [RemoteMedia]) {
// Process all of the media items and create their upload ops
var uploadMediaOpIDs = [NSManagedObjectID]()
var allRemoteMedia = [RemoteMedia]()
localMediaFileURLs.forEach { tempFilePath in
let remoteMedia = RemoteMedia()
remoteMedia.file = tempFilePath.lastPathComponent
remoteMedia.mimeType = Constants.mimeType
remoteMedia.localURL = tempFilePath
allRemoteMedia.append(remoteMedia)
let uploadMediaOpID = coreDataStack.saveMediaOperation(remoteMedia,
sessionID: backgroundSessionIdentifier,
groupIdentifier: groupIdentifier,
siteID: siteID,
with: .pending)
uploadMediaOpIDs.append(uploadMediaOpID)
}
return (uploadMediaOpIDs, allRemoteMedia)
}
/// This function takes the already-uploaded media, inserts it into the provided post, and then
/// uploads the post. This function WILL schedule a local notification to fire upon success or failure.
///
/// - Parameter uploadPostOpID: Managed object ID for the post
///
func combinePostWithMediaAndUpload(forPostUploadOpWithObjectID uploadPostOpID: NSManagedObjectID, postStatus: String, media: [RemoteMedia]) {
guard let postUploadOp = coreDataStack.fetchPostUploadOp(withObjectID: uploadPostOpID),
let groupID = postUploadOp.groupID,
let mediaUploadOps = coreDataStack.fetchMediaUploadOps(for: groupID) else {
return
}
mediaUploadOps.forEach { mediaUploadOp in
guard let fileName = mediaUploadOp.fileName,
let remoteURL = mediaUploadOp.remoteURL else {
return
}
let imgPostUploadProcessor = ImgUploadProcessor(mediaUploadID: fileName,
remoteURLString: remoteURL,
width: Int(mediaUploadOp.width),
height: Int(mediaUploadOp.height))
let content = postUploadOp.postContent ?? ""
postUploadOp.postContent = imgPostUploadProcessor.process(content)
}
coreDataStack.saveContext()
uploadPost(forUploadOpWithObjectID: uploadPostOpID, onComplete: { [weak self] in
guard let uploadPostOp = self?.coreDataStack.fetchPostUploadOp(withObjectID: uploadPostOpID) else {
return
}
let siteID = uploadPostOp.siteID
let postID = uploadPostOp.remotePostID
self?.coreDataStack.saveContext()
// Associate the remote media with the newly-uploaded post
let updatedMedia = mediaUploadOps.compactMap({return $0.remoteMedia})
self?.updateMedia(updatedMedia, postID: postID, siteID: siteID, onComplete: {
// Schedule a local success notification
ExtensionNotificationManager.scheduleSuccessNotification(postUploadOpID: uploadPostOp.objectID.uriRepresentation().absoluteString,
postID: String(uploadPostOp.remotePostID),
blogID: String(uploadPostOp.siteID),
mediaItemCount: mediaUploadOps.count,
postStatus: postStatus)
})
}, onFailure: {
// Schedule a local failure notification
if let uploadPostOp = self.coreDataStack.fetchPostUploadOp(withObjectID: uploadPostOpID) {
ExtensionNotificationManager.scheduleFailureNotification(postUploadOpID: uploadPostOp.objectID.uriRepresentation().absoluteString,
postID: String(uploadPostOp.remotePostID),
blogID: String(uploadPostOp.siteID),
mediaItemCount: mediaUploadOps.count,
postStatus: postStatus)
}
})
}
/// Uploads an already-saved post synchronously.
///
/// - Parameters:
/// - uploadOpObjectID: Managed object ID for the post
/// - onComplete: Completion handler executed after a post is uploaded to the server.
/// - onFailure: The (optional) failure handler.
///
func uploadPost(forUploadOpWithObjectID uploadOpObjectID: NSManagedObjectID, onComplete: CompletionBlock?, onFailure: FailureBlock?) {
guard let postUploadOp = coreDataStack.fetchPostUploadOp(withObjectID: uploadOpObjectID) else {
DDLogError("Error uploading post in share extension — could not fetch saved post.")
onFailure?()
return
}
let remotePost = postUploadOp.remotePost
coreDataStack.updateStatus(.inProgress, forUploadOpWithObjectID: uploadOpObjectID)
// 15-Nov-2017: Creating a post without media on the PostServiceRemoteREST does not use background uploads
let remote = PostServiceRemoteREST(wordPressComRestApi: simpleRestAPI, siteID: remotePost.siteID)
remote.createPost(remotePost, success: { post in
if let post = post {
DDLogInfo("Post \(post.postID.stringValue) sucessfully uploaded to site \(post.siteID.stringValue)")
if let postID = post.postID {
self.coreDataStack.updatePostOperation(with: .complete, remotePostID: postID.int64Value, forPostUploadOpWithObjectID: uploadOpObjectID)
} else {
self.coreDataStack.updateStatus(.complete, forUploadOpWithObjectID: uploadOpObjectID)
}
onComplete?()
}
}, failure: { error in
var errorString = "Error creating post in share extension"
if let error = error as NSError? {
errorString += ": \(error.localizedDescription)"
}
DDLogError(errorString)
self.coreDataStack.updateStatus(.error, forUploadOpWithObjectID: uploadOpObjectID)
onFailure?()
})
}
private func updateMedia(_ media: [RemoteMedia], postID: Int64, siteID: Int64, onComplete: CompletionBlock?) {
guard let siteIdentifier = Int(exactly: siteID) else {
return
}
let syncGroup = DispatchGroup()
let service = mediaService(siteID: siteIdentifier, api: simpleRestAPI)
media.forEach { mediaItem in
syncGroup.enter()
mediaItem.postID = NSNumber(value: postID)
service.update(mediaItem, success: { updatedRemoteMedia in
syncGroup.leave()
}, failure: { error in
var errorString = "Error assigning media items to post in share extension"
if let error = error as NSError? {
errorString += ": \(error.localizedDescription)"
}
DDLogError(errorString)
syncGroup.leave()
})
}
syncGroup.notify(queue: .main) {
onComplete?()
}
}
func mediaService(siteID: Int, api: WordPressComRestApi) -> MediaServiceRemoteREST {
return MediaServiceRemoteREST(wordPressComRestApi: api, siteID: NSNumber(value: siteID))
}
}
// MARK: - Constants
extension AppExtensionsService {
struct Constants {
static let mimeType = "image/jpeg"
}
}
| gpl-2.0 | bbc5e6dbb4022551e7ce967e86fb89df | 44.901923 | 155 | 0.599439 | 5.604367 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Jetpack/Jetpack Restore/Restore Status/Coordinators/JetpackRestoreStatusCoordinator.swift | 2 | 2543 | import Foundation
protocol JetpackRestoreStatusView {
func render(_ rewindStatus: RewindStatus)
func showRestoreStatusUpdateFailed()
func showRestoreFailed()
func showRestoreComplete()
}
class JetpackRestoreStatusCoordinator {
// MARK: - Properties
private let service: JetpackRestoreService
private let site: JetpackSiteRef
private let view: JetpackRestoreStatusView
private var timer: Timer?
private var retryCount: Int = 0
// MARK: - Init
init(site: JetpackSiteRef,
view: JetpackRestoreStatusView,
service: JetpackRestoreService? = nil,
context: NSManagedObjectContext = ContextManager.sharedInstance().mainContext) {
self.service = service ?? JetpackRestoreService(managedObjectContext: context)
self.site = site
self.view = view
}
// MARK: - Public
func viewDidLoad() {
startPolling()
}
func viewWillDisappear() {
stopPolling()
}
// MARK: - Private
private func startPolling() {
guard timer == nil else {
return
}
timer = Timer.scheduledTimer(withTimeInterval: Constants.pollingInterval, repeats: true) { [weak self] _ in
self?.refreshRestoreStatus()
}
}
private func stopPolling() {
timer?.invalidate()
timer = nil
}
private func refreshRestoreStatus() {
service.getRewindStatus(for: self.site, success: { [weak self] rewindStatus in
guard let self = self, let restoreStatus = rewindStatus.restore else {
return
}
switch restoreStatus.status {
case .running, .queued:
self.view.render(rewindStatus)
case .finished:
self.view.showRestoreComplete()
case .fail:
self.view.showRestoreFailed()
}
}, failure: { [weak self] error in
DDLogError("Error fetching rewind status object: \(error.localizedDescription)")
guard let self = self else {
return
}
if self.retryCount == Constants.maxRetryCount {
self.stopPolling()
self.view.showRestoreStatusUpdateFailed()
return
}
self.retryCount += 1
})
}
}
extension JetpackRestoreStatusCoordinator {
private enum Constants {
static let pollingInterval: TimeInterval = 5
static let maxRetryCount: Int = 3
}
}
| gpl-2.0 | 79f878d24945cf153a241a41913fea19 | 24.686869 | 115 | 0.600079 | 5.200409 | false | false | false | false |
SKrotkih/YTLiveStreaming | YTLiveStreaming/YTLiveRequest.swift | 1 | 27586 | //
// YTLiveRequest.swift
// YTLiveStreaming
//
// Created by Serhii Krotkykh on 10/24/16.
// Copyright © 2016 Serhii Krotkykh. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
class YTLiveRequest: NSObject {
// Set up broadcast on your Youtube account:
// https://www.youtube.com/my_live_events
// https://www.youtube.com/live_dashboard
// Errors:
// https://support.google.com/youtube/answer/3006768?hl=ru
// Developer console
// https://console.developers.google.com/apis/credentials/key/0?project=fightnights-143711
}
// MARK: LiveBroatcasts requests
// https://developers.google.com/youtube/v3/live/docs/liveBroadcasts
extension YTLiveRequest {
class func getHeaders(_ completion: @escaping (HTTPHeaders?) -> Void) {
GoogleOAuth2.sharedInstance.requestToken { token in
if let token = token {
var headers: HTTPHeaders = [.contentType("application/json")]
headers.add(.accept("application/json"))
headers.add(.authorization("Bearer \(token)"))
completion(headers)
} else {
completion(nil)
}
}
}
// Returns a list of YouTube broadcasts that match the API request parameters.
// broadcastStatus:
// Acceptable values are:
// active – Return current live broadcasts.
// all – Return all broadcasts.
// completed – Return broadcasts that have already ended.
// upcoming – Return broadcasts that have not yet started.
class func listBroadcasts(_ status: YTLiveVideoState,
completion: @escaping (Result<LiveBroadcastListModel, YTError>) -> Void) {
let parameters: [String: AnyObject] = [
"part": "id,snippet,contentDetails,status" as AnyObject,
"broadcastStatus": status.rawValue as AnyObject,
"maxResults": LiveRequest.MaxResultObjects as AnyObject,
"key": Credentials.APIkey as AnyObject
]
youTubeLiveVideoProvider.request(LiveStreamingAPI.listBroadcasts(parameters), completion: { result in
switch result {
case let .success(response):
do {
let decoder = JSONDecoder()
let response = try decoder.decode(LiveBroadcastListModel.self, from: response.data)
let totalResults = response.pageInfo.totalResults
let resultsPerPage = response.pageInfo.resultsPerPage
print("Broadcasts total count = \(totalResults)")
if totalResults > resultsPerPage {
// TODO: In this case you should send request
// with pageToken=nextPageToken or pageToken=prevPageToken parameter
print("Need to read next page!")
}
completion(.success(response))
} catch {
let message = "Parsing data error: \(error.localizedDescription)"
completion(.failure(.message(message)))
}
case let .failure(error):
let code = error.errorCode
let message = error.errorDescription ?? error.localizedDescription
completion(.failure(.systemMessage(code, message)))
}
})
}
class func getLiveBroadcast(broadcastId: String,
completion: @escaping (Result<LiveBroadcastStreamModel, YTError>) -> Void) {
let parameters: [String: AnyObject] =
[
"part": "id,snippet,contentDetails,status" as AnyObject,
"id": broadcastId as AnyObject,
"key": Credentials.APIkey as AnyObject
]
youTubeLiveVideoProvider.request(LiveStreamingAPI.liveBroadcast(parameters)) { result in
switch result {
case let .success(response):
do {
let json = try JSON(data: response.data)
let error = json["error"]
let message = error["message"].stringValue
if !message.isEmpty {
completion(.failure(.message("Error while request broadcast list" + message)))
} else {
let decoder = JSONDecoder()
let broadcastList = try decoder.decode(LiveBroadcastListModel.self, from: response.data)
let items = broadcastList.items
if let broadcast = items.first(where: { $0.id == broadcastId }) {
completion(.success(broadcast))
} else {
completion(.failure(.message("broadcast does not exist")))
}
}
} catch {
let message = "Parsing data error: \(error.localizedDescription)"
completion(.failure(.message(message)))
}
case let .failure(error):
let code = error.errorCode
let message = error.errorDescription ?? error.localizedDescription
completion(.failure(.systemMessage(code, message)))
}
}
}
// https://developers.google.com/youtube/v3/live/docs/liveBroadcasts/insert
// Creates a broadcast.
class func createLiveBroadcast(_ title: String,
startDateTime: Date,
completion: @escaping (Result<LiveBroadcastStreamModel, YTError>) -> Void) {
getHeaders { headers in
guard let headers = headers else {
completion(.failure(.message("OAuth token is not presented")))
return
}
let jsonBody = CreateLiveBroadcastBody(title: title, startDateTime: startDateTime)
guard let jsonData = try? JSONEncoder().encode(jsonBody),
let jsonString = String(data: jsonData, encoding: .utf8) else {
completion(.failure(.message("Failed while preparing request")))
return
}
let encoder = JSONBodyStringEncoding(jsonBody: jsonString)
let parameters = "liveBroadcasts?part=id,snippet,contentDetails,status&key=\(Credentials.APIkey)"
let url = "\(LiveAPI.BaseURL)/\(parameters)"
AF.request(url, method: .post, parameters: [:], encoding: encoder, headers: headers)
.validate()
.responseData { response in
switch response.result {
case .success:
guard let data = response.data else {
completion(.failure(.message("create liveBroadcasts response is empty")))
return
}
do {
let json = try JSON(data: data)
let error = json["error"].stringValue
if !error.isEmpty {
let message = json["message"].stringValue
completion(.failure(.message("Error while Youtube broadcast was creating: \(message)")))
} else {
// print(json)
let decoder = JSONDecoder()
let liveBroadcast = try decoder.decode(LiveBroadcastStreamModel.self, from: data)
completion(.success(liveBroadcast))
}
} catch {
let message = "Parsing data error: \(error.localizedDescription)"
completion(.failure(.message(message)))
}
case .failure(let error):
let code = error.responseCode ?? -1
let message = error.errorDescription ?? error.localizedDescription
completion(.failure(.systemMessage(code, message)))
}
}.cURLDescription { (description) in
print("\n====== REQUEST =======\n\(description)\n==============\n")
}
}
}
// Updates a broadcast. For example, you could modify the broadcast settings defined
// in the liveBroadcast resource's contentDetails object.
// https://developers.google.com/youtube/v3/live/docs/liveBroadcasts/update
// PUT https://www.googleapis.com/youtube/v3/liveBroadcasts
class func updateLiveBroadcast(_ broadcast: LiveBroadcastStreamModel,
completion: @escaping (Result<Void, YTError>) -> Void) {
getHeaders { headers in
guard let headers = headers else {
completion(.failure(.message("OAuth token is not presented")))
return
}
let jsonBody = UpdateLiveBroadcastBody(broadcast: broadcast)
guard let jsonData = try? JSONEncoder().encode(jsonBody),
let jsonString = String(data: jsonData, encoding: .utf8) else {
completion(.failure(.message("Failed while preparing request")))
return
}
let encoder = JSONBodyStringEncoding(jsonBody: jsonString)
let parameters = "liveBroadcasts?part=id,snippet,contentDetails,status&key=\(Credentials.APIkey)"
AF.request("\(LiveAPI.BaseURL)/\(parameters)",
method: .put,
parameters: [:],
encoding: encoder,
headers: headers)
.responseData { response in
switch response.result {
case .success:
guard let data = response.data else {
completion(.failure(.message("update broadcast response is empty")))
return
}
do {
let json = try JSON(data: data)
let error = json["error"].stringValue
if !error.isEmpty {
let message = json["message"].stringValue
completion(.failure(.message("Error while Youtube broadcast was creating" + message)))
} else {
completion(.success(Void()))
}
} catch {
let message = "Parsing data error: \(error.localizedDescription)"
completion(.failure(.message(message)))
}
case .failure(let error):
let code = error.responseCode ?? -1
let message = error.errorDescription ?? error.localizedDescription
completion(.failure(.systemMessage(code, message)))
}
}.cURLDescription { (description) in
print("\n====== REQUEST =======\n\(description)\n==============\n")
}
}
}
// POST https://www.googleapis.com/youtube/v3/liveBroadcasts/transition
// Changes the status of a YouTube live broadcast and initiates any processes associated with the new status.
// For example, when you transition a broadcast's status to testing, YouTube starts to transmit video
// to that broadcast's monitor stream. Before calling this method, you should confirm that the value of the
// status.streamStatus property for the stream bound to your broadcast is active.
class func transitionLiveBroadcast(_ boadcastId: String,
broadcastStatus: String,
completion: @escaping (Result<LiveBroadcastStreamModel, YTError>) -> Void) {
let parameters: [String: AnyObject] = [
"id": boadcastId as AnyObject,
"broadcastStatus": broadcastStatus as AnyObject,
"part": "id,snippet,contentDetails,status" as AnyObject,
"key": Credentials.APIkey as AnyObject
]
youTubeLiveVideoProvider.request(LiveStreamingAPI.transitionLiveBroadcast(parameters)) { result in
switch result {
case let .success(response):
do {
let json = try JSON(data: response.data)
let error = json["error"]
let message = error["message"].stringValue
if !message.isEmpty {
// print("Error while Youtube broadcast transition", message: message)
let text = "FAILED TRANSITION TO THE \(broadcastStatus) STATUS [\(message)]!"
completion(.failure(.message(text)))
} else {
// print(json)
let decoder = JSONDecoder()
let liveBroadcast = try decoder.decode(LiveBroadcastStreamModel.self, from: response.data)
completion(.success(liveBroadcast))
}
} catch {
let message = "Parsing data error: \(error.localizedDescription)"
completion(.failure(.message(message)))
}
case let .failure(error):
let code = error.errorCode
let message = error.errorDescription ?? error.localizedDescription
completion(.failure(.systemMessage(code, message)))
}
}
}
// Deletes a broadcast.
// DELETE https://www.googleapis.com/youtube/v3/liveBroadcasts
class func deleteLiveBroadcast(broadcastId: String, completion: @escaping (Result<Void, YTError>) -> Void) {
let parameters: [String: AnyObject] = [
"id": broadcastId as AnyObject,
"key": Credentials.APIkey as AnyObject
]
youTubeLiveVideoProvider.request(LiveStreamingAPI.deleteLiveBroadcast(parameters)) { result in
switch result {
case let .success(response):
do {
let json = try JSON(data: response.data)
let error = LiveBroadcastErrorModel.decode(json["error"])
if let code = error.code, code > 0 {
completion(.failure(.message("Failed of deleting broadcast: " + error.message!)))
} else {
// print("Broadcast deleted: \(json)")
completion(.success(Void()))
}
} catch {
let message = "Parsing data error: \(error.localizedDescription)"
completion(.failure(.message(message)))
}
case let .failure(error):
let code = error.errorCode
let message = error.errorDescription ?? error.localizedDescription
completion(.failure(.systemMessage(code, message)))
}
}
}
// Binds a YouTube broadcast to a stream or removes an existing binding between a broadcast and a stream.
// A broadcast can only be bound to one video stream, though a video stream may be bound to more than one broadcast.
// POST https://www.googleapis.com/youtube/v3/liveBroadcasts/bind
class func bindLiveBroadcast(broadcastId: String,
liveStreamId streamId: String,
completion: @escaping (Result<LiveBroadcastStreamModel, YTError>) -> Void) {
let parameters: [String: AnyObject] = [
"id": broadcastId as AnyObject,
"streamId": streamId as AnyObject,
"part": "id,snippet,contentDetails,status" as AnyObject,
"key": Credentials.APIkey as AnyObject
]
youTubeLiveVideoProvider.request(LiveStreamingAPI.bindLiveBroadcast(parameters)) { result in
switch result {
case let .success(response):
do {
let json = try JSON(data: response.data)
let error = json["error"]
let message = error["message"].stringValue
if !message.isEmpty {
let text = "Error while Youtube broadcast binding with live stream: \(message)"
completion(.failure(.message(text)))
} else {
// print(json)
let decoder = JSONDecoder()
let liveBroadcast = try decoder.decode(LiveBroadcastStreamModel.self, from: response.data)
completion(.success(liveBroadcast))
}
} catch {
let message = "Parsing data error: \(error.localizedDescription)"
completion(.failure(.message(message)))
}
case let .failure(error):
let code = error.errorCode
let message = error.errorDescription ?? error.localizedDescription
completion(.failure(.systemMessage(code, message)))
}
}
}
}
// MARK: LiveStreams requests
// https://developers.google.com/youtube/v3/live/docs/liveStreams
// A liveStream resource contains information about the video stream that you are transmitting to YouTube.
// The stream provides the content that will be broadcast to YouTube users.
// Once created, a liveStream resource can be bound to one or more liveBroadcast resources.
extension YTLiveRequest {
// Returns a list of video streams that match the API request parameters.
// https://developers.google.com/youtube/v3/live/docs/liveStreams/list
class func getLiveStream(_ liveStreamId: String, completion: @escaping (Result<LiveStreamModel, YTError>) -> Void) {
let parameters: [String: AnyObject] = [
"part": "id,snippet,cdn,status" as AnyObject,
"id": liveStreamId as AnyObject,
"key": Credentials.APIkey as AnyObject
]
youTubeLiveVideoProvider.request(LiveStreamingAPI.liveStream(parameters)) { result in
switch result {
case let .success(response):
do {
let json = try JSON(data: response.data)
let error = json["error"]
let message = error["message"].stringValue
if !message.isEmpty {
completion(.failure(.message("Error while Youtube broadcast creating: " + message)))
} else {
// print(json)
let broadcastList = LiveStreamListModel.decode(json)
let items = broadcastList.items
var liveStream: LiveStreamModel?
for item in items where item.id == liveStreamId {
liveStream = item
}
if liveStream != nil {
completion(.success(liveStream!))
} else {
completion(.failure(.message("liveStream is empty")))
}
}
} catch {
let message = "Parsing data error: \(error.localizedDescription)"
completion(.failure(.message(message)))
}
case let .failure(error):
let code = error.errorCode
let message = error.errorDescription ?? error.localizedDescription
completion(.failure(.systemMessage(code, message)))
}
}
}
// https://developers.google.com/youtube/v3/live/docs/liveStreams/insert
// Creates a video stream. The stream enables you to send your video to YouTube,
// which can then broadcast the video to your audience.
// POST https://www.googleapis.com/youtube/v3/liveStreams?part=id%2Csnippet%2Ccdn%2Cstatus&key={YOUR_API_KEY}
class func createLiveStream(_ title: String,
description: String,
streamName: String,
completion: @escaping (Result<LiveStreamModel, YTError>) -> Void) {
getHeaders { headers in
guard let headers = headers else {
completion(.failure(.message("OAuth token is not presented")))
return
}
let jsonBody = CreateLiveStreamBody(title: title, description: description, streamName: streamName)
guard let jsonData = try? JSONEncoder().encode(jsonBody),
let jsonString = String(data: jsonData, encoding: .utf8) else {
completion(.failure(.message("Failed while preparing request")))
return
}
let encoder = JSONBodyStringEncoding(jsonBody: jsonString)
let url = "\(LiveAPI.BaseURL)/liveStreams?part=id,snippet,cdn,status&key=\(Credentials.APIkey)"
AF.request(url, method: .post, parameters: [:], encoding: encoder, headers: headers)
.validate()
.responseData { response in
switch response.result {
case .success:
guard let data = response.data else {
completion(.failure(.message("createLiveStream response is empty")))
return
}
do {
let json = try JSON(data: data)
let error = json["error"]
if !error.isEmpty {
let message = json["message"].stringValue
completion(.failure(.message("Error while Youtube broadcast was creating: " + message)))
} else {
let liveStream = LiveStreamModel.decode(json)
completion(.success(liveStream))
}
} catch {
let message = "Parsing data error: \(error.localizedDescription)"
completion(.failure(.message(message)))
}
case .failure(let error):
let code = error.responseCode ?? -1
let message = error.errorDescription ?? error.localizedDescription
completion(.failure(.systemMessage(code, message)))
}
}.cURLDescription { (description) in
print("\n====== REQUEST =======\n\(description)\n==============\n")
}
}
}
// Deletes a video stream
// Request:
// DELETE https://www.googleapis.com/youtube/v3/liveStreams
class func deleteLiveStream(_ liveStreamId: String, completion: @escaping (Result<Void, YTError>) -> Void) {
let parameters: [String: AnyObject] = [
"id": liveStreamId as AnyObject,
"key": Credentials.APIkey as AnyObject
]
youTubeLiveVideoProvider.request(LiveStreamingAPI.deleteLiveStream(parameters)) { result in
switch result {
case let .success(response):
do {
let json = try JSON(data: response.data)
let error = json["error"].stringValue
if !error.isEmpty {
let message = json["message"].stringValue
completion(.failure(.message(error + ";" + message)))
} else {
print("video stream deleted: \(json)")
completion(.success(Void()))
}
} catch {
let message = "Parsing data error: \(error.localizedDescription)"
completion(.failure(.message(message)))
}
case let .failure(error):
let code = error.errorCode
let message = error.errorDescription ?? error.localizedDescription
completion(.failure(.systemMessage(code, message)))
}
}
}
// Updates a video stream. If the properties that you want to change cannot be updated,
// then you need to create a new stream with the proper settings.
// Request:
// PUT https://www.googleapis.com/youtube/v3/liveStreams
// format = 1080p 1440p 240p 360p 480p 720p
// ingestionType = dash rtmp
class func updateLiveStream(_ liveStreamId: String,
title: String,
format: String,
ingestionType: String,
completion: @escaping (Result<Void, YTError>) -> Void) {
getHeaders { headers in
guard let headers = headers else {
completion(.failure(.message("OAuth token is not presented")))
return
}
let jsonBody = UpdateLiveStreamBody(id: liveStreamId, title: title, format: format, ingestionType: ingestionType)
guard let jsonData = try? JSONEncoder().encode(jsonBody),
let jsonString = String(data: jsonData, encoding: .utf8) else {
completion(.failure(.message("Failed while preparing request")))
return
}
let encoder = JSONBodyStringEncoding(jsonBody: jsonString)
AF.request("\(LiveAPI.BaseURL)/liveStreams",
method: .put,
parameters: ["part": "id,snippet,cdn,status", "key": Credentials.APIkey],
encoding: encoder,
headers: headers)
.validate()
.responseData { response in
switch response.result {
case .success:
guard let data = response.data else {
completion(.failure(.message("updateLiveStream response is empty")))
return
}
do {
let json = try JSON(data: data)
let error = json["error"].stringValue
if !error.isEmpty {
let message = json["message"].stringValue
completion(.failure(.message("Error while Youtube broadcast was creating" + message)))
} else {
completion(.success(Void()))
}
} catch {
let message = "Parsing data error: \(error.localizedDescription)"
completion(.failure(.message(message)))
}
case .failure(let error):
let code = error.responseCode ?? -1
let message = error.errorDescription ?? error.localizedDescription
completion(.failure(.systemMessage(code, message)))
}
}.cURLDescription { (description) in
print("\n====== REQUEST =======\n\(description)\n==============\n")
}
}
}
}
| mit | 44a200ee18561403bd30fe93aceee4b7 | 49.414991 | 125 | 0.52464 | 5.633708 | false | false | false | false |
iOkay/MiaoWuWu | Pods/Material/Sources/iOS/ToolbarController.swift | 1 | 7551 | /*
* Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
extension UIViewController {
/**
A convenience property that provides access to the ToolbarController.
This is the recommended method of accessing the ToolbarController
through child UIViewControllers.
*/
public var toolbarController: ToolbarController? {
var viewController: UIViewController? = self
while nil != viewController {
if viewController is ToolbarController {
return viewController as? ToolbarController
}
viewController = viewController?.parent
}
return nil
}
}
@objc(ToolbarControllerDelegate)
public protocol ToolbarControllerDelegate {
/// Delegation method that executes when the floatingViewController will open.
@objc
optional func toolbarControllerWillOpenFloatingViewController(toolbarController: ToolbarController)
/// Delegation method that executes when the floatingViewController will close.
@objc
optional func toolbarControllerWillCloseFloatingViewController(toolbarController: ToolbarController)
/// Delegation method that executes when the floatingViewController did open.
@objc
optional func toolbarControllerDidOpenFloatingViewController(toolbarController: ToolbarController)
/// Delegation method that executes when the floatingViewController did close.
@objc
optional func toolbarControllerDidCloseFloatingViewController(toolbarController: ToolbarController)
}
@objc(ToolbarController)
open class ToolbarController: StatusBarController {
/**
A Display value to indicate whether or not to
display the rootViewController to the full view
bounds, or up to the toolbar height.
*/
open var display = Display.partial {
didSet {
layoutSubviews()
}
}
/// Reference to the Toolbar.
open private(set) lazy var toolbar: Toolbar = Toolbar()
/// Internal reference to the floatingViewController.
private var internalFloatingViewController: UIViewController?
/// Delegation handler.
open weak var delegate: ToolbarControllerDelegate?
/// A floating UIViewController.
open var floatingViewController: UIViewController? {
get {
return internalFloatingViewController
}
set(value) {
if let v = internalFloatingViewController {
v.view.layer.rasterizationScale = Device.scale
v.view.layer.shouldRasterize = true
delegate?.toolbarControllerWillCloseFloatingViewController?(toolbarController: self)
internalFloatingViewController = nil
UIView.animate(withDuration: 0.5,
animations: { [weak self] in
if let s = self {
v.view.center.y = 2 * s.view.bounds.height
s.toolbar.alpha = 1
s.rootViewController.view.alpha = 1
}
}) { [weak self] _ in
if let s = self {
v.willMove(toParentViewController: nil)
v.view.removeFromSuperview()
v.removeFromParentViewController()
v.view.layer.shouldRasterize = false
s.isUserInteractionEnabled = true
s.toolbar.isUserInteractionEnabled = true
DispatchQueue.main.async { [weak self] in
if let s = self {
s.delegate?.toolbarControllerDidCloseFloatingViewController?(toolbarController: s)
}
}
}
}
}
if let v = value {
// Add the noteViewController! to the view.
addChildViewController(v)
v.view.frame = view.bounds
v.view.center.y = 2 * view.bounds.height
v.view.isHidden = true
view.insertSubview(v.view, aboveSubview: toolbar)
v.view.layer.zPosition = 1500
v.didMove(toParentViewController: self)
v.view.isHidden = false
v.view.layer.rasterizationScale = Device.scale
v.view.layer.shouldRasterize = true
view.layer.rasterizationScale = Device.scale
view.layer.shouldRasterize = true
internalFloatingViewController = v
isUserInteractionEnabled = false
toolbar.isUserInteractionEnabled = false
delegate?.toolbarControllerWillOpenFloatingViewController?(toolbarController: self)
UIView.animate(withDuration: 0.5,
animations: { [weak self, v = v] in
guard let s = self else {
return
}
v.view.center.y = s.view.bounds.height / 2
s.toolbar.alpha = 0.5
s.rootViewController.view.alpha = 0.5
}) { [weak self, v = v] _ in
guard let s = self else {
return
}
v.view.layer.shouldRasterize = false
s.view.layer.shouldRasterize = false
DispatchQueue.main.async { [weak self] in
if let s = self {
s.delegate?.toolbarControllerDidOpenFloatingViewController?(toolbarController: s)
}
}
}
}
}
}
open override func layoutSubviews() {
super.layoutSubviews()
statusBar.layoutIfNeeded()
let y = 0 == statusBar.zPosition ? 0 : statusBar.height
let p = y + toolbar.height
toolbar.y = y
toolbar.width = view.width
switch display {
case .partial:
rootViewController.view.y = p
rootViewController.view.height = view.height - p
case .full:
rootViewController.view.frame = view.bounds
}
}
/**
Prepares the view instance when intialized. When subclassing,
it is recommended to override the prepare method
to initialize property values and other setup operations.
The super.prepare method should always be called immediately
when subclassing.
*/
open override func prepare() {
super.prepare()
prepareToolbar()
}
/// Prepares the toolbar.
private func prepareToolbar() {
toolbar.depthPreset = .depth1
view.addSubview(toolbar)
}
}
| gpl-3.0 | 7d6420a3520ab7f202117a11edd6ead3 | 35.302885 | 113 | 0.679115 | 4.74309 | false | false | false | false |
debugsquad/metalic | metalic/View/Home/VHomeMenuCell.swift | 1 | 2673 | import UIKit
class VHomeMenuCell:UICollectionViewCell
{
weak var label:UILabel!
weak var imageView:UIImageView!
private let kLabelHeight:CGFloat = 16
private let kLabelBottom:CGFloat = 5
override init(frame:CGRect)
{
super.init(frame:frame)
clipsToBounds = true
let label:UILabel = UILabel()
label.isUserInteractionEnabled = false
label.translatesAutoresizingMaskIntoConstraints = false
label.backgroundColor = UIColor.clear
label.textAlignment = NSTextAlignment.center
label.font = UIFont.medium(size:12)
self.label = label
let imageView:UIImageView = UIImageView()
imageView.clipsToBounds = true
imageView.isUserInteractionEnabled = false
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = UIViewContentMode.center
self.imageView = imageView
addSubview(label)
addSubview(imageView)
let views:[String:UIView] = [
"label":label,
"imageView":imageView]
let metrics:[String:CGFloat] = [
"labelHeight":kLabelHeight,
"labelBottom":kLabelBottom]
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"H:|-0-[label]-0-|",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"H:|-0-[imageView]-0-|",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"V:|-0-[imageView]-0-[label(labelHeight)]-(labelBottom)-|",
options:[],
metrics:metrics,
views:views))
}
required init?(coder:NSCoder)
{
fatalError()
}
override var isSelected:Bool
{
didSet
{
hover()
}
}
override var isHighlighted:Bool
{
didSet
{
hover()
}
}
//MARK: private
private func hover()
{
if isSelected || isHighlighted
{
backgroundColor = UIColor.main
label.textColor = UIColor.white
}
else
{
backgroundColor = UIColor.clear
label.textColor = UIColor(white:0.75, alpha:1)
}
}
//MARK: public
func config(model:MFiltersItem)
{
label.text = model.name
imageView.image = UIImage(named:model.asset)
hover()
}
}
| mit | 160d5a5078315ff1b3f913220facf963 | 24.951456 | 88 | 0.563786 | 5.534161 | false | false | false | false |
rtm-ctrlz/ParrotZik-OSX | ParrotZik/AppDelegate.swift | 1 | 4203 | //
// AppDelegate.swift
// ParrotZik
//
// Created by Внештатный командир земли on 17/02/15.
// Copyright (c) 2015 Внештатный командир земли. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate, NSUserNotificationCenterDelegate {
@IBOutlet var statusMenu: NSMenu!
var statusItem: NSStatusItem
var readyForNotifications: Bool = false
lazy var pstate: ParrotState = ParrotState(item: self.statusItem)
lazy var con: ParrotConnection = ParrotConnection(state: self.pstate, statusUp: self.updateStatusItem)
override func awakeFromNib() {
self.statusItem.menu = self.statusMenu
self.statusItem.highlightMode = true
}
override init() {
self.statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(CGFloat(-1))
}
func applicationDidFinishLaunching(aNotification: NSNotification?) {
self.updateStatusItem()
self.readyForNotifications = true
self.statusItem.menu!.removeAllItems()
for i in self.pstate.getMenuItems() {
self.statusItem.menu!.addItem(i)
}
self.statusItem.menu!.addItem(NSMenuItem.separatorItem())
self.statusItem.menu!.addItem(NSMenuItem(title: "About ParrotZik", action: "statusMenuItemAboutZik_Action:", keyEquivalent: ""))
self.statusItem.menu!.addItem(NSMenuItem(title: "About ParrotZik OSX", action: "statusMenuItemAbout_Action:", keyEquivalent: ""))
self.statusItem.menu!.addItem(NSMenuItem.separatorItem())
self.statusItem.menu!.addItem(NSMenuItem(title: "Quit", action: "statusMenuItemQuit_Action:", keyEquivalent: ""))
self.con.start()
}
func updateStatusItem() {
if self.con.isConnected {
self.pstate.updateStatusItem(self.statusItem)
self.showNotificationConnected()
} else if self.con.isConnecting {
self.statusItem.title = "Connecting..."
} else {
self.statusItem.title = ""
self.showNotificationDisconnected()
}
self.statusItem.length = CGFloat(0)
if self.statusItem.title != "" {
var image = NSImage(named: "zik-audio-headset")
if image != nil {
image!.size = NSSize(width: 16, height: 16)
image!.setTemplate(true)
self.statusItem.image = image!
}
self.statusItem.length = CGFloat(-1)
}
}
func statusMenuItemAboutZik_Action(sender: NSMenuItem) {
NSWorkspace.sharedWorkspace().openURL(NSURL(string: "http://www.parrot.com/zik")!)
}
func statusMenuItemAbout_Action(sender: NSMenuItem) {
NSWorkspace.sharedWorkspace().openURL(NSURL(string: "https://github.com/rtm-ctrlz/ParrotZik-OSX")!)
}
func statusMenuItemQuit_Action(sender: NSMenuItem) {
NSApplication.sharedApplication().terminate(self)
}
func stateMenuItemClick(sender: NSMenuItem) {
self.pstate.forwardMenuItemClick(sender)
}
func sendNotification(title:String, subtitle:String) -> NSUserNotification? {
if !self.readyForNotifications {
return nil
}
var notification:NSUserNotification = NSUserNotification()
notification.title = title
notification.subtitle = subtitle
notification.deliveryDate = NSDate()
var notificationcenter:NSUserNotificationCenter = NSUserNotificationCenter.defaultUserNotificationCenter()
notificationcenter.delegate = self
notificationcenter.scheduleNotification(notification)
return notification
}
func showNotificationDisconnected() {
self.sendNotification("Parrot Zik", subtitle: "disconnected")
}
func showNotificationConnected() {
self.sendNotification("Parrot Zik", subtitle: "connected")
}
func userNotificationCenter(center: NSUserNotificationCenter, shouldPresentNotification notification: NSUserNotification) -> Bool {
return true
}
}
| gpl-2.0 | 861e36af40f02aafbd5db74f28f45f02 | 34.529915 | 137 | 0.658167 | 4.94881 | false | false | false | false |
johnno1962/GitDiff9 | LNXcodeSupport/KeyPath.swift | 1 | 933 | //
// KeyPath.swift
// LNProvider
//
// Created by John Holdsworth on 09/06/2017.
// Copyright © 2017 John Holdsworth. All rights reserved.
//
import Foundation
@objc public class KeyPath: NSObject {
@objc public class func object(for keyPath: String, from: AnyObject) -> AnyObject {
var out = from
for key in keyPath.components(separatedBy: ".") {
for (name, value) in Mirror(reflecting: out).children {
if name == key || name == key + ".storage" {
let mirror = Mirror(reflecting: value)
if mirror.displayStyle == .optional,
let value = mirror.children.first?.value {
out = value as AnyObject
} else {
out = value as AnyObject
}
break
}
}
}
return out
}
}
| mit | 2b9c47b6d18385fcb1291a20dddd5c2b | 29.064516 | 87 | 0.497854 | 4.931217 | false | false | false | false |
ayvazj/BrundleflyiOS | Pod/Classes/BtfyLoader.swift | 1 | 3317 | /*
* Copyright (c) 2015 James Ayvaz
*
* 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.
*/
class BtfyLoader {
internal static func bundleFileAsStage(filename: String, ofType: String, inDirectory: String) throws -> BtfyStage? {
let bundle = NSBundle.mainBundle()
let path = bundle.pathForResource(filename, ofType: ofType, inDirectory: inDirectory)
if (NSFileManager.defaultManager().fileExistsAtPath(path!)) {
do {
let json = try NSJSONSerialization.JSONObjectWithData(NSFileManager.defaultManager().contentsAtPath(path!)!, options: []) as! [String:AnyObject]
guard let type = json["type"] as? String else {
throw BtfyError.ParseError(msg: "Stage type is missing.")
}
if !(type == "stage") {
throw BtfyError.ParseError(msg: "Unexpected stage type: \(type)")
}
guard let size = json["size"] as? [String:AnyObject] else {
throw BtfyError.ParseError(msg: "Stage is missing size.")
}
guard let animationList = json["animations"] as? [[String:AnyObject]] else {
throw BtfyError.ParseError(msg: "Stage is missing animations.")
}
var animationGroups : [BtfyAnimationGroup] = []
for animationGroup in animationList {
do {
if let group = try BtfyJson.parseAnimationGroup(animationGroup) {
animationGroups.append(group);
}
}
catch let err as NSError {
print(err)
}
}
do {
return try BtfyStage(sizeInfo: BtfyJson.parseSize(size), animationGroups: animationGroups)
}
catch let err as NSError {
throw err
}
} catch let error as NSError {
print("json error: \(error.localizedDescription)")
}
}
return nil
}
} | mit | 80dfaf0f2340b69f8d91b12ae36c3ae2 | 42.657895 | 160 | 0.575219 | 5.367314 | false | false | false | false |
googlemaps/last-mile-fleet-solution-samples | ios_driverapp_samples/LMFSDriverSampleApp/ListTab/Details/TaskDetails.swift | 1 | 1884 | /*
* Copyright 2022 Google LLC. 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 SwiftUI
/// This view defines the details of a task, and buttons which let the driver to update the task
/// status.
struct TaskDetails: View {
@ObservedObject var task: ModelData.Task
@EnvironmentObject var modelData: ModelData
var body: some View {
let taskInfo = task.taskInfo
VStack(alignment: HorizontalAlignment.leading) {
if let contactName = taskInfo.contactName {
Text(contactName)
.fontWeight(.semibold)
.padding(EdgeInsets(top: 0, leading: 0, bottom: 10, trailing: 0))
}
switch task.taskInfo.taskType {
case .PICKUP:
Text("Pick up")
.fontWeight(.semibold)
case .SCHEDULED_STOP:
Text("Scheduled stop")
.fontWeight(.semibold)
case .DELIVERY, .UNAVAIALBLE:
EmptyView()
}
Text("ID: \(taskInfo.taskId)")
TaskButtons(task: task)
}
}
}
struct TaskDetails_Previews: PreviewProvider {
static var previews: some View {
let _ = LMFSDriverSampleApp.googleMapsInited
let modelData = ModelData(filename: "test_manifest")
let stop = modelData.stops[0]
let task = modelData.tasks(stop: stop)[0]
TaskDetails(task: task)
.environmentObject(modelData)
.previewLayout(.sizeThatFits)
}
}
| apache-2.0 | 114f2a2a60a8185ca1da0a096fe1034c | 30.4 | 96 | 0.683121 | 4.177384 | false | false | false | false |
banxi1988/BXAppKit | BXiOSUtils/TextFactory.swift | 1 | 1905 | //
// AttributedTextFactory.swift
// Pods
//
// Created by Haizhen Lee on 15/12/23.
//
//
import UIKit
open class AttributedTextCreator{
public var textColor:UIColor
public var font:UIFont
public init(textColor:UIColor = .darkText, font:UIFont = UIFont.systemFont(ofSize: 15)){
self.textColor = textColor
self.font = font
}
public func create(text:String) -> NSAttributedString{
return NSAttributedString(string: text, attributes: [
NSAttributedStringKey.font:font,
NSAttributedStringKey.foregroundColor:textColor
])
}
}
public struct AttributedText{
public var textColor:UIColor
public var font:UIFont
public fileprivate(set) var text:String
public init(text:String,fontSize: CGFloat = 15,fontWeight:UIFont.Weight = .regular, textColor:UIColor = UIColor.darkText){
self.init(text:text, font: UIFont.systemFont(ofSize: fontSize,weight:fontWeight), textColor: textColor)
}
public init(text:String,font:UIFont = UIFont.systemFont(ofSize: 15),textColor:UIColor = UIColor.darkText){
self.text = text
self.font = font
self.textColor = textColor
}
public var attributedText:NSAttributedString{
return NSAttributedString(string: text, attributes: [NSAttributedStringKey.font:font,NSAttributedStringKey.foregroundColor:textColor])
}
}
public struct TextFactory{
public static func createAttributedText(_ textAttributes:[AttributedText]) -> NSAttributedString{
let attributedText = NSMutableAttributedString()
for attr in textAttributes{
attributedText.append(attr.attributedText)
}
return attributedText
}
public static func createAttributedText(_ textAttributes:[NSAttributedString]) -> NSAttributedString{
let attributedText = NSMutableAttributedString()
for attr in textAttributes{
attributedText.append(attr)
}
return attributedText
}
}
| mit | 7e4908711552fc903286fff02a5c3bee | 25.09589 | 138 | 0.736483 | 4.7625 | false | false | false | false |
jmgc/swift | test/attr/attr_inlinable.swift | 1 | 12179 | // RUN: %target-typecheck-verify-swift -swift-version 5
// RUN: %target-typecheck-verify-swift -swift-version 5 -enable-testing
// RUN: %target-typecheck-verify-swift -swift-version 5 -enable-library-evolution
// RUN: %target-typecheck-verify-swift -swift-version 5 -enable-library-evolution -enable-testing
@inlinable struct TestInlinableStruct {}
// expected-error@-1 {{'@inlinable' attribute cannot be applied to this declaration}}
@inlinable @usableFromInline func redundantAttribute() {}
// expected-warning@-1 {{'@inlinable' declaration is already '@usableFromInline'}}
private func privateFunction() {}
// expected-note@-1 2{{global function 'privateFunction()' is not '@usableFromInline' or public}}
fileprivate func fileprivateFunction() {}
// expected-note@-1{{global function 'fileprivateFunction()' is not '@usableFromInline' or public}}
func internalFunction() {}
// expected-note@-1 2{{global function 'internalFunction()' is not '@usableFromInline' or public}}
@usableFromInline func versionedFunction() {}
public func publicFunction() {}
private struct PrivateStruct {}
// expected-note@-1 5{{struct 'PrivateStruct' is not '@usableFromInline' or public}}
// expected-note@-2 2{{initializer 'init()' is not '@usableFromInline' or public}}
struct InternalStruct {}
// expected-note@-1 3{{struct 'InternalStruct' is not '@usableFromInline' or public}}
// expected-note@-2 {{initializer 'init()' is not '@usableFromInline' or public}}
@usableFromInline struct VersionedStruct {
@usableFromInline init() {}
}
public struct PublicStruct {
public init() {}
@inlinable public var storedProperty: Int
// expected-error@-1 {{'@inlinable' attribute cannot be applied to stored properties}}
@inlinable public lazy var lazyProperty: Int = 0
// expected-error@-1 {{'@inlinable' attribute cannot be applied to stored properties}}
}
public struct Struct {
@_transparent
public func publicTransparentMethod() {
struct Nested {}
// expected-error@-1 {{type 'Nested' cannot be nested inside a '@_transparent' function}}
publicFunction()
// OK
versionedFunction()
// OK
internalFunction()
// expected-error@-1 {{global function 'internalFunction()' is internal and cannot be referenced from a '@_transparent' function}}
fileprivateFunction()
// expected-error@-1 {{global function 'fileprivateFunction()' is fileprivate and cannot be referenced from a '@_transparent' function}}
privateFunction()
// expected-error@-1 {{global function 'privateFunction()' is private and cannot be referenced from a '@_transparent' function}}
}
@inlinable
public func publicInlinableMethod() {
struct Nested {}
// expected-error@-1 {{type 'Nested' cannot be nested inside an '@inlinable' function}}
let _: PublicStruct
let _: VersionedStruct
let _: InternalStruct
// expected-error@-1 {{struct 'InternalStruct' is internal and cannot be referenced from an '@inlinable' function}}
let _: PrivateStruct
// expected-error@-1 {{struct 'PrivateStruct' is private and cannot be referenced from an '@inlinable' function}}
let _ = PublicStruct.self
let _ = VersionedStruct.self
let _ = InternalStruct.self
// expected-error@-1 {{struct 'InternalStruct' is internal and cannot be referenced from an '@inlinable' function}}
let _ = PrivateStruct.self
// expected-error@-1 {{struct 'PrivateStruct' is private and cannot be referenced from an '@inlinable' function}}
let _ = PublicStruct()
let _ = VersionedStruct()
let _ = InternalStruct()
// expected-error@-1 {{struct 'InternalStruct' is internal and cannot be referenced from an '@inlinable' function}}
// expected-error@-2 {{initializer 'init()' is internal and cannot be referenced from an '@inlinable' function}}
let _ = PrivateStruct()
// expected-error@-1 {{struct 'PrivateStruct' is private and cannot be referenced from an '@inlinable' function}}
// expected-error@-2 {{initializer 'init()' is private and cannot be referenced from an '@inlinable' function}}
}
private func privateMethod() {}
// expected-note@-1 {{instance method 'privateMethod()' is not '@usableFromInline' or public}}
@_transparent
@usableFromInline
func versionedTransparentMethod() {
struct Nested {}
// expected-error@-1 {{type 'Nested' cannot be nested inside a '@_transparent' function}}
privateMethod()
// expected-error@-1 {{instance method 'privateMethod()' is private and cannot be referenced from a '@_transparent' function}}
}
@inlinable
func internalInlinableMethod() {
struct Nested {}
// expected-error@-1 {{type 'Nested' cannot be nested inside an '@inlinable' function}}
}
@_transparent
func internalTransparentMethod() {
struct Nested {}
// OK
}
@inlinable
private func privateInlinableMethod() {
// expected-error@-2 {{'@inlinable' attribute can only be applied to public declarations, but 'privateInlinableMethod' is private}}
struct Nested {}
// expected-error@-1 {{type 'Nested' cannot be nested inside an '@inlinable' function}}
}
@inline(__always)
func internalInlineAlwaysMethod() {
struct Nested {}
// OK
}
}
// Make sure protocol extension members can reference protocol requirements
// (which do not inherit the @usableFromInline attribute).
@usableFromInline
protocol VersionedProtocol {
associatedtype T
func requirement() -> T
}
extension VersionedProtocol {
func internalMethod() {}
// expected-note@-1 {{instance method 'internalMethod()' is not '@usableFromInline' or public}}
@inlinable
func versionedMethod() -> T {
internalMethod()
// expected-error@-1 {{instance method 'internalMethod()' is internal and cannot be referenced from an '@inlinable' function}}
return requirement()
}
}
enum InternalEnum {
// expected-note@-1 2{{enum 'InternalEnum' is not '@usableFromInline' or public}}
// expected-note@-2 {{type declared here}}
case apple
// expected-note@-1 {{enum case 'apple' is not '@usableFromInline' or public}}
case orange
// expected-note@-1 {{enum case 'orange' is not '@usableFromInline' or public}}
}
@inlinable public func usesInternalEnum() {
_ = InternalEnum.apple
// expected-error@-1 {{enum 'InternalEnum' is internal and cannot be referenced from an '@inlinable' function}}
// expected-error@-2 {{enum case 'apple' is internal and cannot be referenced from an '@inlinable' function}}
let _: InternalEnum = .orange
// expected-error@-1 {{enum 'InternalEnum' is internal and cannot be referenced from an '@inlinable' function}}
// expected-error@-2 {{enum case 'orange' is internal and cannot be referenced from an '@inlinable' function}}
}
@usableFromInline enum VersionedEnum {
case apple
case orange
case pear(InternalEnum)
// expected-error@-1 {{type of enum case in '@usableFromInline' enum must be '@usableFromInline' or public}}
case persimmon(String)
}
@inlinable public func usesVersionedEnum() {
_ = VersionedEnum.apple
let _: VersionedEnum = .orange
_ = VersionedEnum.persimmon
}
// Inherited initializers - <rdar://problem/34398148>
@usableFromInline
@_fixed_layout
class Base {
@usableFromInline
init(x: Int) {}
}
@usableFromInline
@_fixed_layout
class Middle : Base {}
@usableFromInline
@_fixed_layout
class Derived : Middle {
@inlinable
init(y: Int) {
super.init(x: y)
}
}
// More inherited initializers
@_fixed_layout
public class Base2 {
@inlinable
public init(x: Int) {}
}
@_fixed_layout
@usableFromInline
class Middle2 : Base2 {}
@_fixed_layout
@usableFromInline
class Derived2 : Middle2 {
@inlinable
init(y: Int) {
super.init(x: y)
}
}
// Even more inherited initializers - https://bugs.swift.org/browse/SR-10940
@_fixed_layout
public class Base3 {}
// expected-note@-1 {{initializer 'init()' is not '@usableFromInline' or public}}
@_fixed_layout
public class Derived3 : Base3 {
@inlinable
public init(_: Int) {}
// expected-error@-1 {{initializer 'init()' is internal and cannot be referenced from an '@inlinable' function}}
}
@_fixed_layout
public class Base4 {}
@_fixed_layout
@usableFromInline
class Middle4 : Base4 {}
// expected-note@-1 {{initializer 'init()' is not '@usableFromInline' or public}}
@_fixed_layout
@usableFromInline
class Derived4 : Middle4 {
@inlinable
public init(_: Int) {}
// expected-error@-1 {{initializer 'init()' is internal and cannot be referenced from an '@inlinable' function}}
}
// Stored property initializer expressions.
//
// Note the behavior here does not depend on the state of the -enable-library-evolution
// flag; the test runs with both the flag on and off. Only the explicit
// presence of a '@_fixed_layout' attribute determines the behavior here.
let internalGlobal = 0
// expected-note@-1 {{let 'internalGlobal' is not '@usableFromInline' or public}}
public let publicGlobal = 0
struct InternalStructWithInit {
var x = internalGlobal // OK
var y = publicGlobal // OK
}
public struct PublicResilientStructWithInit {
var x = internalGlobal // OK
var y = publicGlobal // OK
}
private func privateIntReturningFunc() -> Int { return 0 }
internal func internalIntReturningFunc() -> Int { return 0 }
@frozen
public struct PublicFixedStructWithInit {
var x = internalGlobal // expected-error {{let 'internalGlobal' is internal and cannot be referenced from a property initializer in a '@frozen' type}}
var y = publicGlobal // OK
// Static property initializers are not inlinable contexts.
static var z = privateIntReturningFunc() // OK
static var a = internalIntReturningFunc() // OK
// Test the same with a multi-statement closure, which introduces a
// new DeclContext.
static var zz: Int = {
let x = privateIntReturningFunc()
return x
}()
static var aa: Int = {
let x = internalIntReturningFunc()
return x
}()
}
public struct KeypathStruct {
var x: Int
// expected-note@-1 {{property 'x' is not '@usableFromInline' or public}}
@inlinable public func usesKeypath() {
_ = \KeypathStruct.x
// expected-error@-1 {{property 'x' is internal and cannot be referenced from an '@inlinable' function}}
}
}
public struct HasInternalSetProperty {
public internal(set) var x: Int // expected-note {{setter for 'x' is not '@usableFromInline' or public}}
@inlinable public mutating func setsX() {
x = 10 // expected-error {{setter for 'x' is internal and cannot be referenced from an '@inlinable' function}}
}
}
@usableFromInline protocol P {
typealias T = Int
}
extension P {
@inlinable func f() {
_ = T.self // ok, typealias inherits @usableFromInline from P
}
}
// rdar://problem/60605117
public struct PrivateInlinableCrash {
@inlinable // expected-error {{'@inlinable' attribute can only be applied to public declarations, but 'formatYesNo' is private}}
private func formatYesNo(_ value: Bool) -> String {
value ? "YES" : "NO"
}
}
// https://bugs.swift.org/browse/SR-12404
@inlinable public func inlinableOuterFunction() {
func innerFunction1(x: () = privateFunction()) {}
// expected-error@-1 {{global function 'privateFunction()' is private and cannot be referenced from a default argument value}}
func innerFunction2(x: () = internalFunction()) {}
// expected-error@-1 {{global function 'internalFunction()' is internal and cannot be referenced from a default argument value}}
func innerFunction3(x: () = versionedFunction()) {}
func innerFunction4(x: () = publicFunction()) {}
}
// This is OK -- lazy property initializers are emitted inside the getter,
// which is never @inlinable.
@frozen public struct LazyField {
public lazy var y: () = privateFunction()
@inlinable private lazy var z: () = privateFunction()
// expected-error@-1 {{'@inlinable' attribute cannot be applied to stored properties}}
}
@inlinable public func nestedBraceStmtTest() {
if true {
let _: PrivateStruct = PrivateStruct()
// expected-error@-1 2{{struct 'PrivateStruct' is private and cannot be referenced from an '@inlinable' function}}
// expected-error@-2 {{initializer 'init()' is private and cannot be referenced from an '@inlinable' function}}
}
}
| apache-2.0 | 1edb7c34f4d87c6e2ac1946722f9b8a1 | 32.924791 | 152 | 0.710649 | 4.286871 | false | false | false | false |
khanirteza/fusion | Fusion/Fusion/SeeAllViewController.swift | 1 | 3970 | //
// SeeAllViewController.swift
//
//
// Created by vamsi krishna reddy kamjula on 8/7/17.
//
import UIKit
class SeeAllViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var mytableView: UITableView!
var urlString: String?
var MovieDetails = [[String:Any]]()
var x:Bool?
var y:Bool?
override func viewDidLoad() {
super.viewDidLoad()
setNavigationBar()
if x == false {
let modal = TVModel.init()
modal.NetworkCall(urlString: urlString!) {
details in
self.MovieDetails.append(contentsOf: details)
self.mytableView?.reloadData()
}
} else {
let url = URL.init(string: urlString!)
let baseUrl = "http://image.tmdb.org/t/p/w780/"
do {
let data = try Data.init(contentsOf: url!)
let response = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [String:Any]
let results = response["results"] as! [[String:Any]]
for temp in results {
let id = temp["id"] as! Double
let voteAverage = temp["vote_average"] as! Double
let title = temp["title"] as! String
let poster = temp["poster_path"] as! String
let posterurl = baseUrl + poster
let backdrop = temp["backdrop_path"] as! String
let backdropurl = baseUrl + backdrop
let overview = temp["overview"] as! String
let releaseDate = temp["release_date"] as! String
MovieDetails.append(["Title":title, "ID":id, "Rating":voteAverage, "Poster":posterurl, "BackdropPoster":backdropurl, "Overview":overview, "Released":releaseDate])
}
} catch let err {
print(err)
}
}
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return MovieDetails.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath)
cell.textLabel?.text = MovieDetails[indexPath.row]["Title"] as? String
cell.detailTextLabel?.text = MovieDetails[indexPath.row]["Released"] as? String
let url = URL.init(string: (MovieDetails[indexPath.row]["Poster"] as? String)!)
do {
let data = try Data.init(contentsOf: url!)
let image = UIImage.init(data: data)
cell.imageView?.image = image
}catch let err {
print(err)
}
return cell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "tableViewCellSegue" {
let destinationVC = segue.destination as! DetailsViewController
if y == true {
destinationVC.x = true
} else {
destinationVC.x = false
}
let indexPath = self.mytableView.indexPathForSelectedRow
destinationVC.title = MovieDetails[indexPath!.row]["Title"] as? String
destinationVC.detailArray = MovieDetails[indexPath!.row]
}
}
func setNavigationBar(){
let userProfilePhoto = UserDataProvider.getUserPhoto()
let userProfileButtonView = UIImageView(frame: CGRect(x: 0, y: 150, width: 40, height: 40))
userProfileButtonView.contentMode = .scaleAspectFit
userProfileButtonView.image = userProfilePhoto
let userPhotoButton = UIBarButtonItem(customView: userProfileButtonView)
navigationItem.leftBarButtonItem = userPhotoButton
}
}
| apache-2.0 | 80a569da2f1ccb688d039f4adba22791 | 37.921569 | 182 | 0.578589 | 5.149157 | false | false | false | false |
kenwilcox/iOS8SwiftMapKit | iOS8SwiftMapKit/ViewController.swift | 1 | 4637 | //
// ViewController.swift
// iOS8SwiftMapKit
//
// Created by Kenneth Wilcox on 1/4/15.
// Copyright (c) 2015 Kenneth Wilcox. All rights reserved.
//
import UIKit
import MapKit
class ViewController: UIViewController, MKMapViewDelegate {
@IBOutlet weak var mapView: MKMapView!
@IBAction func buttonPressed(sender: AnyObject) {
// keep this around for debugging
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.mapView.delegate = self
let location = CLLocationCoordinate2D (latitude: 43.583962700238274, longitude: -116.67824378418591)
let span = MKCoordinateSpan(latitudeDelta: 1.5, longitudeDelta: 1.5) // 0.85 previously
let region = MKCoordinateRegion(center: location, span: span)
self.mapView.setRegion(region, animated: true)
self.mapView.mapType = .Standard
for pollingLocation in PollingLocations.allPollingLocations {
let precinctLocation = CLLocationCoordinate2D(latitude: pollingLocation.latitude, longitude: pollingLocation.longitude)
let annotation = MKPointAnnotation()
annotation.setCoordinate(precinctLocation)
annotation.title = "\(pollingLocation.precinctNo): \(pollingLocation.name)".capitalizedString
annotation.subtitle = pollingLocation.address.capitalizedString
self.mapView.addAnnotation(annotation)
}
// var coordinates = [CLLocationCoordinate2DMake(43.786266, -116.943101),
// CLLocationCoordinate2DMake(43.725804, -116.800402),
// CLLocationCoordinate2DMake(43.735839, -116.696920)]
// let overlay = MKPolygon(coordinates: &coordinates, count: coordinates.count)
//
// self.mapView.addOverlay(overlay)
var northEast = CLLocationCoordinate2DMake(43.85532635264545, -116.17790222851562)
var neOrigin: MKMapPoint = MKMapPointForCoordinate(northEast)
var southWest = CLLocationCoordinate2DMake(43.358137025577584, -117.1392059394531)
var swOrigin = MKMapPointForCoordinate(southWest)
var size: MKMapSize = MKMapSizeMake(swOrigin.x - neOrigin.x, swOrigin.y - neOrigin.y)
var origin = MKMapPoint(x: swOrigin.x - neOrigin.x, y: swOrigin.y - neOrigin.y)
var rect: MKMapRect = MKMapRect(origin: neOrigin, size: size)
var county = CountyOverlay(rect: rect)
self.mapView.addOverlay(county)
let ne = MKPointAnnotation()
ne.setCoordinate(northEast)
ne.title = "northEast"
self.mapView.addAnnotation(ne)
let sw = MKPointAnnotation()
sw.setCoordinate(southWest)
sw.title = "southWest"
self.mapView.addAnnotation(sw)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
if annotation is MKUserLocation {
//return nil so map view draws "blue dot" for standard user location
return nil
}
let reuseId = "pin"
var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) as? MKPinAnnotationView
if pinView == nil {
pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
pinView!.canShowCallout = true
pinView!.animatesDrop = true
pinView!.pinColor = .Purple
//pinView!.image = UIImage(named: "vote-hereSmall.png")
//pinView!.calloutOffset = CGPoint(x: 0.0, y: 32.0)
}
else {
pinView!.annotation = annotation
}
return pinView
}
func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! {
if overlay is MKPolygon {
var view = MKPolygonRenderer(overlay: overlay)
view!.fillColor = UIColor.cyanColor().colorWithAlphaComponent(0.2)
view!.strokeColor = UIColor.blueColor().colorWithAlphaComponent(0.7)
view!.lineWidth = 3.0
return view
}
else if overlay is CountyOverlay {
/*
UIImage *magicMountainImage = [UIImage imageNamed:@"overlay_park"];
PVParkMapOverlayView *overlayView = [[PVParkMapOverlayView alloc] initWithOverlay:overlay overlayImage:magicMountainImage];
return overlayView;
*/
let countyImage = UIImage(named: "canyon.png")
let view = CountyRenderer(overlay: overlay, image: countyImage!)
return view
}
return nil
}
func mapView(mapView: MKMapView!, viewForOverlay overlay: MKOverlay!) -> MKOverlayView! {
var pV = MKPolygonView(overlay: overlay)
return pV
}
}
| mit | 7eac2f90f97e5a6d4690cbb840ca9532 | 33.864662 | 129 | 0.703688 | 4.428844 | false | false | false | false |
kaojohnny/CoreStore | Sources/Setup/StorageInterfaces/LegacySQLiteStore.swift | 1 | 9830 | //
// LegacySQLiteStore.swift
// CoreStore
//
// Copyright © 2016 John Rommel Estropia
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import CoreData
// MARK: - LegacySQLiteStore
/**
A storage interface backed by an SQLite database that was created before CoreStore 2.0.0.
- Warning: The default SQLite file location for the `LegacySQLiteStore` and `SQLiteStore` are different. If the app was depending on CoreStore's default directories prior to 2.0.0, make sure to use `LegacySQLiteStore` instead of `SQLiteStore`.
*/
public final class LegacySQLiteStore: LocalStorage, DefaultInitializableStore {
/**
Initializes an SQLite store interface from the given SQLite file URL. When this instance is passed to the `DataStack`'s `addStorage()` methods, a new SQLite file will be created if it does not exist.
- parameter fileURL: the local file URL for the target SQLite persistent store. Note that if you have multiple configurations, you will need to specify a different `fileURL` explicitly for each of them.
- parameter configuration: an optional configuration name from the model file. If not specified, defaults to `nil`, the "Default" configuration. Note that if you have multiple configurations, you will need to specify a different `fileURL` explicitly for each of them.
- parameter mappingModelBundles: a list of `NSBundle`s from which to search mapping models for migration.
- parameter localStorageOptions: When the `SQLiteStore` is passed to the `DataStack`'s `addStorage()` methods, tells the `DataStack` how to setup the persistent store. Defaults to `.None`.
*/
public init(fileURL: NSURL, configuration: String? = nil, mappingModelBundles: [NSBundle] = NSBundle.allBundles(), localStorageOptions: LocalStorageOptions = nil) {
self.fileURL = fileURL
self.configuration = configuration
self.mappingModelBundles = mappingModelBundles
self.localStorageOptions = localStorageOptions
}
/**
Initializes an SQLite store interface from the given SQLite file name. When this instance is passed to the `DataStack`'s `addStorage()` methods, a new SQLite file will be created if it does not exist.
- Warning: The default SQLite file location for the `LegacySQLiteStore` and `SQLiteStore` are different. If the app was depending on CoreStore's default directories prior to 2.0.0, make sure to use `LegacySQLiteStore` instead of `SQLiteStore`.
- parameter fileName: the local filename for the SQLite persistent store in the "Application Support" directory (or the "Caches" directory on tvOS). Note that if you have multiple configurations, you will need to specify a different `fileName` explicitly for each of them.
- parameter configuration: an optional configuration name from the model file. If not specified, defaults to `nil`, the "Default" configuration. Note that if you have multiple configurations, you will need to specify a different `fileName` explicitly for each of them.
- parameter mappingModelBundles: a list of `NSBundle`s from which to search mapping models for migration.
- parameter localStorageOptions: When the `SQLiteStore` is passed to the `DataStack`'s `addStorage()` methods, tells the `DataStack` how to setup the persistent store. Defaults to `.None`.
*/
public init(fileName: String, configuration: String? = nil, mappingModelBundles: [NSBundle] = NSBundle.allBundles(), localStorageOptions: LocalStorageOptions = nil) {
self.fileURL = LegacySQLiteStore.defaultRootDirectory.URLByAppendingPathComponent(
fileName,
isDirectory: false
)
self.configuration = configuration
self.mappingModelBundles = mappingModelBundles
self.localStorageOptions = localStorageOptions
}
// MARK: DefaultInitializableStore
/**
Initializes an `LegacySQLiteStore` with an all-default settings: a `fileURL` pointing to a "<Application name>.sqlite" file in the "Application Support" directory (or the "Caches" directory on tvOS), a `nil` `configuration` pertaining to the "Default" configuration, a `mappingModelBundles` set to search all `NSBundle`s, and `localStorageOptions` set to `.AllowProgresiveMigration`.
- Warning: The default SQLite file location for the `LegacySQLiteStore` and `SQLiteStore` are different. If the app was depending on CoreStore's default directories prior to 2.0.0, make sure to use `LegacySQLiteStore` instead of `SQLiteStore`.
*/
public init() {
self.fileURL = LegacySQLiteStore.defaultFileURL
self.configuration = nil
self.mappingModelBundles = NSBundle.allBundles()
self.localStorageOptions = nil
}
// MARK: StorageInterface
/**
The string identifier for the `NSPersistentStore`'s `type` property. For `SQLiteStore`s, this is always set to `NSSQLiteStoreType`.
*/
public static let storeType = NSSQLiteStoreType
/**
The options dictionary for the specified `LocalStorageOptions`
*/
public func storeOptionsForOptions(options: LocalStorageOptions) -> [String: AnyObject]? {
if options == .None {
return self.storeOptions
}
var storeOptions = self.storeOptions ?? [:]
if options.contains(.AllowSynchronousLightweightMigration) {
storeOptions[NSMigratePersistentStoresAutomaticallyOption] = true
storeOptions[NSInferMappingModelAutomaticallyOption] = true
}
return storeOptions
}
/**
The configuration name in the model file
*/
public let configuration: String?
/**
The options dictionary for the `NSPersistentStore`. For `SQLiteStore`s, this is always set to
```
[NSSQLitePragmasOption: ["journal_mode": "WAL"]]
```
*/
public let storeOptions: [String: AnyObject]? = [NSSQLitePragmasOption: ["journal_mode": "WAL"]]
/**
Do not call directly. Used by the `DataStack` internally.
*/
public func didAddToDataStack(dataStack: DataStack) {
self.dataStack = dataStack
}
/**
Do not call directly. Used by the `DataStack` internally.
*/
public func didRemoveFromDataStack(dataStack: DataStack) {
self.dataStack = nil
}
// MAKR: LocalStorage
/**
The `NSURL` that points to the SQLite file
*/
public let fileURL: NSURL
/**
The `NSBundle`s from which to search mapping models for migrations
*/
public let mappingModelBundles: [NSBundle]
/**
Options that tell the `DataStack` how to setup the persistent store
*/
public var localStorageOptions: LocalStorageOptions
/**
Called by the `DataStack` to perform actual deletion of the store file from disk. Do not call directly! The `sourceModel` argument is a hint for the existing store's model version. For `SQLiteStore`, this converts the database's WAL journaling mode to DELETE before deleting the file.
*/
public func eraseStorageAndWait(soureModel soureModel: NSManagedObjectModel) throws {
// TODO: check if attached to persistent store
let fileURL = self.fileURL
try cs_autoreleasepool {
let journalUpdatingCoordinator = NSPersistentStoreCoordinator(managedObjectModel: soureModel)
let store = try journalUpdatingCoordinator.addPersistentStoreWithType(
self.dynamicType.storeType,
configuration: self.configuration,
URL: fileURL,
options: [NSSQLitePragmasOption: ["journal_mode": "DELETE"]]
)
try journalUpdatingCoordinator.removePersistentStore(store)
try NSFileManager.defaultManager().removeItemAtURL(fileURL)
}
}
// MARK: Internal
internal static let defaultRootDirectory: NSURL = {
#if os(tvOS)
let systemDirectorySearchPath = NSSearchPathDirectory.CachesDirectory
#else
let systemDirectorySearchPath = NSSearchPathDirectory.ApplicationSupportDirectory
#endif
return NSFileManager.defaultManager().URLsForDirectory(
systemDirectorySearchPath,
inDomains: .UserDomainMask
).first!
}()
internal static let defaultFileURL = LegacySQLiteStore.defaultRootDirectory
.URLByAppendingPathComponent(DataStack.applicationName, isDirectory: false)
.URLByAppendingPathExtension("sqlite")
// MARK: Private
private weak var dataStack: DataStack?
}
| mit | de4669db86d5607fb80631acc4838adc | 45.363208 | 388 | 0.698647 | 5.430387 | false | true | false | false |
codestergit/swift | test/SILGen/borrow.swift | 3 | 1196 | // RUN: %target-swift-frontend -parse-stdlib -emit-silgen %s | %FileCheck %s
import Swift
final class D {}
// Make sure that we insert the borrow for a ref_element_addr lvalue in the
// proper place.
final class C {
var d: D = D()
}
func useD(_ d: D) {}
// CHECK-LABEL: sil hidden @_T06borrow44lvalueBorrowShouldBeAtEndOfFormalAccessScope{{.*}} : $@convention(thin) () -> () {
// CHECK: bb0:
// CHECK: [[BOX:%.*]] = alloc_box ${ var C }, var, name "c"
// CHECK: [[PB_BOX:%.*]] = project_box [[BOX]]
// CHECK: [[FUNC:%.*]] = function_ref @_T06borrow4useD{{.*}} : $@convention(thin) (@owned D) -> ()
// CHECK: [[CLASS:%.*]] = load [copy] [[PB_BOX]]
// CHECK: [[BORROWED_CLASS:%.*]] = begin_borrow [[CLASS]]
// CHECK: [[OFFSET:%.*]] = ref_element_addr [[BORROWED_CLASS]]
// CHECK: [[LOADED_VALUE:%.*]] = load [copy] [[OFFSET]]
// CHECK: end_borrow [[BORROWED_CLASS]] from [[CLASS]]
// CHECK: apply [[FUNC]]([[LOADED_VALUE]])
// CHECK: destroy_value [[CLASS]]
// CHECK: destroy_value [[BOX]]
// CHECK: } // end sil function '_T06borrow44lvalueBorrowShouldBeAtEndOfFormalAccessScope{{.*}}'
func lvalueBorrowShouldBeAtEndOfFormalAccessScope() {
var c = C()
useD(c.d)
}
| apache-2.0 | 5b42a94764e15a0428f92297ab4be7e1 | 36.375 | 122 | 0.613712 | 3.215054 | false | false | false | false |
kokuyoku82/NumSwift | NumSwift/Source/Exponential.swift | 1 | 2770 | //
// Dear maintainer:
//
// When I wrote this code, only I and God
// know what it was.
// Now, only God knows!
//
// So if you are done trying to 'optimize'
// this routine (and failed),
// please increment the following counter
// as warning to the next guy:
//
// var TotalHoursWastedHere = 0
//
// Reference: http://stackoverflow.com/questions/184618/what-is-the-best-comment-in-source-code-you-have-ever-encountered
import Accelerate
/**
Compute e^(x). (Vectorized)
- Parameters:
- x: array of single precision floating numbers.
- Returns: An array of single precision floating number where its i-th element is e^(x[i]).
*/
public func exp(x:[Float]) -> [Float] {
var y = [Float](count: x.count, repeatedValue: 0.0)
var N = Int32(x.count)
vvexpf(&y, x, &N)
return y
}
/**
Compute e^(x). (Vectorized)
- Parameters:
- x: array of double precision floating numbers.
- Returns: An array of double precision floating number where its i-th element is e^(x[i]).
*/
public func exp(x: [Double]) -> [Double] {
var y = [Double](count: x.count, repeatedValue: 0.0)
var N = Int32(x.count)
vvexp(&y, x, &N)
return y
}
/**
Logrithm with Base
- Parameters:
- x: array of single precision floating numbers.
- base: the base of the logrithm (default: `e`).
- Returns: An array of single precision floating numbers. Its i-th element is the logrithm of x[i]
with base as given by `base`.
*/
public func log(x: [Float], base: Float? = nil) -> [Float] {
var y = [Float](count: x.count, repeatedValue: 0.0)
var N = Int32(x.count)
vvlogf(&y, x, &N)
if base != nil {
var base = base!
var scale:Float = 0.0
var one = Int32(1)
var tempArray = [Float](count: y.count, repeatedValue: 0.0)
vvlogf(&scale, &base, &one)
vDSP_vsdiv(&y, 1, &scale, &tempArray, 1, vDSP_Length(y.count))
y = tempArray
}
return y
}
/**
Logrithm with Base
- Parameters:
- x: array of double precision floating numbers.
- base: the base of the logrithm (default: `e`).
- Returns: An array of double precision floating numbers. Its i-th element is the logrithm of x[i]
with base as given by `base`.
*/
public func log(x: [Double], base: Double? = nil) -> [Double] {
var y = [Double](count: x.count, repeatedValue: 0.0)
var N = Int32(x.count)
vvlog(&y, x, &N)
if base != nil {
var base = base!
var scale: Double = 0.0
var one = Int32(1)
var tempArray = [Double](count: y.count, repeatedValue: 0.0)
vvlog(&scale, &base, &one)
vDSP_vsdivD(&y, 1, &scale, &tempArray, 1, vDSP_Length(y.count))
y = tempArray
}
return y
}
| mit | 4efd3f65fbcbf84ebd398244d3403990 | 23.513274 | 121 | 0.606859 | 3.278107 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.