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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
maxep/MXParallaxHeader | Example/UIScrollViewExample.swift | 1 | 2714 | // UIScrollViewExample.swift
//
// Copyright (c) 2019 Maxime Epain
//
// 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 MXParallaxHeader
class UIScrollViewExample: UITableViewController, MXParallaxHeaderDelegate {
@IBOutlet var headerView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Parallax Header
tableView.parallaxHeader.view = headerView // You can set the parallax header view from the floating view
tableView.parallaxHeader.height = 300
tableView.parallaxHeader.mode = .fill
tableView.parallaxHeader.delegate = self
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
tableView.parallaxHeader.minimumHeight = view.safeAreaInsets.top
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 50
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel!.text = String(format: "Height %ld", indexPath.row * 10)
return cell
}
// MARK: - Table view delegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.parallaxHeader.height = CGFloat(indexPath.row * 10)
}
// MARK: - Parallax header delegate
func parallaxHeaderDidScroll(_ parallaxHeader: MXParallaxHeader) {
NSLog("progress %f", parallaxHeader.progress)
}
}
| mit | 0b05903e3de4febd38beb12d34631a37 | 38.333333 | 113 | 0.715549 | 5.025926 | false | false | false | false |
KittenYang/A-GUIDE-TO-iOS-ANIMATION | Swift Version/KYGooeyMenu-Swift/KYGooeyMenu-Swift/SpringLayerAnimation/SpringLayerAnimation.swift | 1 | 2632 | //
// SpringLayerAnimation.swift
// KYGooeyMenu-Swift
//
// Created by Kitten Yang on 1/7/16.
// Copyright © 2016 Kitten Yang. All rights reserved.
//
import UIKit
class SpringLayerAnimation: NSObject {
static let sharedAnimation = SpringLayerAnimation()
private override init() {}
func createBasicAnimation(keypath: String, duration: Double, fromValue: AnyObject, toValue: AnyObject) -> CAKeyframeAnimation {
let animation = CAKeyframeAnimation(keyPath: keypath)
animation.values = basicAnimationValues(duration, fromValue: fromValue, toValue: toValue)
animation.duration = duration
animation.fillMode = kCAFillModeForwards
animation.removedOnCompletion = false
return animation
}
func createSpringAnima(keypath: String, duration: Double, usingSpringWithDamping: Double, initialSpringVelocity: Double, fromValue: AnyObject, toValue: AnyObject) -> CAKeyframeAnimation {
let dampingFactor = 10.0
let velocityFactor = 10.0
let animation = CAKeyframeAnimation(keyPath: keypath)
animation.values = springAnimationValues(duration, fromValue: fromValue, toValue: toValue, damping: usingSpringWithDamping * dampingFactor, velocity: initialSpringVelocity * velocityFactor)
animation.duration = duration
animation.fillMode = kCAFillModeForwards
animation.removedOnCompletion = false
return animation
}
}
extension SpringLayerAnimation {
private func basicAnimationValues(duration: Double, fromValue: AnyObject, toValue: AnyObject) -> [Double] {
let numberOfFrames = Int(duration * 60)
var values = [Double](count: numberOfFrames, repeatedValue: 0.0)
let diff = toValue.doubleValue - fromValue.doubleValue
for frame in 0..<numberOfFrames {
let x = Double(frame / numberOfFrames)
let value = fromValue.doubleValue + diff * x
values[frame] = value
}
return values
}
private func springAnimationValues(duration: Double, fromValue: AnyObject, toValue: AnyObject, damping: Double, velocity: Double) -> [Double] {
let numberOfFrames = Int(duration * 60)
var values = [Double](count: numberOfFrames, repeatedValue: 0.0)
let diff = toValue.doubleValue - fromValue.doubleValue
for frame in 0..<numberOfFrames {
let x = Double(frame / numberOfFrames)
let value = toValue.doubleValue - diff * (pow(M_E, -damping * x) * cos(velocity * x))
values[frame] = value
}
return values
}
}
| gpl-2.0 | e88ce488eb2262fd4cb2c628fd8e5923 | 39.476923 | 197 | 0.677689 | 5.128655 | false | false | false | false |
kimberlyz/Hint-Hint | Pods/CVCalendar/CVCalendar/CVCalendarTouchController.swift | 6 | 4649 | //
// CVCalendarTouchController.swift
// CVCalendar Demo
//
// Created by Eugene Mozharovsky on 17/03/15.
// Copyright (c) 2015 GameApp. All rights reserved.
//
import UIKit
public final class CVCalendarTouchController {
private unowned let calendarView: CalendarView
// MARK: - Properties
public var coordinator: Coordinator {
get {
return calendarView.coordinator
}
}
/// Init.
public init(calendarView: CalendarView) {
self.calendarView = calendarView
}
}
// MARK: - Events receive
extension CVCalendarTouchController {
public func receiveTouchLocation(location: CGPoint, inMonthView monthView: CVCalendarMonthView, withSelectionType selectionType: CVSelectionType) {
let weekViews = monthView.weekViews
if let dayView = ownerTouchLocation(location, onMonthView: monthView) where dayView.userInteractionEnabled {
receiveTouchOnDayView(dayView, withSelectionType: selectionType)
}
}
public func receiveTouchLocation(location: CGPoint, inWeekView weekView: CVCalendarWeekView, withSelectionType selectionType: CVSelectionType) {
let monthView = weekView.monthView
let index = weekView.index
let weekViews = monthView.weekViews
if let dayView = ownerTouchLocation(location, onWeekView: weekView) where dayView.userInteractionEnabled {
receiveTouchOnDayView(dayView, withSelectionType: selectionType)
}
}
public func receiveTouchOnDayView(dayView: CVCalendarDayView) {
coordinator.performDayViewSingleSelection(dayView)
}
}
// MARK: - Events management
private extension CVCalendarTouchController {
func receiveTouchOnDayView(dayView: CVCalendarDayView, withSelectionType selectionType: CVSelectionType) {
if let calendarView = dayView.weekView.monthView.calendarView {
switch selectionType {
case .Single:
coordinator.performDayViewSingleSelection(dayView)
calendarView.didSelectDayView(dayView)
case let .Range(.Started):
print("Received start of range selection.")
case let .Range(.Changed):
print("Received change of range selection.")
case let .Range(.Ended):
print("Received end of range selection.")
default: break
}
}
}
func monthViewLocation(location: CGPoint, doesBelongToDayView dayView: CVCalendarDayView) -> Bool {
var dayViewFrame = dayView.frame
let weekIndex = dayView.weekView.index
let appearance = dayView.calendarView.appearance
if weekIndex > 0 {
dayViewFrame.origin.y += dayViewFrame.height
dayViewFrame.origin.y *= CGFloat(dayView.weekView.index)
}
if dayView != dayView.weekView.dayViews!.first! {
dayViewFrame.origin.y += appearance.spaceBetweenWeekViews! * CGFloat(weekIndex)
}
if location.x >= dayViewFrame.origin.x && location.x <= CGRectGetMaxX(dayViewFrame) && location.y >= dayViewFrame.origin.y && location.y <= CGRectGetMaxY(dayViewFrame) {
return true
} else {
return false
}
}
func weekViewLocation(location: CGPoint, doesBelongToDayView dayView: CVCalendarDayView) -> Bool {
let dayViewFrame = dayView.frame
if location.x >= dayViewFrame.origin.x && location.x <= CGRectGetMaxX(dayViewFrame) && location.y >= dayViewFrame.origin.y && location.y <= CGRectGetMaxY(dayViewFrame) {
return true
} else {
return false
}
}
func ownerTouchLocation(location: CGPoint, onMonthView monthView: CVCalendarMonthView) -> DayView? {
var owner: DayView?
let weekViews = monthView.weekViews
for weekView in weekViews {
for dayView in weekView.dayViews! {
if self.monthViewLocation(location, doesBelongToDayView: dayView) {
owner = dayView
return owner
}
}
}
return owner
}
func ownerTouchLocation(location: CGPoint, onWeekView weekView: CVCalendarWeekView) -> DayView? {
var owner: DayView?
let dayViews = weekView.dayViews
for dayView in dayViews {
if weekViewLocation(location, doesBelongToDayView: dayView) {
owner = dayView
return owner
}
}
return owner
}
} | bsd-3-clause | 70b28d5f5cb8f4c88d030d3bcafacf47 | 33.701493 | 177 | 0.63347 | 5.704294 | false | false | false | false |
mkaply/firefox-ios | Shared/NSUserDefaultsPrefs.swift | 7 | 5101 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
open class NSUserDefaultsPrefs: Prefs {
fileprivate let prefixWithDot: String
fileprivate let userDefaults: UserDefaults
open func getBranchPrefix() -> String {
return self.prefixWithDot
}
public init(prefix: String, userDefaults: UserDefaults) {
self.prefixWithDot = prefix + (prefix.hasSuffix(".") ? "" : ".")
self.userDefaults = userDefaults
}
public init(prefix: String) {
self.prefixWithDot = prefix + (prefix.hasSuffix(".") ? "" : ".")
self.userDefaults = UserDefaults(suiteName: AppInfo.sharedContainerIdentifier)!
}
open func branch(_ branch: String) -> Prefs {
let prefix = self.prefixWithDot + branch + "."
return NSUserDefaultsPrefs(prefix: prefix, userDefaults: self.userDefaults)
}
// Preferences are qualified by the profile's local name.
// Connecting a profile to a Firefox Account, or changing to another, won't alter this.
fileprivate func qualifyKey(_ key: String) -> String {
return self.prefixWithDot + key
}
open func setInt(_ value: Int32, forKey defaultName: String) {
// Why aren't you using userDefaults.setInteger?
// Because userDefaults.getInteger returns a non-optional; it's impossible
// to tell whether there's a value set, and you thus can't distinguish
// between "not present" and zero.
// Yeah, NSUserDefaults is meant to be used for storing "defaults", not data.
setObject(NSNumber(value: value), forKey: defaultName)
}
open func setTimestamp(_ value: Timestamp, forKey defaultName: String) {
setLong(value, forKey: defaultName)
}
open func setLong(_ value: UInt64, forKey defaultName: String) {
setObject(NSNumber(value: value), forKey: defaultName)
}
open func setLong(_ value: Int64, forKey defaultName: String) {
setObject(NSNumber(value: value), forKey: defaultName)
}
open func setString(_ value: String, forKey defaultName: String) {
setObject(value as AnyObject?, forKey: defaultName)
}
open func setObject(_ value: Any?, forKey defaultName: String) {
userDefaults.set(value, forKey: qualifyKey(defaultName))
}
open func stringForKey(_ defaultName: String) -> String? {
// stringForKey converts numbers to strings, which is almost always a bug.
return userDefaults.object(forKey: qualifyKey(defaultName)) as? String
}
open func setBool(_ value: Bool, forKey defaultName: String) {
setObject(NSNumber(value: value as Bool), forKey: defaultName)
}
open func boolForKey(_ defaultName: String) -> Bool? {
// boolForKey just returns false if the key doesn't exist. We need to
// distinguish between false and non-existent keys, so use objectForKey
// and cast the result instead.
let number = userDefaults.object(forKey: qualifyKey(defaultName)) as? NSNumber
return number?.boolValue
}
fileprivate func nsNumberForKey(_ defaultName: String) -> NSNumber? {
return userDefaults.object(forKey: qualifyKey(defaultName)) as? NSNumber
}
open func unsignedLongForKey(_ defaultName: String) -> UInt64? {
return nsNumberForKey(defaultName)?.uint64Value
}
open func timestampForKey(_ defaultName: String) -> Timestamp? {
return unsignedLongForKey(defaultName)
}
open func longForKey(_ defaultName: String) -> Int64? {
return nsNumberForKey(defaultName)?.int64Value
}
open func objectForKey<T: Any>(_ defaultName: String) -> T? {
return userDefaults.object(forKey: qualifyKey(defaultName)) as? T
}
open func intForKey(_ defaultName: String) -> Int32? {
return nsNumberForKey(defaultName)?.int32Value
}
open func stringArrayForKey(_ defaultName: String) -> [String]? {
let objects = userDefaults.stringArray(forKey: qualifyKey(defaultName))
if let strings = objects {
return strings
}
return nil
}
open func arrayForKey(_ defaultName: String) -> [Any]? {
return userDefaults.array(forKey: qualifyKey(defaultName)) as [Any]?
}
open func dictionaryForKey(_ defaultName: String) -> [String: Any]? {
return userDefaults.dictionary(forKey: qualifyKey(defaultName)) as [String: Any]?
}
open func removeObjectForKey(_ defaultName: String) {
userDefaults.removeObject(forKey: qualifyKey(defaultName))
}
open func clearAll() {
// TODO: userDefaults.removePersistentDomainForName() has no effect for app group suites.
// iOS Bug? Iterate and remove each manually for now.
for key in userDefaults.dictionaryRepresentation().keys {
if key.hasPrefix(prefixWithDot) {
userDefaults.removeObject(forKey: key)
}
}
}
}
| mpl-2.0 | 14621fd4d6907cc839c708e9bb78a634 | 36.507353 | 97 | 0.666732 | 4.848859 | false | false | false | false |
t4thswm/Course | CourseModel/CourseModel/AssignmentModel.swift | 1 | 1571 | //
// AssignmentModel.swift
// CourseModel
//
// Created by Archie Yu on 2017/1/10.
// Copyright © 2017年 Archie Yu. All rights reserved.
//
import Foundation
public class Assignment: NSObject, NSCoding {
public var course: String
public var content: String
public var note: String
public var beginTime: Date
public var endTime: Date
public init(in course: String, todo content: String, note: String, from beginTime: Date, to endTime: Date) {
self.course = course
self.content = content
self.note = note
self.beginTime = beginTime
self.endTime = endTime
}
public func encode(with: NSCoder){
with.encode(course, forKey: "course")
with.encode(content, forKey: "content")
with.encode(note, forKey: "note")
with.encode(beginTime, forKey: "begin")
with.encode(endTime, forKey: "end")
}
required public init?(coder: NSCoder) {
course = coder.decodeObject(forKey: "course") as! String
content = coder.decodeObject(forKey: "content") as! String
note = coder.decodeObject(forKey: "note") as! String
beginTime = coder.decodeObject(forKey: "begin") as! Date
endTime = coder.decodeObject(forKey: "end") as! Date
}
}
public func assignmentDataFilePath() -> String {
let manager = FileManager()
let containerURL = manager.containerURL(forSecurityApplicationGroupIdentifier: "group.studio.sloth.Course")
return (containerURL?.appendingPathComponent("assignment.dat").path)!
}
| gpl-3.0 | 22a2e8711ab2455932f8a4508e90ec67 | 31 | 112 | 0.658801 | 4.284153 | false | false | false | false |
tivenlou/UI-Design-Swift | UI_Design_SWIFT/anchorInCorner.swift | 1 | 1842 | //
// ViewController.swift
// UI_Design_SWIFT
//
// Created by 陸泰文 on 2015/12/8.
// Copyright © 2015年 陸泰文. All rights reserved.
//
import UIKit
class anchorInCorner: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
title = "anchorCorner"
view.backgroundColor = UIColor.lightGrayColor()
}
let contenter = UIView()
let baseView = UIView()
let TopRight = UIView()
let BottomLeft = UIView()
let BottomRight = UIView()
func reload() {
contenter.frame = CGRectMake(0, 0, view.frame.width, view.frame.height-0)
contenter.backgroundColor = UIColor.whiteColor()
view.addSubview(contenter)
//TopLeft
baseView.backgroundColor = UIColor.orangeColor()
baseView.anchorInCorner(contenter, edgeType: anchorType.TopLeft, gap_x: 20, gap_y: 20, width: 100, height: 100)
//TopRight
TopRight.backgroundColor = UIColor.blueColor()
TopRight.anchorInCorner(contenter, edgeType: anchorType.TopRight, gap_x: 20, gap_y: 20, width: 100, height: 100)
//BottomLeft
BottomLeft.backgroundColor = UIColor.redColor()
BottomLeft.anchorInCorner(contenter, edgeType: anchorType.BottomLeft, gap_x: 20, gap_y: 20, width: 100, height: 100)
//BottomRight
BottomRight.backgroundColor = UIColor.greenColor()
BottomRight.anchorInCorner(contenter, edgeType: anchorType.BottomRight, gap_x: 20, gap_y: 20, width: 100, height: 100)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
reload()
}
}
| mit | 337cdff58368225d48dfc7995a6fd0e6 | 27.107692 | 126 | 0.615764 | 4.488943 | false | false | false | false |
netguru/ResponseDetective | ResponseDetective/Tests/Specs/HTMLBodyDeserializerSpec.swift | 1 | 770 | //
// HTMLBodyDeserializerSpec.swift
//
// Copyright © 2016-2020 Netguru S.A. All rights reserved.
// Licensed under the MIT License.
//
import Foundation
import Nimble
import ResponseDetective
import Quick
internal final class HTMLBodyDeserializerSpec: QuickSpec {
override func spec() {
describe("HTMLBodyDeserializer") {
let sut = HTMLBodyDeserializer()
it("should correctly deserialize HTML data") {
let source = "<!DOCTYPE html><html><head></head><body class=\"foo\"><p>lorem<br>ipsum</p></body></html>"
let data = source.data(using: .utf8)!
let expected = "<!DOCTYPE html>\n<html>\n<head></head>\n<body class=\"foo\"><p>lorem<br>ipsum</p></body>\n</html>"
expect { sut.deserialize(body: data) }.to(equal(expected))
}
}
}
}
| mit | ae7cd68052a07923f7da6295837aeaf0 | 23.03125 | 118 | 0.681404 | 3.543779 | false | false | false | false |
Urinx/Moi | Moi/AboutViewController.swift | 3 | 2570 | //
// AboutViewController.swift
// Waither
//
// Created by Eular on 15/7/25.
// Copyright © 2015年 Eular. All rights reserved.
//
import UIKit
import Social
class AboutViewController: UIViewController {
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.
}
*/
func share(forServiceType shareMethod: String){
let controller: SLComposeViewController = SLComposeViewController(forServiceType: shareMethod)
controller.setInitialText("我在使用 Moi 天気予報,不给人生留遗憾,不再错过每一天。http://urinx.github.io/app/moi/")
controller.addImage(UIImage(named: "shareImg"))
self.presentViewController(controller, animated: true, completion: nil)
}
func sendLinkContent(_scene: Int32, title: String){
let message = WXMediaMessage()
message.title = title
message.description = "不给人生留遗憾,不想错过每一天"
message.setThumbImage(UIImage(named:"shareImg"))
let ext = WXWebpageObject()
ext.webpageUrl = "http://pre.im/40fb"
message.mediaObject = ext
let req = SendMessageToWXReq()
req.bText = false
req.message = message
req.scene = _scene
WXApi.sendReq(req)
}
@IBAction func twitterTapped(sender: AnyObject) {
share(forServiceType: SLServiceTypeTwitter)
}
@IBAction func sinaTapped(sender: AnyObject) {
share(forServiceType: SLServiceTypeSinaWeibo)
}
@IBAction func wechatTapped(sender: AnyObject) {
sendLinkContent(WXSceneSession.rawValue, title: "我在使用 Moi - 天気予報")
}
@IBAction func wechatCircleTapped(sender: AnyObject) {
sendLinkContent(WXSceneTimeline.rawValue, title: "不给人生留遗憾,不想错过每一天")
}
@IBAction func close(segue:UIStoryboardSegue) {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
| apache-2.0 | e5eb9c7d27564967f75add4c3481a57e | 30.701299 | 106 | 0.667759 | 4.382406 | false | false | false | false |
RMizin/PigeonMessenger-project | FalconMessenger/ChatsControllers/ReportSender.swift | 1 | 1870 | //
// ReportSender.swift
// FalconMessenger
//
// Created by Roman Mizin on 9/10/18.
// Copyright © 2018 Roman Mizin. All rights reserved.
//
import UIKit
import Firebase
import ARSLineProgress
class ReportSender: NSObject {
func sendReport(_ description: String?, _ controller: UIViewController?, _ message: Message?, _ indexPath: IndexPath? = nil, _ cell: BaseMessageCell? = nil) {
guard let controller = controller else { return }
ARSLineProgress.show()
var reportsDatabaseReference: DatabaseReference!
reportsDatabaseReference = Database.database(url: globalVariables.reportDatabaseURL).reference().child("reports").childByAutoId()
let reportedMessageID = message?.messageUID ?? "empty"
let reportedUserID = message?.fromId ?? "empty"
let victimUserID = Auth.auth().currentUser?.uid ?? "empty"
let reportDescription = description ?? "empty"
let childValues: [String: String] = ["reportedMessageID": reportedMessageID,
"reportedUserID": reportedUserID,
"victimUserID": victimUserID,
"description": reportDescription]
reportsDatabaseReference.updateChildValues(childValues) { (error, _) in
guard error == nil else {
ARSLineProgress.hide()
basicErrorAlertWith(title: "Error", message: error?.localizedDescription ?? "Try again later", controller: controller)
return
}
ARSLineProgress.hide()
basicErrorAlertWith(title: "Your report has bees sent",
message: "We will review your report and react as soon as possible",
controller: controller)
guard let indexPath = indexPath , let cell = cell else { return }
cell.handleDeletion(indexPath: indexPath)
}
}
}
| gpl-3.0 | f68f22b25b646a7e57b79eaeb86930c4 | 39.630435 | 160 | 0.64366 | 5.065041 | false | false | false | false |
watson-developer-cloud/ios-sdk | Sources/DiscoveryV2/Models/DefaultQueryParamsTableResults.swift | 1 | 1972 | /**
* (C) Copyright IBM Corp. 2020.
*
* 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
/**
Default project query settings for table results.
*/
public struct DefaultQueryParamsTableResults: Codable, Equatable {
/**
When `true`, a table results for the query are returned by default.
*/
public var enabled: Bool?
/**
The number of table results to return by default.
*/
public var count: Int?
/**
The number of table results to include in each result document.
*/
public var perDocument: Int?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case enabled = "enabled"
case count = "count"
case perDocument = "per_document"
}
/**
Initialize a `DefaultQueryParamsTableResults` with member variables.
- parameter enabled: When `true`, a table results for the query are returned by default.
- parameter count: The number of table results to return by default.
- parameter perDocument: The number of table results to include in each result document.
- returns: An initialized `DefaultQueryParamsTableResults`.
*/
public init(
enabled: Bool? = nil,
count: Int? = nil,
perDocument: Int? = nil
)
{
self.enabled = enabled
self.count = count
self.perDocument = perDocument
}
}
| apache-2.0 | 75b166b8e73160c1a1aca63c832329b9 | 28.878788 | 94 | 0.672414 | 4.522936 | false | false | false | false |
EckoEdc/simpleDeadlines-iOS | Simple Deadlines/CircleCounterView.swift | 1 | 1783 | //
// CircleCounterView.swift
// Simple Deadlines
//
// Created by Edric MILARET on 17-01-24.
// Copyright © 2017 Edric MILARET. All rights reserved.
//
import UIKit
@IBDesignable
public class CircleCounterView: UIView {
let circleLayer = CAShapeLayer()
let dayLabel = UILabel()
@IBInspectable public var dayRemaining: Int = 0 {
didSet {
dayLabel.text = String(dayRemaining)
}
}
@IBInspectable public var color: UIColor = .red {
didSet {
circleLayer.fillColor = color.cgColor
}
}
public override init(frame: CGRect) {
super.init(frame: frame)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.isOpaque = false
self.backgroundColor = .clear
}
public override func draw(_ frame: CGRect) {
drawCircle()
}
func drawCircle() {
let width = Double(self.bounds.size.width);
let height = Double(self.bounds.size.height);
dayLabel.bounds = self.bounds
dayLabel.textAlignment = NSTextAlignment.center
dayLabel.center = CGPoint(x: width/2, y: height/2)
dayLabel.textColor = UIColor.white
self.addSubview(dayLabel)
circleLayer.bounds = CGRect(x: 2.0, y: 2.0, width: width-2.0, height: height-2.0)
circleLayer.position = CGPoint(x: width/2, y: height/2);
let rect = CGRect(x: 2.0, y: 2.0, width: width-2.0, height: height-2.0)
let path = UIBezierPath.init(ovalIn: rect)
circleLayer.path = path.cgPath
circleLayer.fillColor = color.cgColor
circleLayer.lineWidth = 2.0
self.layer.insertSublayer(circleLayer, at: 0)
}
}
| gpl-3.0 | 7b0cc2f9b23a11a2510cfb085d2b28ce | 26.84375 | 89 | 0.603255 | 4.096552 | false | false | false | false |
okkhoury/SafeNights_iOS | Pods/Siesta/Source/Siesta/Support/WeakCache.swift | 1 | 3305 | //
// WeakCache.swift
// Siesta
//
// Created by Paul on 2015/6/26.
// Copyright © 2016 Bust Out Solutions. All rights reserved.
//
import Foundation
#if os(OSX) || os(watchOS)
internal let MemoryWarningNotification = NSNotification.Name("Siesta.MemoryWarningNotification")
#elseif os(iOS) || os(tvOS)
import UIKit
internal let MemoryWarningNotification = NSNotification.Name.UIApplicationDidReceiveMemoryWarning
#endif
/**
A cache for maintaining a unique instance for a given key as long as any other objects
retain references to it.
*/
internal final class WeakCache<K: Hashable, V: AnyObject>
{
private var entriesByKey = [K : WeakCacheEntry<V>]()
private var lowMemoryObserver: AnyObject? = nil
internal var countLimit = 2048
{
didSet { checkLimit() }
}
init()
{
lowMemoryObserver =
NotificationCenter.default.addObserver(
forName: MemoryWarningNotification,
object: nil,
queue: nil)
{
[weak self] _ in
self?.flushUnused()
}
}
deinit
{
if let lowMemoryObserver = lowMemoryObserver
{ NotificationCenter.default.removeObserver(lowMemoryObserver) }
}
func get(_ key: K, onMiss: () -> V) -> V
{
return entriesByKey[key]?.value ??
{
checkLimit()
let value = onMiss()
entriesByKey[key] = WeakCacheEntry(value)
return value
}()
}
private func checkLimit()
{
if entriesByKey.count >= countLimit
{ flushUnused() }
}
func flushUnused()
{
for (key, entry) in entriesByKey
{
entry.allowRemoval()
if entry.value == nil
{
// TODO: prevent double lookup if something like this proposal ever gets implemented:
// https://gist.github.com/natecook1000/473720ba072fa5a0cd5e6c913de75fe1
entriesByKey.removeValue(forKey: key)
}
}
}
var entries: AnySequence<(K, V)>
{
return AnySequence(
entriesByKey.flatMap
{
(key, entry) -> (K, V)? in
if let value = entry.value
{ return (key, value) }
else
{ return nil }
}
)
}
var keys: AnySequence<K>
{
return AnySequence(entries.map { $0.0 })
}
var values: AnySequence<V>
{
return AnySequence(entries.map { $0.1 })
}
}
private final class WeakCacheEntry<V: AnyObject>
{
private var ref: StrongOrWeakRef<V>
init(_ value: V)
{
ref = StrongOrWeakRef(value)
}
var value: V?
{
ref.strong = true // Any access promotes to strong ref until next memory event
return ref.value
}
func allowRemoval()
{
ref.strong = false
if let value = ref.value as? WeakCacheValue
{ value.allowRemovalFromCache() }
}
}
internal protocol WeakCacheValue
{
func allowRemovalFromCache()
}
| mit | 53891e84cbfeccab229d1bc44490e330 | 23.842105 | 101 | 0.53632 | 4.713267 | false | false | false | false |
Mars182838/WJCycleScrollView | WJCycleScrollView/Extentions/StringExtensions.swift | 1 | 6726 | //
// StringExtensions.swift
// EZSwiftExtensions
//
// Created by Goktug Yilmaz on 15/07/15.
// Copyright (c) 2015 Goktug Yilmaz. All rights reserved.
//
import UIKit
extension String {
/// EZSE: Cut string from integerIndex to the end
public subscript(integerIndex: Int) -> Character {
let index = startIndex.advancedBy(integerIndex)
return self[index]
}
/// EZSE: Cut string from range
public subscript(integerRange: Range<Int>) -> String {
let start = startIndex.advancedBy(integerRange.startIndex)
let end = startIndex.advancedBy(integerRange.endIndex)
let range = start..<end
return self[range]
}
/// EZSE: Character count
public var length: Int {
return self.characters.count
}
/// EZSE: Counts number of instances of the input inside String
public func count(substring: String) -> Int {
return componentsSeparatedByString(substring).count - 1
}
/// EZSE: Capitalizes first character of String
public var capitalizeFirst: String {
var result = self
result.replaceRange(startIndex...startIndex, with: String(self[startIndex]).capitalizedString)
return result
}
/// EZSE: Counts whitespace & new lines
public func isOnlyEmptySpacesAndNewLineCharacters() -> Bool {
let characterSet = NSCharacterSet.whitespaceAndNewlineCharacterSet()
let newText = self.stringByTrimmingCharactersInSet(characterSet)
return newText.isEmpty
}
/// EZSE: Trims white space and new line characters
public mutating func trim() {
self = self.trimmed()
}
/// EZSE: Trims white space and new line characters, returns a new string
public func trimmed() -> String {
return self.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).joinWithSeparator("")
}
/// EZSE: Checks if String contains Email
public var isEmail: Bool {
let dataDetector = try? NSDataDetector(types: NSTextCheckingType.Link.rawValue)
let firstMatch = dataDetector?.firstMatchInString(self, options: NSMatchingOptions.ReportCompletion, range: NSRange(location: 0, length: length))
return (firstMatch?.range.location != NSNotFound && firstMatch?.URL?.scheme == "mailto")
}
/// EZSE: Returns if String is a number
public func isNumber() -> Bool {
if let _ = NSNumberFormatter().numberFromString(self) {
return true
}
return false
}
/// EZSE: Extracts URLS from String
public var extractURLs: [NSURL] {
var urls: [NSURL] = []
let detector: NSDataDetector?
do {
detector = try NSDataDetector(types: NSTextCheckingType.Link.rawValue)
} catch _ as NSError {
detector = nil
}
let text = self
if let detector = detector {
detector.enumerateMatchesInString(text, options: [], range: NSRange(location: 0, length: text.characters.count), usingBlock: {
(result: NSTextCheckingResult?, flags: NSMatchingFlags, stop: UnsafeMutablePointer<ObjCBool>) -> Void in
if let result = result,
let url = result.URL {
urls.append(url)
}
})
}
return urls
}
/// EZSE: Checking if String contains input
public func contains(find: String) -> Bool {
return self.rangeOfString(find) != nil
}
/// EZSE: Checking if String contains input with comparing options
public func contains(find: String, compareOption: NSStringCompareOptions) -> Bool {
return self.rangeOfString(find, options: compareOption) != nil
}
/// EZSE: Converts String to Int
public func toInt() -> Int? {
if let num = NSNumberFormatter().numberFromString(self) {
return num.integerValue
} else {
return nil
}
}
/// EZSE: Converts String to Double
public func toDouble() -> Double? {
if let num = NSNumberFormatter().numberFromString(self) {
return num.doubleValue
} else {
return nil
}
}
/// EZSE: Converts String to Float
public func toFloat() -> Float? {
if let num = NSNumberFormatter().numberFromString(self) {
return num.floatValue
} else {
return nil
}
}
/// EZSE: Converts String to Bool
public func toBool() -> Bool? {
let trimmed = self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).lowercaseString
if trimmed == "true" || trimmed == "false" {
return (trimmed as NSString).boolValue
}
return nil
}
///EZSE: Returns the first index of the occurency of the character in String
public func getIndexOf(char: Character) -> Int? {
for (index, c) in characters.enumerate() {
if c == char {
return index
}
}
return nil
}
/// EZSE: Converts String to NSString
public var toNSString: NSString { get { return self as NSString } }
#if os(iOS)
///EZSE: Returns bold NSAttributedString
public func bold() -> NSAttributedString {
let boldString = NSMutableAttributedString(string: self, attributes: [NSFontAttributeName: UIFont.boldSystemFontOfSize(UIFont.systemFontSize())])
return boldString
}
#endif
///EZSE: Returns underlined NSAttributedString
public func underline() -> NSAttributedString {
let underlineString = NSAttributedString(string: self, attributes: [NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue])
return underlineString
}
#if os(iOS)
///EZSE: Returns italic NSAttributedString
public func italic() -> NSAttributedString {
let italicString = NSMutableAttributedString(string: self, attributes: [NSFontAttributeName: UIFont.italicSystemFontOfSize(UIFont.systemFontSize())])
return italicString
}
#endif
///EZSE: Returns NSAttributedString
public func color(color: UIColor) -> NSAttributedString {
let colorString = NSMutableAttributedString(string: self, attributes: [NSForegroundColorAttributeName: color])
return colorString
}
/// EZSE: Checks if String contains Emoji
public func includesEmoji() -> Bool {
for i in 0...length {
let c: unichar = (self as NSString).characterAtIndex(i)
if (0xD800 <= c && c <= 0xDBFF) || (0xDC00 <= c && c <= 0xDFFF) {
return true
}
}
return false
}
}
| mit | 38b03642a923c8216c35317d99d5e023 | 32.63 | 157 | 0.632174 | 5.24649 | false | false | false | false |
pocketsvg/PocketSVG | Demos/Demo-iOS/Demo-iOS/RectangleViewController.swift | 2 | 1047 | /*
* This file is part of the PocketSVG package.
* Copyright (c) Ponderwell, Ariel Elkin, Fjölnir Ásgeirsson, and Contributors
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
import UIKit
import PocketSVG
class RectangleViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
let svgURL = Bundle.main.url(forResource: "rectangle", withExtension: "svg")!
let svgImageView = SVGImageView.init(contentsOf: svgURL)
// The original SVG's stroke color is yellow, but we'll make it red:
svgImageView.strokeColor = .red
//The original SVG's fill is transparent but we'll make it blue:
svgImageView.fillColor = .blue
svgImageView.frame = view.bounds
svgImageView.contentMode = .scaleAspectFit
svgImageView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(svgImageView)
}
}
| mit | 6dc49d333f83a01d0a366348e1a8e338 | 28.857143 | 85 | 0.698565 | 4.623894 | false | false | false | false |
banxi1988/Staff | Staff/ClockRecordEditorViewController.swift | 1 | 4661 | //
// ClockRecordEditorViewController.swift
// Staff
//
// Created by Haizhen Lee on 16/3/1.
// Copyright © 2016年 banxi1988. All rights reserved.
//
import Foundation
// Build for target uicontroller
import UIKit
import SwiftyJSON
import BXModel
import BXiOSUtils
import BXForm
//-ClockRecordEditorViewController(m=ClockRecord,sadapter):tvc
class ClockRecordEditorViewController : UITableViewController {
init(){
super.init(style:.Plain)
}
override init(style: UITableViewStyle){
super.init(style:style)
}
// must needed for iOS 8
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
var allOutlets :[UIView]{
return []
}
func commonInit(){
for childView in allOutlets{
self.view.addSubview(childView)
childView.translatesAutoresizingMaskIntoConstraints = false
}
installConstaints()
setupAttrs()
}
func installConstaints(){
}
func setupAttrs(){
}
override func loadView(){
super.loadView()
self.view.backgroundColor = AppColors.colorBackground
commonInit()
}
var typeCell: RightDetailCell = {
let cell = RightDetailCell()
cell.textLabel?.text = "打卡类型"
cell.staticHeight = 50
return cell
}()
var timeCell: RightDetailCell = {
let cell = RightDetailCell()
cell.textLabel?.text = "打卡时间"
cell.detailTextLabel?.text = "请选择打卡时间"
cell.staticHeight = 50
return cell
}()
var clockRecord:ClockRecord = ClockRecord(type: .On)
let staticAdapter = StaticTableViewAdapter()
override func viewDidLoad() {
super.viewDidLoad()
title = clockRecord.id > 0 ? "修改打卡记录" : "新增打卡记录"
navigationItem.title = title
if clockRecord.id > 0 {
time = clockRecord.clock_time
timeCell.detailTextLabel?.text = clockRecord.clock_time.bx_dateTimeString
}
staticAdapter.appendContentsOf([typeCell,timeCell])
staticAdapter.bindTo(tableView)
clearsSelectionOnViewWillAppear = true
tableView.keyboardDismissMode = .OnDrag
tableView.tableFooterView = UIView()
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 120
tableView.separatorStyle = .None
tableView.separatorColor = AppColors.seperatorLineColor
staticAdapter.didSelectCell = { cell,index in
self.didTapCell(cell)
}
let doneButton = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: "trySave:")
navigationItem.rightBarButtonItem = doneButton
autobind()
}
func autobind(){
bind(clockRecord)
}
func bind(record:ClockRecord){
type = record.recordType
typeCell.detailTextLabel?.text = record.recordType.title
}
func didTapCell(cell:UITableViewCell){
switch cell{
case typeCell:
chooseType()
case timeCell:
chooseTime()
default:break
}
}
var type:ClockRecordType?
var time:NSDate?
func trySave(sender:AnyObject){
guard let type = self.type else{
return
}
guard let date = self.time else{
return
}
clockRecord.updateClockTime(date)
clockRecord.updateType(type)
if clockRecord.id > 0 {
ClockRecordService.sharedService.update(clockRecord)
}else{
ClockRecordService.sharedService.add(clockRecord)
}
if calendar.isDateInToday(date){
NSNotificationCenter.defaultCenter().postNotificationName(AppEvents.Clocked, object: nil)
}
NSNotificationCenter.defaultCenter().postNotificationName(AppEvents.ClockDataSetChanged, object: nil)
bx_closeSelf()
}
func chooseType(){
let picker = SelectPickerController(options: ClockRecordType.allCases)
picker.onSelectOption = { option in
self.type = option
self.typeCell.detailTextLabel?.text = option.title
}
presentViewController(picker, animated: true, completion: nil)
}
func chooseTime(){
let pickerController = DatePickerController()
let picker = pickerController.datePicker
pickerController.date = NSDate()
picker.minimumDate = NSDate(timeIntervalSinceNow: -3600 * 24 * 60)
picker.maximumDate = NSDate()
picker.datePickerMode = .DateAndTime
pickerController.pickDoneHandler = { date in
self.time = date
self.timeCell.detailTextLabel?.text = date.bx_dateTimeString
}
presentViewController(pickerController, animated: true, completion: nil)
}
}
| mit | bb92c2977fe6768cc6b4508ff87c3a99 | 23.620321 | 105 | 0.693962 | 4.678862 | false | false | false | false |
RocketChat/Rocket.Chat.iOS | Rocket.Chat/API/Requests/Room/RoomRolesRequest.swift | 1 | 1471 | //
// RoomRolesRequest.swift
// Rocket.Chat
//
// Created by Rafael Kellermann Streit on 11/05/18.
// Copyright © 2018 Rocket.Chat. All rights reserved.
//
import SwiftyJSON
import RealmSwift
fileprivate extension SubscriptionType {
var path: String {
switch self {
case .channel:
return "/api/v1/channels.roles"
case .group:
return "/api/v1/groups.roles"
case .directMessage:
return ""
}
}
}
final class RoomRolesRequest: APIRequest {
typealias APIResourceType = RoomRolesResource
let requiredVersion = Version(0, 64, 2)
var path: String {
return type.path
}
var query: String?
let roomName: String?
let type: SubscriptionType
init(roomName: String, subscriptionType: SubscriptionType) {
self.type = subscriptionType
self.roomName = roomName
self.query = "roomName=\(roomName)"
}
}
final class RoomRolesResource: APIResource {
var roomRoles: [RoomRoles]? {
guard let realm = Realm.current else { return nil }
return raw?["roles"].arrayValue.map {
let object = RoomRoles()
object.user = User.getOrCreate(realm: realm, values: $0["u"], updates: nil)
object.roles.append(objectsIn: $0["roles"].arrayValue.compactMap({ $0.string }))
return object
}
}
var success: Bool {
return raw?["success"].bool ?? false
}
}
| mit | c55d84555a42d89242f7507288130ff6 | 23.915254 | 92 | 0.612925 | 4.285714 | false | false | false | false |
jwamin/Xnpm | Xnpm/ConsoleViewController.swift | 1 | 3429 | //
// ConsoleViewController.swift
// Xnpm
//
// Created by Joss Manger on 6/29/17.
// Copyright © 2017 Joss Manger. All rights reserved.
//
import Cocoa
class ConsoleViewController: NSViewController,NSWindowDelegate {
@IBOutlet weak var touchBarButton: NSButton!
@IBOutlet var textView: NSTextView!
var parentController:ViewController?
@IBOutlet weak var indicator: NSProgressIndicator!
override func viewDidLoad() {
NotificationCenter.default.addObserver(self, selector: #selector(handleText), name: NSNotification.Name(rawValue: "gotOut"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(handleEnd), name: NSNotification.Name(rawValue: "gotEnd"), object: nil)
// if #available(OSX 10.12.2, *) {
// touchBarButton.image = NSImage(named: NSImageNameTouchBarRecordStopTemplate)
// indicator.startAnimation(self)
// }
}
override func viewDidAppear() {
self.view.window?.delegate = self;
if #available(OSX 10.12.2, *) {
self.view.window?.unbind(#keyPath(touchBar)) // unbind first
self.view.window?.bind(#keyPath(touchBar), to: self, withKeyPath: #keyPath(touchBar), options: nil)
}
}
override func awakeFromNib() {
//print("hello world")
textView.font = NSFont(name: "Andale Mono", size: 11.0)
}
func handleText(notification:NSNotification){
//print(notification.object ?? "none")
let dict = notification.object as! NSDictionary
let str = dict.object(forKey: "str") as! String
let notificationID = dict.object(forKey: "sender") as! String
if let identifier = parentController?.package.packageTitle{
if(identifier==notificationID){
updateTextView(str: str)
}
}
}
func handleEnd(notification:NSNotification){
//print(notification.object ?? "none")
updateTextView(str: notification.object as! String)
}
func updateTextView(str:String){
// Smart Scrolling
let scroll = (NSMaxY(textView.visibleRect) == NSMaxY(textView.bounds));
// Append string to textview
textView.textStorage?.append(NSAttributedString(string: str))
//Set Font
textView.textStorage?.font = NSFont(name: "Andale Mono", size: 11.0)
if (scroll){
textView.scrollRangeToVisible(NSMakeRange((textView.string?.count)!, 0));
}// Scroll to end of the textview contents
}
func windowShouldClose(_ sender: Any) -> Bool {
self.parentController?.executeScript(sender: self)
return false;
}
func removeObservers(){
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "gotOut"), object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "gotEnd"), object: nil)
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
override func viewDidDisappear() {
removeObservers()
}
deinit {
if #available(OSX 10.12.2, *) {
self.view.window?.unbind(#keyPath(touchBar))
}
}
}
| mit | 4f069dd95e2d7af5a854039635899dce | 29.882883 | 145 | 0.612894 | 4.715268 | false | false | false | false |
Michael-Lfx/SwiftArmyKnife | Controls/SAKPlaceholderTextView.swift | 1 | 3663 | // 参考 https://github.com/chaoyuan899/KCTextView
// 已简单测试
import UIKit
@IBDesignable class SAKPlaceholderTextView: UITextView {
private struct AssociatedKeys {
static var InitializeName = "sak_InitializeName"
}
/**
The string that is displayed when there is no other text in the text view.
*/
@IBInspectable var placeholder: String = "在此输入内容" {
didSet {
setNeedsDisplay()
}
}
/**
The color of the placeholder.
*/
@IBInspectable var placeholderTextColor: UIColor! = UIColor(white: 0.702, alpha: 1)
// MARK: - Accessors
override var text: String! {
didSet {
setNeedsDisplay()
}
}
override func insertText(text: String) {
super.insertText(text)
setNeedsDisplay()
}
override var attributedText: NSAttributedString! {
didSet {
setNeedsDisplay()
}
}
override var contentInset: UIEdgeInsets {
didSet {
setNeedsDisplay()
}
}
override var font: UIFont! {
didSet {
setNeedsDisplay()
}
}
override var textAlignment: NSTextAlignment {
didSet{
setNeedsDisplay()
}
}
// MARK: - NSObject
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self, name: UITextViewTextDidChangeNotification, object: self)
}
// MARK: - UIView
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
initialize()
}
override func drawRect(var rect: CGRect) {
super.drawRect(rect)
if count(text) == 0 && placeholder != "" {
// Inset the rect
rect = UIEdgeInsetsInsetRect(rect, contentInset)
// HAX: This is hacky. Not sure why 8 is the magic number
if contentInset.left == 0.0 {
rect.origin.x += 8.0
}
rect.origin.y += 8.0
// Draw the text
// HAX: The following lines are inspired by http://stackoverflow.com/questions/18948180/align-text-using-drawinrectwithattributes thanks @Hejazi.
// Make a copy of the default paragraph style
var paragraphStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle
// Set line break mode
paragraphStyle.lineBreakMode = .ByTruncatingTail
// Set text alignment
paragraphStyle.alignment = .Left
let attributes = [NSFontAttributeName: font, NSParagraphStyleAttributeName: paragraphStyle, NSForegroundColorAttributeName: placeholderTextColor]
placeholder.drawInRect(rect, withAttributes: attributes)
}
}
// MARK: - Private
private func initialize() {
let obj = objc_getAssociatedObject(self, &AssociatedKeys.InitializeName) as? NSString
if obj == nil {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "textChanged:", name: UITextViewTextDidChangeNotification, object: self)
layer.drawsAsynchronously = true
objc_setAssociatedObject(self, &AssociatedKeys.InitializeName, "SAKPlaceholderTextView", UInt(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
}
}
func textChanged(notification: NSNotification) {
setNeedsDisplay()
}
}
| mit | 5f26b1c98e5a63913af4db30404edf4e | 29.308333 | 158 | 0.60187 | 5.40416 | false | false | false | false |
pnhechim/Fiestapp-iOS | Fiestapp/Fiestapp/Common/Enums/EnumFuncionalidades.swift | 1 | 395 | //
// EnumFuncionalidades.swift
// fiestapp
//
// Created by Nicolás Hechim on 19/5/17.
// Copyright © 2017 Mint. All rights reserved.
//
import UIKit
enum EnumFuncionalidades: String {
case Galeria = "Fotos",
MeGustas = "¡Me gustás!",
Menu = "Menú",
Regalos = "Lista de Regalos",
Asistencia = "Asistencia",
Vestimenta = "Vestimenta",
Musica = "Música"
}
| mit | 7bafc19e998d1f744c8afa778062cc01 | 19.473684 | 47 | 0.637532 | 2.778571 | false | false | false | false |
invalidstream/radioonthetv | RadioOnTheTV/RadioOnTheTV/WebRadioPlayer.swift | 1 | 8939 | //
// WebRadioPlayer.swift
// RadioOnTheTV
//
// Created by Chris Adamson on 3/6/16.
// Copyright © 2016 Subsequently & Furthermore, Inc. All rights reserved.
//
import Foundation
import AudioToolbox
enum PlayerState {
case Initialized
case Starting
case Playing
case Paused
case Error // todo: maybe an associated value with OSStatus?
}
extension PlayerState : CustomStringConvertible {
var description : String {
switch self {
case .Initialized: return "Initialized"
case .Starting: return "Starting"
case .Playing: return "Playing"
case .Paused: return "Paused"
case .Error: return "Error"
}
}
}
// this two-delegate stuff is really bad; maybe KVO on the state property would be better here
protocol PlayerInfoDelegate : class {
func stateChangedForPlayerInfo(playerInfo: PlayerInfo)
}
class PlayerInfo {
var dataFormat : AudioStreamBasicDescription?
var audioQueue : AudioQueueRef?
var totalPacketsReceived : UInt32 = 0
var queueStarted : Bool = false
weak var delegate : PlayerInfoDelegate?
var state : PlayerState = .Initialized {
didSet {
if state != oldValue {
delegate?.stateChangedForPlayerInfo(self)
}
}
}
}
/*
mime types in the wild:
MP3: audio/mpeg
AAC: application/octet-stream
*/
protocol WebRadioPlayerDelegate {
func webRadioPlayerStateChanged(player : WebRadioPlayer)
}
class WebRadioPlayer : NSObject, NSURLSessionDataDelegate, PlayerInfoDelegate {
private (set) var error : NSError?
// TODO: figure out something nice with OSStatus
// (to replace CheckError)
private let stationURL : NSURL
private var dataTask : NSURLSessionDataTask?
// must be var of a class to do C-style pointer stuff
var playerInfo : PlayerInfo
var fileStream : AudioFileStreamID = AudioFileStreamID()
var delegate : WebRadioPlayerDelegate?
var parseIsDiscontinuous = true
init(stationURL : NSURL) {
self.stationURL = stationURL
playerInfo = PlayerInfo()
super.init()
playerInfo.delegate = self
playerInfo.state = .Initialized
}
func start() {
playerInfo.state = .Starting
let urlSession = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: self, delegateQueue: nil)
let dataTask = urlSession.dataTaskWithURL(stationURL)
self.dataTask = dataTask
dataTask.resume()
}
func pause() {
dataTask?.suspend()
playerInfo.state = .Paused
if let audioQueue = playerInfo.audioQueue {
var err = noErr
err = AudioQueueStop(audioQueue, true)
}
parseIsDiscontinuous = true
}
func resume() {
playerInfo.totalPacketsReceived = 0
dataTask?.resume()
}
func stateChangedForPlayerInfo(playerInfo:PlayerInfo) {
delegate?.webRadioPlayerStateChanged(self)
}
// MARK: - NSURLSessionDataDelegate
func URLSession(session: NSURLSession,
dataTask: NSURLSessionDataTask,
didReceiveResponse response: NSURLResponse,
completionHandler: (NSURLSessionResponseDisposition) -> Void) {
NSLog ("dataTask didReceiveResponse: \(response), MIME type \(response.MIMEType)")
guard let httpResponse = response as? NSHTTPURLResponse
where httpResponse.statusCode == 200 else {
NSLog ("failed with response \(response)")
completionHandler(.Cancel)
return
}
let streamTypeHint : AudioFileTypeID
if let mimeType = response.MIMEType {
streamTypeHint = streamTypeHintForMIMEType(mimeType)
} else {
streamTypeHint = 0
}
var err = noErr
err = AudioFileStreamOpen(&playerInfo,
streamPropertyListenerProc,
streamPacketsProc,
streamTypeHint,
&fileStream)
NSLog ("created file stream, err = \(err)")
completionHandler(.Allow)
}
func URLSession(session: NSURLSession,
dataTask: NSURLSessionDataTask,
didReceiveData data: NSData) {
NSLog ("dataTask didReceiveData, \(data.length) bytes")
var err = noErr
let parseFlags : AudioFileStreamParseFlags
if parseIsDiscontinuous {
parseFlags = .Discontinuity
parseIsDiscontinuous = false
} else {
parseFlags = AudioFileStreamParseFlags()
}
err = AudioFileStreamParseBytes(fileStream,
UInt32(data.length),
data.bytes,
parseFlags)
NSLog ("wrote \(data.length) bytes to AudioFileStream, err = \(err)")
}
// MARK: - util
private func streamTypeHintForMIMEType(mimeType : String) -> AudioFileTypeID {
switch mimeType {
case "audio/mpeg":
return kAudioFileMP3Type
case "application/octet-stream":
return kAudioFileAAC_ADTSType
default:
return 0
}
}
}
// MARK: - AudioFileStream procs
// TODO: can these be private?
let streamPropertyListenerProc : AudioFileStream_PropertyListenerProc = {
(inClientData : UnsafeMutablePointer<Void>,
inAudioFileStreamID : AudioFileStreamID,
inAudioFileStreamPropertyID : AudioFileStreamPropertyID,
ioFlags : UnsafeMutablePointer<AudioFileStreamPropertyFlags>) -> Void in
let playerInfo = UnsafeMutablePointer<PlayerInfo>(inClientData).memory
var err = noErr
NSLog ("streamPropertyListenerProc, prop id \(inAudioFileStreamPropertyID)")
switch inAudioFileStreamPropertyID {
case kAudioFileStreamProperty_DataFormat:
var dataFormat = AudioStreamBasicDescription()
var propertySize = UInt32(sizeof(AudioStreamBasicDescription))
err = AudioFileStreamGetProperty(inAudioFileStreamID, inAudioFileStreamPropertyID,
&propertySize, &dataFormat)
NSLog ("got data format, err is \(err) \(dataFormat)")
playerInfo.dataFormat = dataFormat
NSLog ("playerInfo.dataFormat: \(playerInfo.dataFormat)")
case kAudioFileStreamProperty_MagicCookieData:
NSLog ("got magic cookie")
case kAudioFileStreamProperty_ReadyToProducePackets:
NSLog ("got ready to produce packets")
var audioQueue = AudioQueueRef()
var dataFormat = playerInfo.dataFormat!
err = AudioQueueNewOutput(&dataFormat,
queueCallbackProc,
inClientData,
nil,
nil,
0,
&audioQueue)
NSLog ("created audio queue, err is \(err), queue is \(audioQueue)")
playerInfo.audioQueue = audioQueue
default:
break
}
}
let streamPacketsProc : AudioFileStream_PacketsProc = {
(inClientData : UnsafeMutablePointer<Void>,
inNumberBytes : UInt32,
inNumberPackets : UInt32,
inInputData : UnsafePointer<Void>,
inPacketDescriptions : UnsafeMutablePointer<AudioStreamPacketDescription>) -> Void in
var err = noErr
NSLog ("streamPacketsProc got \(inNumberPackets) packets")
let playerInfo = UnsafeMutablePointer<PlayerInfo>(inClientData).memory
var buffer = AudioQueueBufferRef()
if let audioQueue = playerInfo.audioQueue {
err = AudioQueueAllocateBuffer(audioQueue,
inNumberBytes,
&buffer)
NSLog ("allocated buffer, err is \(err) buffer is \(buffer)")
buffer.memory.mAudioDataByteSize = inNumberBytes
memcpy(buffer.memory.mAudioData, inInputData, Int(inNumberBytes))
NSLog ("copied data, not dead yet")
err = AudioQueueEnqueueBuffer(audioQueue,
buffer,
inNumberPackets,
inPacketDescriptions)
NSLog ("enqueued buffer, err is \(err)")
playerInfo.totalPacketsReceived += inNumberPackets
if playerInfo.totalPacketsReceived > 100 {
err = AudioQueueStart (audioQueue,
nil)
NSLog ("started playing, err is \(err)")
playerInfo.state = .Playing
}
}
}
// MARK: - AudioQueue callback
let queueCallbackProc : AudioQueueOutputCallback = {
(inUserData : UnsafeMutablePointer<Void>,
inAudioQueue : AudioQueueRef,
inQueueBuffer : AudioQueueBufferRef) -> Void in
NSLog ("queueCallbackProc")
let playerInfo = UnsafeMutablePointer<PlayerInfo>(inUserData).memory
var err = noErr
err = AudioQueueFreeBuffer (inAudioQueue, inQueueBuffer)
NSLog ("freed a buffer, err is \(err)")
}
| cc0-1.0 | 2ef7905cd1f862dcb0c5ba348f60080f | 31.151079 | 145 | 0.635041 | 5.433435 | false | false | false | false |
jeffreybergier/Hipstapaper | Hipstapaper/Packages/V3Browser/Sources/V3Browser/Web.swift | 1 | 4980 | //
// Created by Jeffrey Bergier on 2022/07/01.
//
// MIT License
//
// Copyright (c) 2021 Jeffrey Bergier
//
// 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 WebKit
import SwiftUI
import Umbrella
import V3Store
internal struct Web: View {
@Navigation private var nav
@StateObject private var progress = ObserveBox<Double>(0)
internal var body: some View {
ZStack(alignment: .top) {
_Web(progress: self.progress)
.ignoresSafeArea()
ProgressView(value: self.progress.value, total: 1)
.opacity(self.nav.isLoading ? 1 : 0)
.animation(.default, value: self.progress.value)
.animation(.default, value: self.nav.isLoading)
}
}
}
fileprivate struct _Web: View {
@Navigation private var nav
@Environment(\.codableErrorResponder) private var errorChain
@ObservedObject fileprivate var progress: ObserveBox<Double>
@StateObject private var kvo = SecretBox(Array<NSObjectProtocol>())
private func update(_ wv: WKWebView, context: Context) {
if self.nav.shouldStop {
wv.stopLoading()
self.nav.shouldStop = false
}
if self.nav.shouldReload {
wv.reload()
self.nav.shouldReload = false
}
if self.nav.shouldGoBack {
wv.goBack()
self.nav.shouldGoBack = false
}
if self.nav.shouldGoForward {
wv.goForward()
self.nav.shouldGoForward = false
}
if wv.configuration.preferences.javaScriptEnabled != self.nav.isJSEnabled {
wv.configuration.preferences.javaScriptEnabled = self.nav.isJSEnabled
wv.reload()
}
if let load = self.nav.shouldLoadURL {
wv.load(URLRequest(url: load))
self.nav.shouldLoadURL = nil
}
}
private func makeWebView(context: Context) -> WKWebView {
let config = WKWebViewConfiguration()
let wv = WKWebView(frame: .zero, configuration: config)
wv.configuration.websiteDataStore = .nonPersistent()
wv.navigationDelegate = context.coordinator
let token1 = wv.observe(\.isLoading)
{ [unowned nav = _nav.raw] wv, _ in
nav.value.isLoading = wv.isLoading
}
let token2 = wv.observe(\.url)
{ [unowned nav = _nav.raw] wv, _ in
nav.value.currentURL = wv.url
}
let token3 = wv.observe(\.title)
{ [unowned nav = _nav.raw] wv, _ in
nav.value.currentTitle = wv.title ?? ""
}
let token4 = wv.observe(\.estimatedProgress)
{ [unowned progress] wv, _ in
progress.value = wv.estimatedProgress
}
let token5 = wv.observe(\.canGoBack)
{ [unowned nav = _nav.raw] wv, _ in
nav.value.canGoBack = wv.canGoBack
}
let token6 = wv.observe(\.canGoForward)
{ [unowned nav = _nav.raw] wv, _ in
nav.value.canGoForward = wv.canGoForward
}
self.kvo.value = [token1, token2, token3, token4, token5, token6]
return wv
}
func makeCoordinator() -> GenericWebKitNavigationDelegate {
return .init { [errorChain] error in
errorChain(.init(error))
}
}
}
#if canImport(AppKit) && !targetEnvironment(macCatalyst)
extension _Web: NSViewRepresentable {
func makeNSView(context: Context) -> WKWebView {
return self.makeWebView(context: context)
}
func updateNSView(_ wv: WKWebView, context: Context) {
self.update(wv, context: context)
}
}
#else
extension _Web: UIViewRepresentable {
func makeUIView(context: Context) -> WKWebView {
return self.makeWebView(context: context)
}
func updateUIView(_ wv: WKWebView, context: Context) {
self.update(wv, context: context)
}
}
#endif
| mit | 0994094f868abbaec9b3215221057315 | 33.583333 | 83 | 0.629317 | 4.360771 | false | false | false | false |
orta/Swift-at-Artsy | Beginners/Lesson One/Lesson One.playground/Contents.swift | 1 | 8725 | import Foundation
/*:
(Note: a screen recording of a presentation of this material is [available on YouTube](https://github.com/artsy/Swift-at-Artsy/tree/master/Beginners/Lesson%20One).)
Hey! So we're going to be looking at Swift from the perspective of learning programming. This means you get to ask awkward questions and I struggle to verbalise concepts that are the programming equivalent of muscle memory. It'll be fun!
To start off we need to get to a point where we can write any code. We're going to assume that you already have a copy of Xcode 7 installed. With that, let's get started!
Open Xcode and you'll get this Welcome dialogue.

We'll be using _playgrounds_ to learn Swift. Click "Get started with a playground", give it a name, and make sure the platform is set to **OS X**.

Awesome. Xcode will create an open the playground for you. It'll look something like this.

The large pane on the left is where we're going to write code. On the right is where the results of our code are displayed. You can see that there's already one line of code written for us, `var str = "Hello, playground"`, and the results pane says `"Hello, playground"`. Neat.
Normally for things I work with, the code we are writing gets transformed from something we, as humans, kind-of understand to something a machine understands via a compiler. Let's stick with the idea that it's basically a translator from human to machine. Normally its a big upfront conversion, for example Eigen can take 5 minutes to compile.
We're going to use Playgrounds, which is more like a back and forth conversation with the compiler, so it's much faster to write code and test things out. These are called REPLs.
What this means is whatever you type will be run by Xcode and the results will be shown on the right. When Xcode is compiling code (whenever you change text), the top bar of the window will change to say "Running" and will show a little spinner.
Let's start by saying what _isn't_ code. You see the the first line, how it is greyed out? Well that's a comment. Comments are annotations in the code that are not ran by the compiler. We'll be using comments occasionally to skip bits of code, or to remind us what something is.
OK let's write some code, let's try typing some things.
*/
1 + 2
1 / 2
1.0 / 2.0
"Hello, Artsy"
/*:
You can see the results in the results pane:

In programming, we want to work with abstractions. So let's make our first variable. A variable holds a value that you can refer to later, you can name them (almost) whatever you want.
Variables are themselves an abstract concept, and it's normal for beginners to take time getting comfortable with them. In essence, a variable is a way to store something in a place that you can refer to later. There are a few good reasons to do this, but the most common one is that we need to refer to the same value more than once.
On an artist's Artsy page, we show their name more than once. It's useful to be able to store the artists name in a variable _once_ and then refer to that variable multiple times to show the user an artist's page.
We're going to make a simple calculator with 3 variables. What I'd like to do is define a variable called `a` and `b` then add them together to make `c`. This is a simple example, but it's about foundations.
*/
var a = 2
var b = 3
var c = a + b
/*:
In this case, you can see that we're referring back to `a` and `b` as variables, instead of the numbers `2` and `3`. This is a simple example, and with more experience, you'll get more comfortable.
Variables all have a _type_. Some variables are numbers, and some are strings, and some are other things, too! Numbers are often `Int`, or an integer (basically a round number: 1, 2, 3, -500, 401). Swift is a **strongly-typed language**, which means that types matter a lot. Swift won't let you confuse one type for another. Even though we haven't _told_ Swift what the type of our variables are, the compiler figures it out automatically.
In Swift, `:` specifies a type. So the following two lines are equivalent.
*/
var myString = "Hello, Artsy"
// var myString: String = "Hello, Artsy"
/*:
In this case we're dealing with a collection of letters, that combined, we call a string. This is common terminology in most programming languages, think of it as a string of letters.
*/
// var myString: String = 1
/*:
If you uncomment, Swift will complain and say that `'Int' is not convertible to 'String'`. This is Swift's compile-time type checking. It prevents bugs from happening in apps at runtime by giving you errors before-hand. Swift's primary goal is safety against crashes in apps.
When we're writing code, very often we want to print out some useful information for someone to read. We're going to use this to show that some of our code is running. So lets add a print statement saying what the value of `c` is:
*/
print(c)
/*:
With `print` working, we can start doing some logic. We want to start checking how big our `c` is, and just like in English, we'll use an `if` statement:
*/
if c > 6 {
print("Pretty big c you got there.")
}
/*:
Let's unpack what we're seeing here. `if [something]` - what's happening here is that the bit after the `if` is checking to see if `c` is greater than the number (`Int`) `6`. If it is, then it will run the code inside the braces.
`if` statements are fundamentally about doing some code only under certain circumstances. For example, Artsy only shows the "Inquire on Artwork" button **if** that artwork can be inquired upon. There are lots of different places in our code where it's useful to do something only if a condition is met.
It is common to use a left margin / indentation to indicate that something is inside a braced section. It's not enforced though.
*/
if c > 6 {
print("Pretty big c you got there.")
}
/*:
*/
if c > 6 {
print("Pretty big c you got there.")
}
/*:
*/
if c > 6 { print("Pretty big c you got there.") }
/*:
We've got one more thing to go over, and that is loops. Loops repeat a section of code. Computers are really good at doing the same thing over and over, and loops are how programmers tell computers to do that. Repeating code is really useful in the Artsy's artwork pages, specifically in the related artworks section. As programmers, we tell the computer how to add _one_ artwork to the page, and then tell the computer to do that over and over for all the related artworks.
Let's make a nice simple loop, one that reads like English. For _a_ number in _zero to c_.
*/
for number in 0...c {
print("hi")
}
/*:
It has the same behavior that we saw in the `if` example. It will run the thing inside the braces as many times as the value of `c`. Each time it will print out `"hi"`. I think we can expand on this one little bit. The word `number` here is actually a variable, let's make it sound all mathematical and call it `x` instead.
*/
for x in 0...c {
print("hi")
}
/*:
Now we know it's a variable, lets print it!
*/
for x in 0...c {
print(x)
}
/*:
For loops, often just called "loops", are foundational to programming. In this example above, we've looped over all the numbers from `0` to `c`, but you can loop over other things, too. Say we're making an app at Artsy that shows a bunch of artworks – we might loop over all the artworks to show them on the screen.
If you hit the little triangle in the bottom left you can see the printed output!
----------------
So let's recap.
* We've learned a little bit about variables, they are named values that make it easier for us to think about what something represents vs what it is.
* Then we looked at some `String`s, and showed that you can't change something from a string to a number once you've start using it as a `String`,
* We then printed some information.
* After that we looked at adding an `if` statement to add some logic to our code.
* Finally we wrapped up with a `for in` loop.
If you're keen, feel free to keep playing in the playground. Try changing things in the loops to see what happens. Is it what you expected to happen? Why or why not?
What do you think this code would do?
*/
for number in 0...15 {
if number > 5 {
print("This is greater than five")
}
}
/*:
What about this?
*/
for number in 0...15 {
if number > 5 {
print("This is greater than five")
} else {
print("This is less than five")
}
}
/*:
You can also look at the [free Stanford Swift Course](https://www.youtube.com/playlist?list=PLxwBNxx9j4PW4sY-wwBwQos3G6Kn3x6xP)
*/ | cc0-1.0 | 7266de17d77f40e4143079dcc23c5e25 | 42.62 | 474 | 0.733693 | 3.832601 | false | false | false | false |
jorjuela33/OperationKit | OperationKit/Observers/NetworkObserver.swift | 1 | 2487 | //
// NetworkObserver.swift
// beacon-ios
//
// Created by Jorge Orjuela on 3/21/16.
// Copyright © 2016 Stabilitas. All rights reserved.
//
import UIKit
public struct NetworkObserver: ObservableOperation {
private let networkIndicatorManager: NetworkIndicatorManager
// MARK: Initializer
public init(networkIndicatorManager: NetworkIndicatorManager) {
self.networkIndicatorManager = networkIndicatorManager
}
// MARK: ObservableOperation
public func operationDidStart(_ operation: Operation) {
DispatchQueue.main.async {
self.networkIndicatorManager.networkActivityDidStart()
}
}
public func operation(_ operation: Operation, didProduceOperation newOperation: Foundation.Operation) { }
public func operationDidFinish(_ operation: Operation, errors: [Error]) {
DispatchQueue.main.async {
self.networkIndicatorManager.networkActivityDidEnd()
}
}
}
public class NetworkIndicatorManager {
private var activityCount = 0
private var networkIndicatorObserver: NetworkIndicatorObserver
private var cancelled = false
// MARK: Initialization
init(networkIndicatorObserver: NetworkIndicatorObserver) {
self.networkIndicatorObserver = networkIndicatorObserver
}
// MARK: Instance methods
func networkActivityDidStart() {
assert(Thread.isMainThread)
activityCount += 1
updateIndicatorVisibility()
}
func networkActivityDidEnd() {
assert(Thread.isMainThread)
activityCount -= 1
updateIndicatorVisibility()
}
// MARK: Private methods
private func hideIndicator() {
cancelled = true
networkIndicatorObserver.isNetworkActivityIndicatorVisible = false
}
private func showIndicator() {
cancelled = false
networkIndicatorObserver.isNetworkActivityIndicatorVisible = true
}
private func updateIndicatorVisibility() {
if activityCount > 0 {
showIndicator()
} else {
let dispatchTime = DispatchTime.now() + Double(Int64(1.0 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: dispatchTime, execute: {
guard self.cancelled == false else { return }
self.hideIndicator()
})
}
}
}
| mit | cc6b83c31a68fc6a45ac928691f41ba1 | 26.622222 | 116 | 0.646822 | 5.66287 | false | false | false | false |
xwu/swift | test/SILOptimizer/capturepromotion-wrong-lexicalscope.swift | 2 | 2442 | // Make sure project_box gets assigned the correct lexical scope when we create it.
// RUN: %target-swift-frontend -primary-file %s -Onone -emit-sil -Xllvm -sil-print-after=capture-promotion -Xllvm \
// RUN: -sil-print-debuginfo -o /dev/null -module-name null 2>&1 | %FileCheck %s
// CHECK: sil hidden [ossa] @$s4null19captureStackPromoteSiycyF : $@convention(thin) () -> @owned @callee_guaranteed () -> Int {
// CHECK: bb0:
// CHECK: %0 = alloc_box ${ var Int }, var, name "x", loc {{.*}}:32:7, scope 3
// CHECK: %1 = project_box %0 : ${ var Int }, 0, loc {{.*}}:32:7, scope 3
// CHECK: %2 = integer_literal $Builtin.IntLiteral, 1, loc {{.*}}:32:11, scope 3
// CHECK: %3 = metatype $@thin Int.Type, loc {{.*}}:32:11, scope 3
// CHECK: %4 = function_ref @$sSi22_builtinIntegerLiteralSiBI_tcfC : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int, loc {{.*}}:32:11, scope 3
// CHECK: %5 = apply %4(%2, %3) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int, loc {{.*}}:32:11, scope 3
// CHECK: store %5 to [trivial] %1 : $*Int, loc {{.*}}:32:11, scope 3
// CHECK: %7 = copy_value %0 : ${ var Int }, loc {{.*}}:33:11, scope 3
// CHECK: %8 = project_box %7 : ${ var Int }, 0, loc {{.*}}:33:11, scope 3
// CHECK: mark_function_escape %1 : $*Int, loc {{.*}}:33:11, scope 3
// CHECK: %10 = function_ref @$s4null19captureStackPromoteSiycyFSiycfU_Tf2i_n : $@convention(thin) (Int) -> Int, loc {{.*}}:33:11, scope 3
// CHECK: %11 = load [trivial] %8 : $*Int, loc {{.*}}:33:11, scope 3
// CHECK: destroy_value %7 : ${ var Int }, loc {{.*}}:33:11, scope 3
// CHECK: %13 = partial_apply [callee_guaranteed] %10(%11) : $@convention(thin) (Int) -> Int, loc {{.*}}:33:11, scope 3
// CHECK: debug_value %13 : $@callee_guaranteed () -> Int, let, name "f", loc {{.*}}:33:7, scope 3
// There used to be a begin_borrow here. We leave an emptyline here to preserve line numbers.
// CHECK: %15 = copy_value %13 : $@callee_guaranteed () -> Int, loc {{.*}}:34:10, scope 3
// There used to be an end_borrow here. We leave an emptyline here to preserve line numbers.
// CHECK: destroy_value %13 : $@callee_guaranteed () -> Int, loc {{.*}}:35:1, scope 3
// CHECK: destroy_value %0 : ${ var Int }, loc {{.*}}:35:1, scope 3
// CHECK: return %15 : $@callee_guaranteed () -> Int, loc {{.*}}:34:3, scope 3
// CHECK: }
func captureStackPromote() -> () -> Int {
var x = 1
let f = { x }
return f
}
| apache-2.0 | 056e0fd7d557bab121cfb18da485a974 | 68.771429 | 162 | 0.600737 | 3.130769 | false | false | false | false |
mac-cain13/DocumentStore | DocumentStoreTests/DocumentStoreTestsOld.swift | 1 | 4448 | //
// DocumentStoreTests.swift
// DocumentStoreTests
//
// Created by Mathijs Kadijk on 02-11-16.
// Copyright © 2016 Mathijs Kadijk. All rights reserved.
//
import XCTest
import DocumentStore
////////
let documentStore = try! DocumentStore(identifier: "MyStore",
documentDescriptors: [Message.documentDescriptor])
struct Message: Document, Codable {
static let documentDescriptor = DocumentDescriptor<Message>(name: "Message",
identifier: Identifier(keyPath: \.id),
indices: [
Index(name: "read", keyPath: \.read),
Index(name: "senderName", keyPath: \.sender.name),
Index(name: "receiverName", keyPath: \.receiver.name),
Index(name: "sentDate", keyPath: \.sentDate)
])
let id: Int
let read: Bool
let sentDate: Date
let sender: Person
let receiver: Person
let subject: String?
let text: String
}
struct Person: Codable {
let id: Int
let name: String
}
///////
class DocumentStoreTestsOld: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testExample() {
let message = Message(id: 1, read: false, sentDate: Date(), sender: Person(id: 1, name: "John Appleseed"), receiver: Person(id: 2, name: "Jane Bananaseed"), subject: nil, text: "Hi!\nHow about dinner?")
documentStore.write(handler: { error in
if let error = error {
fatalError("\(error)")
}
}, actions: { transaction in
try transaction.insert(document: message, mode: .addOrReplace)
return .saveChanges
})
/* Promise version */
// documentStore.write { transaction in
// try transaction.insert(document: message, mode: .addOrReplace)
// return .saveChanges
// }
// .then {
// // Hooray!
// }
// .trap { error in
// fatalError("\(error)")
// }
let newestMessageQuery = Query<Message>()
.sorted(by: \Message.sentDate, order: .ascending)
.filtered(by: !\.read && \.sender.name == "Mathijs")
documentStore.read(handler: { result in
if case let .success(.some(message)) = result {
debugPrint(message.id)
}
}) { try $0.fetchFirst(matching: newestMessageQuery) }
// documentStore.write(handler: { _ in }) { transaction in
// try transaction.add(document: rswiftDeveloper)
// return .SaveChanges
// }
// try Query<Developer>()
// .filtered { $0.age > 18 && $0.age < 30 }
// .sorted { $0.age.ascending() }
// .skipping(upTo: 3)
// .limited(upTo: 1)
// .delete()
// let documentStore: DocumentStore! = nil
// documentStore!.read(handler: { developers in print(developers) }) { transaction in
// try transaction.fetch(matching:
// Query<Developer>()
// .filtered { _ in \.age > 18 }
// .sorted { _ in (\Developer.age).ascending() }
// )
// }
// documentStore!.read {
// try $0.fetchFirst(
// Query<Developer>()
// .filtered { $0.age > 18 && $0.age < 30 }
// .sorted { $0.age.ascending() }
// .skipping(upTo: 3)
// .limited(upTo: 1)
// )
// }
//
//
// return try Query<Developer>()
// .filtered { $0.age > 18 && $0.age < 30 }
// .sorted { $0.age.ascending() }
// .skipping(upTo: 3)
// .limited(upTo: 1)
// .execute(operation: transaction.fetchFirst)
// }
// .then { developer in
//
// }
// Promise example
// documentStore!.read { transaction in
// try Query<Developer>()
// .filtered { $0.age > 18 }
// .sorted { $0.age.ascending() }
// .execute(operation: transaction.fetchFirst)
// }
// .then { developer in
// youngestAdultDeveloper.text = developer?.name ?? "No adults found."
// }
}
}
| mit | a9ef97e758e8459e4f82dd7736553029 | 30.097902 | 208 | 0.498538 | 4.255502 | false | false | false | false |
VigaasVentures/iOSWoocommerceClient | WoocommerceClient/models/Cart.swift | 1 | 2356 | //
// Cart.swift
// WoocommerceClient
//
// Created by Damandeep Singh on 15/02/17.
// Copyright © 2017 Damandeep Singh. All rights reserved.
//
import UIKit
public class Cart: NSObject {
var totalPrice:Double = 0
var totalWeight:Double = 0
var cartItems:[CartLine] = []
public func addToCart(item:CartLine) {
var ADDED:Bool = false
for idx in cartItems.indices {
let c = cartItems[idx]
if c.productId == item.productId {
if c.variationId == item.variationId {
ADDED = true
totalPrice = totalPrice - (c.price! * Double(c.quantity!)) + (Double(item.quantity!) * item.price!)
totalWeight = totalWeight - (c.weight! * Double(c.quantity!)) + (Double(item.quantity!) * item.weight!)
cartItems[idx] = item
return
}
else {
ADDED = true
totalPrice = totalPrice + (Double(item.quantity!) * item.price!)
totalWeight = totalWeight + (Double(item.quantity!) * item.weight!)
cartItems.append(item)
return
}
}
}
if(!ADDED) {
totalPrice = totalPrice + (Double(item.quantity!) * item.price!)
totalWeight = totalWeight + (Double(item.quantity!) * item.weight!)
cartItems.append(item)
}
}
public func getCartItems() -> [CartLine] {
return self.cartItems
}
public func updateCartItem(item:CartLine, at position:Int) {
let c = cartItems[position]
totalPrice = totalPrice - (c.price! * Double(c.quantity!)) + (Double(item.quantity!) * item.price!)
totalWeight = totalWeight - (c.weight! * Double(c.quantity!)) + (Double(item.quantity!) * item.weight!)
cartItems[position] = item
}
public func removeCartItem(at position: Int) {
let c = cartItems[position]
totalPrice = totalPrice - (c.price! * Double(c.quantity!))
totalWeight = totalWeight - (c.weight! * Double(c.quantity!))
self.cartItems.remove(at: position)
}
public func clearCart() {
self.cartItems = []
self.totalWeight = 0
self.totalPrice = 0
}
}
| mit | 5d4c186234d14696ff76762e2ecd8606 | 32.642857 | 123 | 0.544374 | 4.410112 | false | false | false | false |
EZ-NET/CodePiece | CodePiece/Windows/Timeline/TableCell/TimelineHashtagTableCellView.swift | 1 | 2555 | //
// TimelineHashtagTableCellView.swift
// CodePiece
//
// Created by Tomohiro Kumagai on H27/11/09.
// Copyright © 平成27年 EasyStyle G.K. All rights reserved.
//
import Cocoa
import Swim
import ESTwitter
struct TimelineHashtagTableCellItem{
var previousHashtags: HashtagSet?
var currentHashtags: HashtagSet
init(previousHashtags: HashtagSet?, currentHashtags: HashtagSet) {
self.previousHashtags = previousHashtags
self.currentHashtags = currentHashtags
}
}
extension TimelineHashtagTableCellItem : TimelineTableItem {
var timelineItemTweetId: String? {
return nil
}
var timelineCellType: TimelineTableCellType.Type {
return TimelineHashtagTableCellView.self
}
}
@IBDesignable
@objcMembers
final class TimelineHashtagTableCellView: NSTableCellView {
var item = TimelineHashtagTableCellItem(previousHashtags: nil, currentHashtags: []) {
didSet {
previousHashtagLabel.stringValue = item.previousHashtags?.twitterDisplayText ?? ""
currentHashtagLabel.stringValue = item.currentHashtags.twitterDisplayText
previousHashtagView.isHidden = (item.previousHashtags == nil)
}
}
var selected: Bool = false
@IBOutlet var previousHashtagLabel: NSTextField!
@IBOutlet var currentHashtagLabel: NSTextField!
@IBOutlet var previousHashtagView: NSView!
@IBOutlet var currentHashtagView: NSView!
@IBInspectable var backgroundColor: NSColor?
override func draw(_ dirtyRect: NSRect) {
switch backgroundColor {
case .some(let color):
color.set()
case .none:
NSColor.white.set()
}
dirtyRect.fill()
super.draw(dirtyRect)
}
}
extension NSUserInterfaceItemIdentifier {
static var timelineHashtagCell = NSUserInterfaceItemIdentifier(rawValue: "TimelineHashtagCell")
}
extension TimelineHashtagTableCellView : TimelineTableCellType {
static var userInterfaceItemIdentifier: NSUserInterfaceItemIdentifier = .timelineHashtagCell
static func makeCellWithItem(item: TimelineTableItem, tableView: NSTableView, owner: AnyObject?) -> NSTableCellView {
let rawView = makeCellForTableView(tableView: tableView, owner: owner)
guard let view = rawView as? TimelineHashtagTableCellView else {
fatalError("Unexpected cell type: \(type(of: rawView))")
}
guard let item = item as? TimelineHashtagTableCellItem else {
fatalError("Unexpected TableView item passed.")
}
view.item = item
return view
}
static func estimateCellHeightForItem(item:TimelineTableItem, tableView:NSTableView) -> CGFloat {
return 20.0
}
}
| gpl-3.0 | 16125b026b4b89f204b28d24d26728ed | 21.954955 | 118 | 0.759812 | 4.378007 | false | false | false | false |
pangpingfei/SimpleLoadingView | SimpleLoadingView/SimpleLoading.swift | 1 | 5317 | //
// SimpleLoading.swift
// SimpleLoadingView
//
// Created by 庞平飞 on 2016/12/31.
// Copyright © 2016年 PangPingfei. All rights reserved.
//
public struct SimpleLoading {
fileprivate static var maskView: UIView!
fileprivate static var loadingView: SimpleLoadingView?
}
public extension SimpleLoading {
/// SimpleLoading global settings
public struct Config {
public static var overApplicationWindow: Bool = false // default is false
/// Ignore all interaction events.
/// If nil, when you use 'show()' with 'inView' pramater, is false, otherwise is true.
public static var ignoreInteractionEvents: Bool? // default is nil
/// Mask view alpha.
/// If you change 'superViewColor', or use 'show()' with 'inView' pramater, this setting will be ignored.
public static var maskViewAlpha: CGFloat = 0.3 // [0,1] range. default is 0.3
/// Super view properties.
/// If you change this default value, 'maskViewAlpha' will be ignored.
public static var superViewColor: UIColor = .clear // default is .clear
/// Loading view properties.
public static var viewColor: UIColor = .white // default is .white
public static var viewAlpha: CGFloat = 1 // [0,1] range. default is 1
public static var viewCornerRadius: CGFloat = 5 // default is 5
public static var viewBorderWidth: CGFloat = 0 // default is 0
public static var viewBorderColor: UIColor = .black // default is opaque black
public static var viewShadowOpacity: Float = 0 // [0,1] range. default is 0
/// Activity properties.
public static var activityStyle: UIActivityIndicatorViewStyle = .gray // Default is .gray
public static var activityColor: UIColor? // default is nil
/// Text properties.
public static var textColor: UIColor = .lightGray // default is .lightGray
public static var textSize: CGFloat = 15 // default is 15
/// Minimum spacing between view and superView.
/// If your text is more then one line, it is useful.
public static var minHorizontalMargin: CGFloat = 15 // default is 15
public static var minVerticalMargin: CGFloat = 20 // default is 20
/// Spacing between text or activity and edge.
public static var horizontalPadding: CGFloat = 20 // default is 20 (Style.noText is 15)
public static var verticalPadding: CGFloat = 15 // default is 15
/// Spacing between activity and text.
public static var horizontalSpacing: CGFloat = 5 // default is 5
public static var verticalSpacing: CGFloat = 8 // default is 8
}
/// SimpleLoading style
public enum Style {
/// Only activity.
case noText
/// Only text.
case text(String)
/// Activity on left, text on right.
case textRight(String)
/// Text on left, activity on right.
case textLeft(String)
/// Activity on top, text on bottom.
case textBottom(String)
/// Text on top, activity on bottom.
case textTop(String)
}
}
public extension SimpleLoading {
/// Show SimpleLoadingView
/// If there is a SimpleLoadingView already, it will call 'hide()' function first.
/// - Parameters:
/// - style: SimpleLoading.Style. default is .noText
/// - duration: TimeInterval. SimpleLoadingView will hide after it. default is nil, you need to hide view use ‘hide()’
/// - inView: UIView. SimpleLoadingView will be added to the view. default is nil
public static func show(_ style: SimpleLoading.Style = .noText, duration: TimeInterval? = nil, inView: UIView? = nil) {
guard loadingView == nil else {
hide {
show(style, duration: duration, inView: inView)
}
return
}
guard topMostController != nil else {
debugPrint("You don't have any views set. You may be calling them in viewDidLoad. Try viewDidAppear instead.")
return
}
self.loadingView = SimpleLoadingView(style: style)
DispatchQueue.main.async {
let alpha = Config.maskViewAlpha
if inView == nil, Config.superViewColor == .clear, alpha > 0, alpha <= 1 {
maskView = maskView ?? UIView(frame: UIApplication.shared.keyWindow!.frame)
maskView.backgroundColor = UIColor.black.withAlphaComponent(0)
topMostController?.view.addSubview(maskView)
UIView.animate(withDuration: 0.2, animations: {
maskView.backgroundColor = maskView.backgroundColor?.withAlphaComponent(alpha)
})
}
self.loadingView?.show(inView: inView)
}
if let duration = duration {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(duration * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: {
hide()
})
}
}
/// Hide SimpleLoadingView
/// - Parameters:
/// - completion: Closure. default is nil
public static func hide(_ completion: (() -> Void)? = nil) {
guard loadingView != nil else {
debugPrint("No SimpleLoadingView...")
return
}
func removeMaskView() {
if maskView != nil {
UIView.animate(withDuration: 0.2, animations: {
maskView.backgroundColor = maskView.backgroundColor?.withAlphaComponent(0)
}, completion: { _ in
maskView.removeFromSuperview()
completion?()
})
} else {
completion?()
}
}
func removeView() {
loadingView?.hide() {
self.loadingView = nil
removeMaskView()
}
}
if Thread.current.isMainThread { removeView() } else {
DispatchQueue.main.async { removeView() }
}
}
}
| mit | 6269f93a9ae568add306dc6fed5bbb86 | 28.966102 | 145 | 0.693439 | 3.993976 | false | false | false | false |
dvor/Antidote | Antidote/ChangeAutodownloadImagesController.swift | 2 | 2634 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
import UIKit
protocol ChangeAutodownloadImagesControllerDelegate: class {
func changeAutodownloadImagesControllerDidChange(_ controller: ChangeAutodownloadImagesController)
}
class ChangeAutodownloadImagesController: StaticTableController {
weak var delegate: ChangeAutodownloadImagesControllerDelegate?
fileprivate let userDefaults: UserDefaultsManager
fileprivate let selectedStatus: UserDefaultsManager.AutodownloadImages
fileprivate let neverModel = StaticTableDefaultCellModel()
fileprivate let wifiModel = StaticTableDefaultCellModel()
fileprivate let alwaysModel = StaticTableDefaultCellModel()
init(theme: Theme) {
self.userDefaults = UserDefaultsManager()
self.selectedStatus = userDefaults.autodownloadImages
super.init(theme: theme, style: .plain, model: [
[
neverModel,
wifiModel,
alwaysModel,
],
])
updateModels()
title = String(localized: "settings_autodownload_images")
}
required convenience init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
private extension ChangeAutodownloadImagesController {
func updateModels() {
neverModel.value = String(localized: "settings_never")
neverModel.didSelectHandler = changeNever
wifiModel.value = String(localized: "settings_using_wifi")
wifiModel.didSelectHandler = changeUsingWifi
alwaysModel.value = String(localized: "settings_always")
alwaysModel.didSelectHandler = changeAlways
switch selectedStatus {
case .Never:
neverModel.rightImageType = .checkmark
case .UsingWiFi:
wifiModel.rightImageType = .checkmark
case .Always:
alwaysModel.rightImageType = .checkmark
}
}
func changeNever(_: StaticTableBaseCell) {
userDefaults.autodownloadImages = .Never
delegate?.changeAutodownloadImagesControllerDidChange(self)
}
func changeUsingWifi(_: StaticTableBaseCell) {
userDefaults.autodownloadImages = .UsingWiFi
delegate?.changeAutodownloadImagesControllerDidChange(self)
}
func changeAlways(_: StaticTableBaseCell) {
userDefaults.autodownloadImages = .Always
delegate?.changeAutodownloadImagesControllerDidChange(self)
}
}
| mit | b2175257a32afa5476a2e7855b727bf8 | 32.769231 | 102 | 0.6959 | 5.853333 | false | false | false | false |
laurenyew/Stanford_cs193p_iOS_Application_Development | Spring_2017_iOS10_Swift/Calculator/Calculator/Graph/CalculatorGraphView.swift | 1 | 2774 | //
// CalculatorGraphView.swift
// Calculator
//
// Created by laurenyew on 12/13/17.
// Copyright © 2017 CS193p. All rights reserved.
//
import UIKit
@IBDesignable
class CalculatorGraphView: UIView
{
@IBInspectable
var scale: CGFloat = 40 {didSet {setNeedsDisplay()}}
@IBInspectable
var axesColor: UIColor = UIColor.blue {didSet {setNeedsDisplay()}}
@IBInspectable
var graphColor: UIColor = UIColor.red
// Center of the graph being viewed on the screen
// Used for calculating path via scale for each part of screen
var graphViewCenter: CGPoint{
return center
}
// Saved Origin of the function (changes propagate to the view here)
var originRelativeToGraphViewCenter: CGPoint = CGPoint.zero {didSet{setNeedsDisplay()}}
// Calculated origin of function
// Used for main logic, can be set to update the view's origin
var origin: CGPoint{
get{
var funcOrigin = originRelativeToGraphViewCenter
funcOrigin.x += graphViewCenter.x
funcOrigin.y += graphViewCenter.y
return funcOrigin
}
set{
var funcOrigin = newValue
funcOrigin.x -= graphViewCenter.x
funcOrigin.y -= graphViewCenter.y
originRelativeToGraphViewCenter = funcOrigin
}
}
//Graphing function: returns value Y for given value X for a given function
//If this value is changed, redraw
var graphFunctionY: ((Double) -> Double?)? {didSet {setNeedsDisplay()}}
private var axesDrawer = AxesDrawer()
override func draw(_ rect: CGRect) {
axesColor.setStroke()
axesDrawer.color = axesColor
axesDrawer.drawAxes(in: bounds, origin: origin, pointsPerUnit: scale)
//Draw the graph function in the view using the graphFunctionY
drawGraphFunction(in: bounds, origin: origin, pointsPerUnit: scale)
}
//Handles UI of drawing new function
private func drawGraphFunction(in rect: CGRect, origin: CGPoint, pointsPerUnit: CGFloat){
var graphX, graphY:CGFloat
var x,y: Double
UIGraphicsGetCurrentContext()?.saveGState()
graphColor.set()
let path = UIBezierPath()
path.lineWidth = 20.0
//For the graph view's width, calculate the function and show
for i in 0...Int(rect.size.width * scale) {
graphX = CGFloat(i)
x = Double((graphX - origin.x)/scale)
y = graphFunctionY?(x) ?? 0
graphY = (CGFloat(y) + origin.y) * scale
path.addLine(to: CGPoint(x: graphX, y: graphY))
}
path.stroke()
UIGraphicsGetCurrentContext()?.restoreGState()
}
}
| mit | 8c387bfc70d6287af4e35ea476374ee3 | 30.873563 | 93 | 0.627119 | 4.732082 | false | false | false | false |
dvor/Antidote | Antidote/ExtendedTextField.swift | 2 | 5897 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
import UIKit
import SnapKit
private struct Constants {
static let TextFieldHeight = 40.0
static let VerticalOffset = 5.0
}
protocol ExtendedTextFieldDelegate: class {
func loginExtendedTextFieldReturnKeyPressed(_ field: ExtendedTextField)
}
class ExtendedTextField: UIView {
enum FieldType {
case login
case normal
}
weak var delegate: ExtendedTextFieldDelegate?
var maxTextUTF8Length: Int = Int.max
var title: String? {
get {
return titleLabel.text
}
set {
titleLabel.text = newValue
}
}
var placeholder: String? {
get {
return textField.placeholder
}
set {
textField.placeholder = newValue
}
}
var text: String? {
get {
return textField.text
}
set {
textField.text = newValue
}
}
var hint: String? {
get {
return hintLabel.text
}
set {
hintLabel.text = newValue
}
}
var secureTextEntry: Bool {
get {
return textField.isSecureTextEntry
}
set {
textField.isSecureTextEntry = newValue
}
}
var returnKeyType: UIReturnKeyType {
get {
return textField.returnKeyType
}
set {
textField.returnKeyType = newValue
}
}
fileprivate var titleLabel: UILabel!
fileprivate var textField: UITextField!
fileprivate var hintLabel: UILabel!
init(theme: Theme, type: FieldType) {
super.init(frame: CGRect.zero)
createViews(theme: theme, type: type)
installConstraints()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func becomeFirstResponder() -> Bool {
return textField.becomeFirstResponder()
}
}
extension ExtendedTextField: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
delegate?.loginExtendedTextFieldReturnKeyPressed(self)
return false
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let resultText = (textField.text! as NSString).replacingCharacters(in: range, with: string)
if resultText.lengthOfBytes(using: String.Encoding.utf8) <= maxTextUTF8Length {
return true
}
textField.text = resultText.substringToByteLength(maxTextUTF8Length, encoding: String.Encoding.utf8)
return false
}
}
// Accessibility
extension ExtendedTextField {
override var isAccessibilityElement: Bool {
get {
return true
}
set {}
}
override var accessibilityLabel: String? {
get {
return placeholder ?? title
}
set {}
}
override var accessibilityHint: String? {
get {
var result: String?
if placeholder != nil {
// If there is a placeholder also read title as part of the hint.
result = title
}
switch (result, hint) {
case (.none, _):
return hint
case (.some, .none):
return result
case (.some(let r), .some(let s)):
return "\(r), \(s)"
}
}
set {}
}
override var accessibilityValue: String? {
get {
return text
}
set {}
}
override var accessibilityTraits: UIAccessibilityTraits {
get {
return textField.accessibilityTraits
}
set {}
}
}
private extension ExtendedTextField {
func createViews(theme: Theme, type: FieldType) {
textField = UITextField()
textField.delegate = self
textField.borderStyle = .roundedRect
textField.autocapitalizationType = .sentences
textField.enablesReturnKeyAutomatically = true
addSubview(textField)
let textColor: UIColor
switch type {
case .login:
textColor = theme.colorForType(.NormalText)
textField.layer.borderColor = theme.colorForType(.LoginButtonBackground).cgColor
textField.layer.borderWidth = 0.5
textField.layer.masksToBounds = true
textField.layer.cornerRadius = 6.0
case .normal:
textColor = theme.colorForType(.NormalText)
}
titleLabel = UILabel()
titleLabel.textColor = textColor
titleLabel.font = UIFont.systemFont(ofSize: 18.0)
titleLabel.backgroundColor = .clear
addSubview(titleLabel)
hintLabel = UILabel()
hintLabel.textColor = textColor
hintLabel.font = UIFont.antidoteFontWithSize(14.0, weight: .light)
hintLabel.numberOfLines = 0
hintLabel.backgroundColor = .clear
addSubview(hintLabel)
}
func installConstraints() {
titleLabel.snp.makeConstraints {
$0.top.leading.trailing.equalTo(self)
}
textField.snp.makeConstraints {
$0.top.equalTo(titleLabel.snp.bottom).offset(Constants.VerticalOffset)
$0.leading.trailing.equalTo(self)
$0.height.equalTo(Constants.TextFieldHeight)
}
hintLabel.snp.makeConstraints {
$0.top.equalTo(textField.snp.bottom).offset(Constants.VerticalOffset)
$0.leading.trailing.equalTo(self)
$0.bottom.equalTo(self)
}
}
}
| mit | 29d0d36046e6e482e2e96d1e3f7fc57a | 25.325893 | 129 | 0.58623 | 5.186456 | false | false | false | false |
JohnEstropia/JEToolkit | JEToolkitDemo/JEToolkitDemo/AppDelegate.swift | 1 | 1835 | //
// AppDelegate.swift
// JEToolkitDemo
//
// Created by John Rommel Estropia on 2014/10/05.
// Copyright (c) 2014 John Rommel Estropia. All rights reserved.
//
import UIKit
import JEToolkit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
// The actual default logging level masks for debug and release modes are set with consideration to performance and privacy. (For example, The HUD logger is disabled on release mode)
// For other configurable settings, refer to the JEConsoleLoggerSettings, JEHUDLoggerSettings, and JEFileLoggerSettings classes.
let consoleLoggerSettings = JEDebugging.copyConsoleLoggerSettings()
consoleLoggerSettings.logLevelMask = .all
JEDebugging.setConsoleLoggerSettings(consoleLoggerSettings)
let HUDLoggerSettings = JEDebugging.copyHUDLoggerSettings()
HUDLoggerSettings.logLevelMask = .all
HUDLoggerSettings.visibleOnStart = false
HUDLoggerSettings.buttonOffsetOnStart = 1.0
JEDebugging.setHUDLoggerSettings(HUDLoggerSettings)
let fileLoggerSettings = JEDebugging.copyFileLoggerSettings()
fileLoggerSettings.logLevelMask = [.notice, .alert]
JEDebugging.setFileLoggerSettings(fileLoggerSettings)
// Note that this will detach previously set exception handlers, such as handlers provided by analytics frameworks or other debugging frameworks.
JEDebugging.setExceptionLoggingEnabled(true)
JEDebugging.setApplicationLifeCycleLoggingEnabled(true)
JEDebugging.start()
return true
}
}
| mit | 52d393fc758b5dc5a1154259774edb54 | 38.891304 | 190 | 0.73188 | 5.681115 | false | false | false | false |
SusanDoggie/Doggie | Sources/DoggieGraphics/ImageCodec/Decoder/ImageRepDecoder.swift | 1 | 2780 | //
// ImageRepDecoder.swift
//
// The MIT License
// Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved.
//
// 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.
//
protocol ImageRepDecoder: ImageRepBase {
static var supportedMediaTypes: [MediaType] { get }
var mediaType: MediaType { get }
init?(data: Data) throws
}
struct ImageRepDecoderBitStream: Sequence, IteratorProtocol {
let mask: UInt8
let shift: Int
let bitWidth: Int
let count1: Int
let count2: Int
var counter1: Int
var counter2: Int
var byte: UInt8
var buffer: UnsafePointer<UInt8>
init(buffer: UnsafePointer<UInt8>, count: Int, bitWidth: Int) {
switch bitWidth {
case 1:
self.count1 = 8
self.shift = 7
self.mask = 0x80
case 2:
self.count1 = 4
self.shift = 6
self.mask = 0xC0
case 4:
self.count1 = 2
self.shift = 4
self.mask = 0xF0
case 8:
self.count1 = 1
self.shift = 0
self.mask = 0xFF
default: fatalError()
}
self.count2 = count
self.bitWidth = bitWidth
self.counter1 = 0
self.counter2 = 0
self.byte = 0
self.buffer = buffer
}
mutating func next() -> UInt8? {
guard counter2 < count2 else { return nil }
if counter1 == 0 {
byte = buffer.pointee
buffer += 1
counter1 = count1
}
let value = (byte & mask) >> shift
byte <<= bitWidth
counter1 -= 1
counter2 += 1
return value
}
}
| mit | c78747a2fa77657af69293ba4470e9e3 | 28.574468 | 81 | 0.605396 | 4.377953 | false | false | false | false |
mikaelm1/Teach-Me-Fast | Teach Me Fast/AddCommentVC.swift | 1 | 4393 | //
// AddCommentVC.swift
// Teach Me Fast
//
// Created by Mikael Mukhsikaroyan on 6/26/16.
// Copyright © 2016 MSquaredmm. All rights reserved.
//
import Foundation
import Firebase
class AddCommentVC: UIViewController {
var commentView: UITextView = {
let v = UITextView()
return v
}()
var currentUser: User!
var post: LessonPost!
// MARK: Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white()
setupViews()
addBarButtons()
commentView.becomeFirstResponder()
navigationController?.navigationBar.barStyle = .black
navigationController?.navigationBar.barTintColor = Constants.navbarColor
navigationController?.navigationBar.tintColor = UIColor.white()
}
deinit {
print("Deinitialzing AddCommentVC")
FirebaseClient.sharedInstance.refComments.removeAllObservers()
}
// MARK: Setup
func addBarButtons() {
let exit = UIBarButtonItem(title: "X", style: .plain, target: self, action: #selector(AddCommentVC.exitButtonTapped(sender:)))
exit.setTitleTextAttributes([NSFontAttributeName: UIFont.boldSystemFont(ofSize: 20)], for: [])
navigationItem.leftBarButtonItem = exit
let postButton = UIBarButtonItem(title: "POST", style: .plain, target: self, action: #selector(AddCommentVC.postButtonTapped(sender:)))
navigationItem.rightBarButtonItem = postButton
}
func setupViews() {
view.addSubview(commentView)
view.addConstraintsWithFormat(format: "H:|-5-[v0]-5-|", views: commentView)
view.addConstraintsWithFormat(format: "V:|-5-[v0]|", views: commentView)
}
// MARK: Helpers
func textIsLongEnough() -> Bool {
if commentView.text.characters.count > 1 && !commentView.text.isBlank {
return true
}
return false
}
func getDateString() -> String {
let d = Date()
let formatter = DateFormatter()
formatter.dateFormat = "MM/dd/yyy"
let strDate = formatter.string(from: d)
return strDate
}
func createComment() {
guard let uid = FIRAuth.auth()?.currentUser?.uid else {
print("Unable to get uid")
return
}
let username = currentUser.username
let profilePhoto = currentUser.profilePhotoUrl
let commentContent = commentView.text!
let postKey = post.postKey
let timestamp = getDateString()
var comment: [String: AnyObject] = [
"content": commentContent,
"timestamp": timestamp,
"userkey": uid,
"username": username,
"post": postKey
]
if let url = profilePhoto {
comment["user_photo_url"] = url
}
postCommentToFirebase(comment: comment)
}
// MARK: Firebase
func postCommentToFirebase(comment: [String: AnyObject]) {
_ = FirebaseClient.sharedInstance.refComments.childByAutoId().setValue(comment) { (error, ref) in
if let err = error {
print("There was an error posting comment to db: \(err)")
} else {
print("Successfully posted comment")
FirebaseClient.sharedInstance.refPosts.child(self.post.postKey).child("comments").child(ref.key).setValue("true", withCompletionBlock: { (error, ref) in
if let err = error {
print("error updating post comment keys: \(err)")
} else {
print("Successfully updated post comment key")
}
self.dismiss(animated: true, completion: nil)
})
}
}
}
// MARK: Actions
func postButtonTapped(sender: UIBarButtonItem) {
if textIsLongEnough() {
createComment()
} else {
_ = SweetAlert().showAlert("Incomplete", subTitle: "Your comment can't be empty.", style: AlertStyle.error)
}
}
func exitButtonTapped(sender: UIBarButtonItem) {
dismiss(animated: true, completion: nil)
}
}
| mit | 75c81ef7fe7668b00fb8297ee7f0508b | 29.5 | 168 | 0.574909 | 5.15493 | false | false | false | false |
spritekitbook/flappybird-swift | Chapter 8/Start/FloppyBird/FloppyBird/Tutorial.swift | 4 | 1329 | //
// Tutorial.swift
// FloppyBird
//
// Created by Jeremy Novak on 9/26/16.
// Copyright © 2016 SpriteKit Book. All rights reserved.
//
import SpriteKit
class Tutorial:SKSpriteNode {
// MARK: - Init
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(texture: SKTexture?, color: UIColor, size: CGSize) {
super.init(texture: texture, color: color, size: size)
}
convenience init() {
let texture = Textures.sharedInstance.textureWith(name: SpriteName.tutorial)
self.init(texture: texture, color: SKColor.white, size: texture.size())
setup()
setupPhysics()
}
// MARK: - Setup
private func setup() {
self.position = kScreenCenter
}
private func setupPhysics() {
}
// MARK: - Update
func update(delta: TimeInterval) {
}
// MARK: - Actions
private func animate() {
}
// MARK: - Tapped
func tapepd() {
let scaleUp = SKAction.scale(to: 1.1, duration: 0.25)
let scaleDown = SKAction.scale(to: 0.0, duration: 0.5)
let completion = SKAction.removeFromParent()
let sequence = SKAction.sequence([scaleUp, scaleDown, completion])
self.run(sequence)
}
}
| apache-2.0 | 4db0bc5b42a1dda0922188e6a909e261 | 22.298246 | 84 | 0.585843 | 4.124224 | false | false | false | false |
hrscy/TodayNews | News/News/Classes/Mine/View/UserDetailWendaCell.swift | 1 | 1438 | //
// UserDetailWendaCell.swift
// News
//
// Created by 杨蒙 on 2017/12/23.
// Copyright © 2017年 hrscy. All rights reserved.
//
import UIKit
class UserDetailWendaCell: UITableViewCell, RegisterCellFromNib {
var wenda = UserDetailWenda() {
didSet {
questionTitleLabel.text = wenda.question.title
contentLabel.text = wenda.answer.content_abstract.text
diggCountLabel.text = wenda.answer.diggCount + "赞 ·"
readCountLabel.text = wenda.answer.browCount + "人阅读"
showTimeLabel.text = wenda.answer.show_time
contentLabelHeight.constant = wenda.answer.content_abstract.textHeight
layoutIfNeeded()
}
}
/// 问题的标题
@IBOutlet weak var questionTitleLabel: UILabel!
/// 回答的内容
@IBOutlet weak var contentLabel: UILabel!
@IBOutlet weak var contentLabelHeight: NSLayoutConstraint!
/// 点赞数量
@IBOutlet weak var diggCountLabel: UILabel!
/// 阅读数量
@IBOutlet weak var readCountLabel: UILabel!
/// 显示时间
@IBOutlet weak var showTimeLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit | a39189d6d7d1aa60a6db2fb78178595f | 27.708333 | 82 | 0.650218 | 4.518033 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/Platform/Sources/PlatformUIKit/Foundation/Extensions/Rx+UIViewUtils.swift | 1 | 1422 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import RxCocoa
import RxSwift
import UIKit
/// Extension for rx that makes `UIProgressView` properties reactive
extension Reactive where Base: UIProgressView {
public var progress: Binder<Float> {
Binder(base) { view, progress in
view.setProgress(progress, animated: true)
}
}
public var trackTintColor: Binder<UIColor> {
Binder(base) { view, color in
view.trackTintColor = color
}
}
public var fillColor: Binder<UIColor> {
Binder(base) { view, color in
view.progressTintColor = color
}
}
}
extension Reactive where Base: UIView {
public var rx_heightAnchor: Binder<CGFloat> {
Binder(base) { view, height in
view.heightAnchor.constraint(equalToConstant: height).isActive = true
}
}
}
extension Reactive where Base: UILabel {
public var textColor: Binder<UIColor> {
Binder(base) { label, color in
label.textColor = color
}
}
}
extension Reactive where Base: UIImageView {
/// If this value is `nil`, the image derives its `tintColor`
/// from its superview.
public var tintColor: Binder<UIColor?> {
Binder(base) { imageView, color in
guard let tintColor = color else { return }
imageView.tintColor = tintColor
}
}
}
| lgpl-3.0 | 58db15f5ace332a8290608c5eb8a6e74 | 25.811321 | 81 | 0.627023 | 4.613636 | false | false | false | false |
farion/eloquence | Eloquence/Eloquence/Cells/EXMessageViewCell.swift | 1 | 1691 | import Foundation
import JNWCollectionView
import XMPPFramework
class EXMessageViewCell:JNWCollectionViewCell {
@IBOutlet var cellView: NSView!
@IBOutlet var cellBottomLabel: NSTextField!
@IBOutlet var avatarImage: NSImageView!
@IBOutlet var messageContentView: NSView!
@IBOutlet var textLabel: NSTextField!
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
commonInit(frame)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit(self.frame)
}
private func commonInit(frame:NSRect){
NSBundle.mainBundle().loadNibNamed(getNibName(), owner: self, topLevelObjects: nil)
let contentFrame = NSMakeRect(0,0,frame.size.width,frame.size.height)
self.cellView.frame = contentFrame
contentView = cellView
/* nameLabel = NSTextField()
contentView.addSubview(nameLabel)
nameLabel.stringValue = "LABEL"
nameLabel.sizeToFit()*/
}
/*
func getHeight() -> Int {
return 100;
}*/
func setMessage(message: EloMessage) {
textLabel.stringValue = message.text!
let formatter = NSDateFormatter()
formatter.dateStyle = .MediumStyle
formatter.timeStyle = .ShortStyle
cellBottomLabel.stringValue = formatter.stringFromDate(message.timestamp)
// nameLabel.stringValue = user.jidStr;
// viaLabel.stringValue = "via " + user.streamBareJidStr;
}
func getNibName() -> String {
fatalError("Subclasses need to implement the `getNibName()` method.")
}
} | apache-2.0 | ae6aa7c7e012a2c8db9e32b159518d05 | 26.290323 | 91 | 0.633944 | 5.047761 | false | false | false | false |
huonw/swift | test/SILGen/boxed_existentials.swift | 2 | 10265 |
// RUN: %target-swift-emit-silgen -module-name boxed_existentials -Xllvm -sil-full-demangle -enable-sil-ownership %s | %FileCheck %s
// RUN: %target-swift-emit-silgen -module-name boxed_existentials -Xllvm -sil-full-demangle -enable-sil-ownership %s | %FileCheck %s --check-prefix=GUARANTEED
func test_type_lowering(_ x: Error) { }
// CHECK-LABEL: sil hidden @$S18boxed_existentials18test_type_loweringyys5Error_pF : $@convention(thin) (@guaranteed Error) -> () {
// CHECK-NOT: destroy_value %0 : $Error
class Document {}
enum ClericalError: Error {
case MisplacedDocument(Document)
var _domain: String { return "" }
var _code: Int { return 0 }
}
func test_concrete_erasure(_ x: ClericalError) -> Error {
return x
}
// CHECK-LABEL: sil hidden @$S18boxed_existentials21test_concrete_erasureys5Error_pAA08ClericalF0OF
// CHECK: bb0([[ARG:%.*]] : @guaranteed $ClericalError):
// CHECK: [[EXISTENTIAL:%.*]] = alloc_existential_box $Error, $ClericalError
// CHECK: [[ADDR:%.*]] = project_existential_box $ClericalError in [[EXISTENTIAL]] : $Error
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: store [[ARG_COPY]] to [init] [[ADDR]] : $*ClericalError
// CHECK-NOT: destroy_value [[ARG]]
// CHECK: return [[EXISTENTIAL]] : $Error
protocol HairType {}
func test_composition_erasure(_ x: HairType & Error) -> Error {
return x
}
// CHECK-LABEL: sil hidden @$S18boxed_existentials24test_composition_erasureys5Error_psAC_AA8HairTypepF
// CHECK: [[VALUE_ADDR:%.*]] = open_existential_addr immutable_access [[OLD_EXISTENTIAL:%.*]] : $*Error & HairType to $*[[VALUE_TYPE:@opened\(.*\) Error & HairType]]
// CHECK: [[NEW_EXISTENTIAL:%.*]] = alloc_existential_box $Error, $[[VALUE_TYPE]]
// CHECK: [[ADDR:%.*]] = project_existential_box $[[VALUE_TYPE]] in [[NEW_EXISTENTIAL]] : $Error
// CHECK: copy_addr [[VALUE_ADDR]] to [initialization] [[ADDR]]
// CHECK-NOT: destroy_addr [[OLD_EXISTENTIAL]]
// CHECK: return [[NEW_EXISTENTIAL]]
protocol HairClass: class {}
func test_class_composition_erasure(_ x: HairClass & Error) -> Error {
return x
}
// CHECK-LABEL: sil hidden @$S18boxed_existentials30test_class_composition_erasureys5Error_psAC_AA9HairClasspF
// CHECK: [[VALUE:%.*]] = open_existential_ref [[OLD_EXISTENTIAL:%.*]] : $Error & HairClass to $[[VALUE_TYPE:@opened\(.*\) Error & HairClass]]
// CHECK: [[NEW_EXISTENTIAL:%.*]] = alloc_existential_box $Error, $[[VALUE_TYPE]]
// CHECK: [[ADDR:%.*]] = project_existential_box $[[VALUE_TYPE]] in [[NEW_EXISTENTIAL]] : $Error
// CHECK: [[COPIED_VALUE:%.*]] = copy_value [[VALUE]]
// CHECK: store [[COPIED_VALUE]] to [init] [[ADDR]]
// CHECK: return [[NEW_EXISTENTIAL]]
func test_property(_ x: Error) -> String {
return x._domain
}
// CHECK-LABEL: sil hidden @$S18boxed_existentials13test_propertyySSs5Error_pF
// CHECK: bb0([[ARG:%.*]] : @guaranteed $Error):
// CHECK: [[VALUE:%.*]] = open_existential_box [[ARG]] : $Error to $*[[VALUE_TYPE:@opened\(.*\) Error]]
// FIXME: Extraneous copy here
// CHECK-NEXT: [[COPY:%[0-9]+]] = alloc_stack $[[VALUE_TYPE]]
// CHECK-NEXT: copy_addr [[VALUE]] to [initialization] [[COPY]] : $*[[VALUE_TYPE]]
// CHECK: [[METHOD:%.*]] = witness_method $[[VALUE_TYPE]], #Error._domain!getter.1
// -- self parameter of witness is @in_guaranteed; no need to copy since
// value in box is immutable and box is guaranteed
// CHECK: [[RESULT:%.*]] = apply [[METHOD]]<[[VALUE_TYPE]]>([[COPY]])
// CHECK-NOT: destroy_value [[ARG]]
// CHECK: return [[RESULT]]
func test_property_of_lvalue(_ x: Error) -> String {
var x = x
return x._domain
}
// CHECK-LABEL: sil hidden @$S18boxed_existentials23test_property_of_lvalueySSs5Error_pF :
// CHECK: bb0([[ARG:%.*]] : @guaranteed $Error):
// CHECK: [[VAR:%.*]] = alloc_box ${ var Error }
// CHECK: [[PVAR:%.*]] = project_box [[VAR]]
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] : $Error
// CHECK: store [[ARG_COPY]] to [init] [[PVAR]]
// CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[PVAR]] : $*Error
// CHECK: [[VALUE_BOX:%.*]] = load [copy] [[ACCESS]]
// CHECK: [[VALUE:%.*]] = open_existential_box [[VALUE_BOX]] : $Error to $*[[VALUE_TYPE:@opened\(.*\) Error]]
// CHECK: [[COPY:%.*]] = alloc_stack $[[VALUE_TYPE]]
// CHECK: copy_addr [[VALUE]] to [initialization] [[COPY]]
// CHECK: [[METHOD:%.*]] = witness_method $[[VALUE_TYPE]], #Error._domain!getter.1
// CHECK: [[RESULT:%.*]] = apply [[METHOD]]<[[VALUE_TYPE]]>([[COPY]])
// CHECK: destroy_addr [[COPY]]
// CHECK: dealloc_stack [[COPY]]
// CHECK: destroy_value [[VALUE_BOX]]
// CHECK: destroy_value [[VAR]]
// CHECK-NOT: destroy_value [[ARG]]
// CHECK: return [[RESULT]]
// CHECK: } // end sil function '$S18boxed_existentials23test_property_of_lvalueySSs5Error_pF'
extension Error {
func extensionMethod() { }
}
// CHECK-LABEL: sil hidden @$S18boxed_existentials21test_extension_methodyys5Error_pF
func test_extension_method(_ error: Error) {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $Error):
// CHECK: [[VALUE:%.*]] = open_existential_box [[ARG]]
// CHECK: [[METHOD:%.*]] = function_ref
// CHECK-NOT: copy_addr
// CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]])
// CHECK-NOT: destroy_addr [[COPY]]
// CHECK-NOT: destroy_addr [[VALUE]]
// CHECK-NOT: destroy_addr [[VALUE]]
// -- destroy_value the owned argument
// CHECK-NOT: destroy_value %0
error.extensionMethod()
}
func plusOneError() -> Error { }
// CHECK-LABEL: sil hidden @$S18boxed_existentials31test_open_existential_semanticsyys5Error_p_sAC_ptF
// GUARANTEED-LABEL: sil hidden @$S18boxed_existentials31test_open_existential_semanticsyys5Error_p_sAC_ptF
// CHECK: bb0([[ARG0:%.*]]: @guaranteed $Error,
// GUARANTEED: bb0([[ARG0:%.*]]: @guaranteed $Error,
func test_open_existential_semantics(_ guaranteed: Error,
_ immediate: Error) {
var immediate = immediate
// CHECK: [[IMMEDIATE_BOX:%.*]] = alloc_box ${ var Error }
// CHECK: [[PB:%.*]] = project_box [[IMMEDIATE_BOX]]
// GUARANTEED: [[IMMEDIATE_BOX:%.*]] = alloc_box ${ var Error }
// GUARANTEED: [[PB:%.*]] = project_box [[IMMEDIATE_BOX]]
// CHECK-NOT: copy_value [[ARG0]]
// CHECK: [[VALUE:%.*]] = open_existential_box [[ARG0]]
// CHECK: [[METHOD:%.*]] = function_ref
// CHECK-NOT: copy_addr
// CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]])
// CHECK-NOT: destroy_value [[ARG0]]
// GUARANTEED-NOT: copy_value [[ARG0]]
// GUARANTEED: [[VALUE:%.*]] = open_existential_box [[ARG0]]
// GUARANTEED: [[METHOD:%.*]] = function_ref
// GUARANTEED: apply [[METHOD]]<{{.*}}>([[VALUE]])
// GUARANTEED-NOT: destroy_addr [[VALUE]]
// GUARANTEED-NOT: destroy_value [[ARG0]]
guaranteed.extensionMethod()
// CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[PB]] : $*Error
// CHECK: [[IMMEDIATE:%.*]] = load [copy] [[ACCESS]]
// -- need a copy_value to guarantee
// CHECK: [[VALUE:%.*]] = open_existential_box [[IMMEDIATE]]
// CHECK: [[METHOD:%.*]] = function_ref
// CHECK-NOT: copy_addr
// CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]])
// -- end the guarantee
// -- TODO: could in theory do this sooner, after the value's been copied
// out.
// CHECK: destroy_value [[IMMEDIATE]]
// GUARANTEED: [[ACCESS:%.*]] = begin_access [read] [unknown] [[PB]] : $*Error
// GUARANTEED: [[IMMEDIATE:%.*]] = load [copy] [[ACCESS]]
// -- need a copy_value to guarantee
// GUARANTEED: [[VALUE:%.*]] = open_existential_box [[IMMEDIATE]]
// GUARANTEED: [[METHOD:%.*]] = function_ref
// GUARANTEED: apply [[METHOD]]<{{.*}}>([[VALUE]])
// GUARANTEED-NOT: destroy_addr [[VALUE]]
// -- end the guarantee
// GUARANTEED: destroy_value [[IMMEDIATE]]
immediate.extensionMethod()
// CHECK: [[F:%.*]] = function_ref {{.*}}plusOneError
// CHECK: [[PLUS_ONE:%.*]] = apply [[F]]()
// CHECK: [[VALUE:%.*]] = open_existential_box [[PLUS_ONE]]
// CHECK: [[METHOD:%.*]] = function_ref
// CHECK-NOT: copy_addr
// CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]])
// CHECK: destroy_value [[PLUS_ONE]]
// GUARANTEED: [[F:%.*]] = function_ref {{.*}}plusOneError
// GUARANTEED: [[PLUS_ONE:%.*]] = apply [[F]]()
// GUARANTEED: [[VALUE:%.*]] = open_existential_box [[PLUS_ONE]]
// GUARANTEED: [[METHOD:%.*]] = function_ref
// GUARANTEED: apply [[METHOD]]<{{.*}}>([[VALUE]])
// GUARANTEED-NOT: destroy_addr [[VALUE]]
// GUARANTEED: destroy_value [[PLUS_ONE]]
plusOneError().extensionMethod()
}
// CHECK-LABEL: sil hidden @$S18boxed_existentials14erasure_to_anyyyps5Error_p_sAC_ptF
// CHECK: bb0([[OUT:%.*]] : @trivial $*Any, [[GUAR:%.*]] : @guaranteed $Error,
func erasure_to_any(_ guaranteed: Error, _ immediate: Error) -> Any {
var immediate = immediate
// CHECK: [[IMMEDIATE_BOX:%.*]] = alloc_box ${ var Error }
// CHECK: [[PB:%.*]] = project_box [[IMMEDIATE_BOX]]
if true {
// CHECK-NOT: copy_value [[GUAR]]
// CHECK: [[FROM_VALUE:%.*]] = open_existential_box [[GUAR:%.*]]
// CHECK: [[TO_VALUE:%.*]] = init_existential_addr [[OUT]]
// CHECK: copy_addr [[FROM_VALUE]] to [initialization] [[TO_VALUE]]
// CHECK-NOT: destroy_value [[GUAR]]
return guaranteed
} else if true {
// CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[PB]]
// CHECK: [[IMMEDIATE:%.*]] = load [copy] [[ACCESS]]
// CHECK: [[FROM_VALUE:%.*]] = open_existential_box [[IMMEDIATE]]
// CHECK: [[TO_VALUE:%.*]] = init_existential_addr [[OUT]]
// CHECK: copy_addr [[FROM_VALUE]] to [initialization] [[TO_VALUE]]
// CHECK: destroy_value [[IMMEDIATE]]
return immediate
} else if true {
// CHECK: function_ref boxed_existentials.plusOneError
// CHECK: [[PLUS_ONE:%.*]] = apply
// CHECK: [[FROM_VALUE:%.*]] = open_existential_box [[PLUS_ONE]]
// CHECK: [[TO_VALUE:%.*]] = init_existential_addr [[OUT]]
// CHECK: copy_addr [[FROM_VALUE]] to [initialization] [[TO_VALUE]]
// CHECK: destroy_value [[PLUS_ONE]]
return plusOneError()
}
}
| apache-2.0 | 4b304223de880d5f7f20b329c9caa1ff | 46.304147 | 173 | 0.596688 | 3.670004 | false | true | false | false |
3DprintFIT/octoprint-ios-client | OctoPhone/View Related/File Detail/FileDetailViewController.swift | 1 | 5271 | //
// FileDetailViewController.swift
// OctoPhone
//
// Created by Josef Dolezal on 09/04/2017.
// Copyright © 2017 Josef Dolezal. All rights reserved.
//
import UIKit
import ReactiveSwift
import ReactiveCocoa
/// File detail flow controller
protocol FileDetailViewControllerDelegate: class {
/// Called when user tapped on delete button and is decided to delete the file
func deleteFileButtonTapped()
}
/// File detail controller, allows to manipulate with one specific file.
///
/// File may be selected for print or deleted from printer.
class FileDetailViewController: BaseViewController {
// MARK: - Properties
/// Controller logic
fileprivate var viewModel: FileDetailViewModelType!
/// Preconfigured file detail view
private weak var fileDetailView: FileDetailView!
/// Button to mark file for print
private lazy var printButton: UIBarButtonItem = {
let button = UIBarButtonItem(barButtonSystemItem: .action, target: self,
action: #selector(printButtonTapped))
return button
}()
/// Delete file button
private lazy var deleteButton: UIBarButtonItem = {
let button = UIBarButtonItem(barButtonSystemItem: .trash, target: self,
action: #selector(deleteButtonTapped))
return button
}()
// MARK: - Initializers
convenience init(viewModel: FileDetailViewModelType) {
self.init()
self.viewModel = viewModel
}
// MARK: - Controller lifecycle
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItems = [deleteButton, printButton]
let scrollView = UIScrollView()
let fileDetailView = FileDetailView(
analysisEnabled: viewModel.outputs.analysisSectionIsEnabled.value,
statsEnabled: viewModel.outputs.statsSectionIsEnabled.value)
view.addSubview(scrollView)
scrollView.addSubview(fileDetailView)
scrollView.alwaysBounceVertical = true
scrollView.snp.makeConstraints { make in
make.edges.equalToSuperview()
}
fileDetailView.snp.makeConstraints { make in
make.edges.equalToSuperview()
}
self.fileDetailView = fileDetailView
bindViewModel()
}
// MARK: - Internal logic
/// Binds outputs of View Model to UI and converts
/// user interaction to View Model inputs
private func bindViewModel() {
viewModel.outputs.displayError.startWithValues { [weak self] error in
self?.presentError(title: error.title, message: error.message)
}
navigationItem.title = viewModel.outputs.screenTitle.value
printButton.reactive.isEnabled <~ viewModel.outputs.printIsEnabled
fileDetailView.attributesHeading.headingLabel.reactive.text <~ viewModel.outputs.attributesHeading
fileDetailView.fileNameItem.descriptionLabel.reactive.text <~ viewModel.outputs.fileNameLabel
fileDetailView.fileNameItem.detailLabel.reactive.text <~ viewModel.outputs.fileName
fileDetailView.sizeItem.descriptionLabel.reactive.text <~ viewModel.outputs.sizeLabel
fileDetailView.sizeItem.detailLabel.reactive.text <~ viewModel.outputs.size
fileDetailView.typeItem.descriptionLabel.reactive.text <~ viewModel.outputs.typeLabel
fileDetailView.typeItem.detailLabel.reactive.text <~ viewModel.outputs.type
fileDetailView.lastModificationItem.descriptionLabel.reactive.text <~ viewModel.outputs.lastModificationLabel
fileDetailView.lastModificationItem.detailLabel.reactive.text <~ viewModel.outputs.lastModification
fileDetailView.analysisHeading.headingLabel.reactive.text <~ viewModel.outputs.analysisHeading
fileDetailView.filamentLengthItem.descriptionLabel.reactive.text <~ viewModel.outputs.filamentLengthLabel
fileDetailView.filamentLengthItem.detailLabel.reactive.text <~ viewModel.outputs.filamentLength
fileDetailView.filamentVolumeItem.descriptionLabel.reactive.text <~ viewModel.outputs.filamentVolumeLabel
fileDetailView.filamentVolumeItem.detailLabel.reactive.text <~ viewModel.outputs.filamentVolume
fileDetailView.statsHeading.headingLabel.reactive.text <~ viewModel.outputs.statsHeading
fileDetailView.successesItem.descriptionLabel.reactive.text <~ viewModel.outputs.printSuccessesLabel
fileDetailView.successesItem.detailLabel.reactive.text <~ viewModel.outputs.printSuccesses
fileDetailView.failuresItem.descriptionLabel.reactive.text <~ viewModel.outputs.printFailuresLabel
fileDetailView.failuresItem.detailLabel.reactive.text <~ viewModel.outputs.printFailures
}
/// UI callback for delete button tap event
func deleteButtonTapped() {
let controller = DeletionDialogFactory.createDialog(
title: nil, message: tr(.doYouReallyWantToDeleteFileFromPrinter)) { [weak self] in
self?.viewModel.inputs.deleteButtonTapped()
}
present(controller, animated: true, completion: nil)
}
/// UI callback for print button tap event
func printButtonTapped() {
viewModel.inputs.printButtonTapped()
}
}
| mit | 74f06cb08f5b680f79a4310b6fd43998 | 36.642857 | 117 | 0.721442 | 5.47817 | false | false | false | false |
JohnnyDevMode/Hoard | HoardTests/EntryTests.swift | 1 | 1882 | //
// EntryTests.swift
// Hoard
//
// Created by John Bailey on 4/10/17.
// Copyright © 2017 DevMode Studios. All rights reserved.
//
import XCTest
@testable import Hoard
class EntryTests : XCTestCase {
func testIsValidExpired() {
let entry = Entry(value: "string")
XCTAssertFalse(entry.isValid(expiry: 0))
}
func testIsValid() {
let entry = Entry(value: "string")
XCTAssertTrue(entry.isValid(expiry: 60))
}
func testAccessed() {
let entry = Entry(value: "string")
let initial = entry.accessed
let exp = expectation(description: "Dispatch")
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(1)) {
entry.access()
let after = entry.accessed
XCTAssertNotEqual(initial, after)
exp.fulfill()
}
waitForExpectations(timeout: 5, handler: nil)
}
func testDrift() {
let entry = Entry(value: "string")
let exp = expectation(description: "Dispatch")
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(1)) {
let drift = entry.drift
XCTAssertTrue(drift > 1)
exp.fulfill()
}
waitForExpectations(timeout: 5, handler: nil)
}
func testRot() {
let entry = Entry(value: "string")
let exp = expectation(description: "Dispatch")
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(1)) {
let rot = entry.rot(expiry: 2)
XCTAssertTrue(rot > 0.5)
exp.fulfill()
}
waitForExpectations(timeout: 5, handler: nil)
}
func testIsRotten() {
let entry = Entry(value: "string")
let exp = expectation(description: "Dispatch")
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(1)) {
XCTAssertTrue(entry.isRotten(expiry: 2)) // Assuming 0.5 rot threshold.
exp.fulfill()
}
waitForExpectations(timeout: 5, handler: nil)
}
}
| mit | b6fe3cd865338690db08445d64512045 | 25.871429 | 79 | 0.652844 | 3.91875 | false | true | false | false |
February12/YLPhotoBrowser | Sources/YLPushAnimator.swift | 1 | 3075 | //
// YLPushAnimator.swift
// YLPhotoBrowser
//
// Created by yl on 2017/7/25.
// Copyright © 2017年 February12. All rights reserved.
//
import UIKit
class YLPushAnimator: NSObject,UIViewControllerAnimatedTransitioning {
var transitionImage: UIImage?
var transitionImageView: UIView?
var transitionOriginalImgFrame: CGRect = CGRect.zero
var transitionBrowserImgFrame: CGRect = CGRect.zero
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.5
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
// 转场过渡的容器view
let containerView = transitionContext.containerView
// FromVC
// let fromViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)
// let fromView = fromViewController?.view
// fromView?.isHidden = true
// ToVC
let toViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)
let toView = toViewController?.view
containerView.addSubview(toView!)
toView?.isHidden = true
if transitionOriginalImgFrame == CGRect.zero ||
(transitionImage == nil && transitionImageView == nil) {
toView?.isHidden = false
toView?.alpha = 0
UIView.animate(withDuration: 0.3, animations: {
toView?.alpha = 1
}, completion: { (finished:Bool) in
// 设置transitionContext通知系统动画执行完毕
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
})
return
}
// 有渐变的黑色背景
let bgView = UIView.init(frame: containerView.bounds)
bgView.backgroundColor = PhotoBrowserBG
bgView.alpha = 0
containerView.addSubview(bgView)
// 过渡的图片
let transitionImgView = transitionImageView ?? UIImageView.init(image: self.transitionImage)
transitionImgView.frame = self.transitionOriginalImgFrame
transitionImageView?.layoutIfNeeded()
containerView.addSubview(transitionImgView)
UIView.animate(withDuration: 0.3, animations: { [weak self] in
transitionImgView.frame = (self?.transitionBrowserImgFrame)!
self?.transitionImageView?.layoutIfNeeded()
bgView.alpha = 1
}) { (finished:Bool) in
toView?.isHidden = false
bgView.removeFromSuperview()
transitionImgView.removeFromSuperview()
// 设置transitionContext通知系统动画执行完毕
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
}
}
| mit | cd33674440beaa381b872936b1c83b6f | 33.298851 | 118 | 0.619303 | 6.089796 | false | false | false | false |
bitboylabs/selluv-ios | selluv-ios/Pods/MaterialKit/Source/MKSwitch.swift | 1 | 14034 | //
// MKSwitch.swift
// MaterialKit
//
// Created by Rahul Iyer on 29/01/16.
// Copyright © 2016 Le Van Nghia. All rights reserved.
//
import UIKit
public let kMKControlWidth: CGFloat = 40
public let kMKControlHeight: CGFloat = 20
public let kMKTrackWidth: CGFloat = 34
public let kMKTrackHeight: CGFloat = 12
public let kMKTrackCornerRadius: CGFloat = 6
public let kMKThumbRadius: CGFloat = 10
@IBDesignable
open class MKSwitch: UIControl {
@IBInspectable open override var isEnabled: Bool {
didSet {
if let switchLayer = self.switchLayer {
switchLayer.enabled = self.isEnabled
}
}
}
@IBInspectable open var thumbOnColor: UIColor = UIColor.MKColor.Blue.P500 {
didSet {
if let switchLayer = self.switchLayer {
if let onColorPallete = switchLayer.onColorPallete {
onColorPallete.thumbColor = self.thumbOnColor
switchLayer.updateColors()
}
}
}
}
@IBInspectable open var thumbOffColor: UIColor = UIColor(hex: 0xFAFAFA) {
didSet {
if let switchLayer = self.switchLayer {
if let offColorPallete = switchLayer.offColorPallete {
offColorPallete.thumbColor = self.thumbOffColor
switchLayer.updateColors()
}
}
}
}
@IBInspectable open var thumbDisabledColor: UIColor = UIColor(hex: 0xBDBDBD) {
didSet {
if let switchLayer = self.switchLayer {
if let disabledColorPallete = switchLayer.disabledColorPallete {
disabledColorPallete.thumbColor = self.thumbDisabledColor
switchLayer.updateColors()
}
}
}
}
@IBInspectable open var trackOnColor: UIColor = UIColor.MKColor.Blue.P300 {
didSet {
if let switchLayer = self.switchLayer {
if let onColorPallete = switchLayer.onColorPallete {
onColorPallete.trackColor = self.trackOnColor
switchLayer.updateColors()
}
}
}
}
@IBInspectable open var trackOffColor: UIColor = UIColor(hex: 0x000042, alpha: 0.1) {
didSet {
if let switchLayer = self.switchLayer {
if let offColorPallete = switchLayer.offColorPallete {
offColorPallete.trackColor = self.trackOffColor
switchLayer.updateColors()
}
}
}
}
@IBInspectable open var trackDisabledColor: UIColor = UIColor(hex: 0xBDBDBD) {
didSet {
if let switchLayer = self.switchLayer {
if let disabledColorPallete = switchLayer.disabledColorPallete {
disabledColorPallete.trackColor = self.trackDisabledColor
switchLayer.updateColors()
}
}
}
}
@IBInspectable open var on: Bool = false {
didSet {
if let switchLayer = self.switchLayer {
switchLayer.switchState(self.on)
sendActions(for: .valueChanged)
}
}
}
fileprivate var switchLayer: MKSwitchLayer?
public override init(frame: CGRect) {
super.init(frame: frame)
self.setup()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setup()
}
open override func layoutSubviews() {
super.layoutSubviews()
if let switchLayer = switchLayer {
switchLayer.updateSuperBounds(self.bounds)
}
}
open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
if let touch = touches.first {
let point = touch.location(in: self)
if let switchLayer = switchLayer {
switchLayer.onTouchDown(self.layer.convert(point, to: switchLayer))
}
}
}
open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
if let touch = touches.first {
let point = touch.location(in: self)
if let switchLayer = switchLayer {
switchLayer.onTouchUp(self.layer.convert(point, to: switchLayer))
}
}
}
open override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesCancelled(touches, with: event)
if touches.count > 0 {
if let touch = touches.first {
let point = touch.location(in: self)
if let switchLayer = switchLayer {
switchLayer.onTouchUp(self.layer.convert(point, to: switchLayer))
}
}
}
}
open override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesMoved(touches, with: event)
if let touch = touches.first {
let point = touch.location(in: self)
if let switchLayer = switchLayer {
switchLayer.onTouchMoved(self.layer.convert(point, to: switchLayer))
}
}
}
fileprivate func setup() {
switchLayer = MKSwitchLayer(withParent: self)
self.isEnabled = true
switchLayer!.onColorPallete = MKSwitchColorPallete(
thumbColor: thumbOnColor, trackColor: trackOnColor)
switchLayer!.offColorPallete = MKSwitchColorPallete(
thumbColor: thumbOffColor, trackColor: trackOffColor)
switchLayer!.disabledColorPallete = MKSwitchColorPallete(
thumbColor: thumbDisabledColor, trackColor: trackDisabledColor)
self.layer.addSublayer(switchLayer!)
}
}
open class MKSwitchLayer: CALayer {
open var enabled: Bool = true {
didSet {
updateColors()
}
}
open var parent: MKSwitch?
open var rippleAnimationDuration: CFTimeInterval = 0.35
fileprivate var trackLayer: CAShapeLayer?
fileprivate var thumbHolder: CALayer?
fileprivate var thumbLayer: CAShapeLayer?
fileprivate var thumbBackground: CALayer?
fileprivate var rippleLayer: MKLayer?
fileprivate var shadowLayer: MKLayer?
fileprivate var touchInside: Bool = false
fileprivate var touchDownLocation: CGPoint?
fileprivate var thumbFrame: CGRect?
fileprivate var onColorPallete: MKSwitchColorPallete? {
didSet {
updateColors()
}
}
fileprivate var offColorPallete: MKSwitchColorPallete? {
didSet {
updateColors()
}
}
fileprivate var disabledColorPallete: MKSwitchColorPallete? {
didSet {
updateColors()
}
}
public init(withParent parent: MKSwitch) {
super.init()
self.parent = parent
setup()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
fileprivate func setup() {
trackLayer = CAShapeLayer()
thumbLayer = CAShapeLayer()
thumbHolder = CALayer()
thumbBackground = CALayer()
shadowLayer = MKLayer(superLayer: thumbLayer!)
shadowLayer!.rippleScaleRatio = 0
rippleLayer = MKLayer(superLayer: thumbBackground!)
rippleLayer!.rippleScaleRatio = 1.7
rippleLayer!.maskEnabled = false
rippleLayer!.elevation = 0
thumbHolder!.addSublayer(thumbBackground!)
thumbHolder!.addSublayer(thumbLayer!)
self.addSublayer(trackLayer!)
self.addSublayer(thumbHolder!)
}
fileprivate func updateSuperBounds(_ bounds: CGRect) {
let center = CGPoint(x: bounds.midX, y: bounds.midY)
let subX = center.x - kMKControlWidth / 2
let subY = center.y - kMKControlHeight / 2
self.frame = CGRect(x: subX, y: subY, width: kMKControlWidth, height: kMKControlHeight)
updateTrackLayer()
updateThumbLayer()
}
fileprivate func updateTrackLayer() {
let center = CGPoint(x: self.bounds.midX, y: self.bounds.midY)
let subX = center.x - kMKTrackWidth / 2
let subY = center.y - kMKTrackHeight / 2
if let trackLayer = trackLayer {
trackLayer.frame = CGRect(x: subX, y: subY, width: kMKTrackWidth, height: kMKTrackHeight)
trackLayer.path = UIBezierPath(
roundedRect: trackLayer.bounds,
byRoundingCorners: UIRectCorner.allCorners,
cornerRadii: CGSize(
width: kMKTrackCornerRadius,
height: kMKTrackCornerRadius)).cgPath
}
}
fileprivate func updateThumbLayer() {
var subX: CGFloat = 0
if let parent = parent {
if parent.on {
subX = kMKControlWidth - kMKThumbRadius * 2
}
}
thumbFrame = CGRect(x: subX, y: 0, width: kMKThumbRadius * 2, height: kMKThumbRadius * 2)
if let
thumbHolder = thumbHolder,
let thumbBackground = thumbBackground,
let thumbLayer = thumbLayer {
thumbHolder.frame = thumbFrame!
thumbBackground.frame = thumbHolder.bounds
thumbLayer.frame = thumbHolder.bounds
thumbLayer.path = UIBezierPath(ovalIn: thumbLayer.bounds).cgPath
}
}
fileprivate func updateColors() {
if let trackLayer = trackLayer,
let thumbLayer = thumbLayer,
let rippleLayer = rippleLayer,
let parent = parent {
if !enabled {
if let disabledColorPallete = disabledColorPallete {
trackLayer.fillColor = disabledColorPallete.trackColor.cgColor
thumbLayer.fillColor = disabledColorPallete.thumbColor.cgColor
}
} else if parent.on {
if let
onColorPallete = onColorPallete {
trackLayer.fillColor = onColorPallete.trackColor.cgColor
thumbLayer.fillColor = onColorPallete.thumbColor.cgColor
rippleLayer.setRippleColor(onColorPallete.thumbColor, withRippleAlpha: 0.1,
withBackgroundAlpha: 0.1)
}
} else {
if let
offColorPallete = offColorPallete {
trackLayer.fillColor = offColorPallete.trackColor.cgColor
thumbLayer.fillColor = offColorPallete.thumbColor.cgColor
rippleLayer.setRippleColor(offColorPallete.thumbColor,
withRippleAlpha: 0.1,
withBackgroundAlpha: 0.1)
}
}
}
}
fileprivate func switchState(_ on: Bool) {
if on {
thumbFrame = CGRect(
x: kMKControlWidth - kMKThumbRadius * 2,
y: 0,
width: kMKThumbRadius * 2,
height: kMKThumbRadius * 2)
} else {
thumbFrame = CGRect(
x: 0, y: 0, width: kMKThumbRadius * 2, height: kMKThumbRadius * 2)
}
if let thumbHolder = thumbHolder {
thumbHolder.frame = thumbFrame!
}
self.updateColors()
}
open func onTouchDown(_ touchLocation: CGPoint) {
if enabled {
if let
rippleLayer = rippleLayer, let shadowLayer = shadowLayer,
let thumbBackground = thumbBackground, let thumbLayer = thumbLayer {
rippleLayer.startEffects(atLocation: self.convert(touchLocation, to: thumbBackground))
shadowLayer.startEffects(atLocation: self.convert(touchLocation, to: thumbLayer))
self.touchInside = self.contains(touchLocation)
self.touchDownLocation = touchLocation
}
}
}
open func onTouchMoved(_ moveLocation: CGPoint) {
if enabled {
if touchInside {
if let thumbFrame = thumbFrame, let thumbHolder = thumbHolder, let touchDownLocation = touchDownLocation {
var x = thumbFrame.origin.x + moveLocation.x - touchDownLocation.x
if x < 0 {
x = 0
} else if x > self.bounds.size.width - thumbFrame.size.width {
x = self.bounds.size.width - thumbFrame.size.width
}
thumbHolder.frame = CGRect(
x: x,
y: thumbFrame.origin.y,
width: thumbFrame.size.width,
height: thumbFrame.size.height)
}
}
}
}
open func onTouchUp(_ touchLocation: CGPoint) {
if enabled {
if let rippleLayer = rippleLayer, let shadowLayer = shadowLayer {
rippleLayer.stopEffects()
shadowLayer.stopEffects()
}
if let touchDownLocation = touchDownLocation, let parent = parent {
if !touchInside || self.checkPoint(touchLocation, equalTo: touchDownLocation) {
parent.on = !parent.on
} else {
if parent.on && touchLocation.x < touchDownLocation.x {
parent.on = false
} else if !parent.on && touchLocation.x > touchDownLocation.x {
parent.on = true
}
}
}
touchInside = false
}
}
fileprivate func checkPoint(_ point: CGPoint, equalTo other: CGPoint) -> Bool {
return fabs(point.x - other.x) <= 5 && fabs(point.y - other.y) <= 5
}
}
open class MKSwitchColorPallete {
open var thumbColor: UIColor
open var trackColor: UIColor
init(thumbColor: UIColor, trackColor: UIColor) {
self.thumbColor = thumbColor
self.trackColor = trackColor
}
}
| mit | 8cb3c6c9835ac16b99a185059fe35041 | 34.170426 | 122 | 0.577781 | 5.496671 | false | false | false | false |
esttorhe/RxSwift | RxCocoa/RxCocoa/Common/Observables/Implementations/KVOObservable.swift | 1 | 4751 | //
// KVOObservable.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 7/5/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import RxSwift
class KVOObservable<Element> : Producer<Element?>
, KVOObservableProtocol {
unowned var target: AnyObject
var strongTarget: AnyObject?
var keyPath: String
var options: NSKeyValueObservingOptions
var retainTarget: Bool
init(object: AnyObject, keyPath: String, options: NSKeyValueObservingOptions, retainTarget: Bool) {
self.target = object
self.keyPath = keyPath
self.options = options
self.retainTarget = retainTarget
if retainTarget {
self.strongTarget = object
}
}
override func run<O : ObserverType where O.Element == Element?>(observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable {
let observer = KVOObserver(parent: self) { (value) in
if value as? NSNull != nil {
sendNext(observer, nil)
return
}
sendNext(observer, value as? Element)
}
return AnonymousDisposable {
observer.dispose()
}
}
}
#if !DISABLE_SWIZZLING
func observeWeaklyKeyPathFor(target: NSObject, keyPath: String, options: NSKeyValueObservingOptions) -> Observable<AnyObject?> {
let components = keyPath.componentsSeparatedByString(".").filter { $0 != "self" }
let observable = observeWeaklyKeyPathFor(target, keyPathSections: components, options: options)
>- distinctUntilChanged { $0 === $1 }
>- finishWithNilWhenDealloc(target)
if !options.intersect(.Initial).isEmpty {
return observable
}
else {
return observable
>- skip(1)
}
}
// This should work correctly
// Identifiers can't contain `,`, so the only place where `,` can appear
// is as a delimiter.
// This means there is `W` as element in an array of property attributes.
func isWeakProperty(properyRuntimeInfo: String) -> Bool {
return properyRuntimeInfo.rangeOfString(",W,") != nil
}
func finishWithNilWhenDealloc(target: NSObject)
-> Observable<AnyObject?> -> Observable<AnyObject?> {
let deallocating = target.rx_deallocating
return { source in
return deallocating
>- map { _ in
return just(nil)
}
>- startWith(source)
>- switchLatest
}
}
func observeWeaklyKeyPathFor(
target: NSObject,
keyPathSections: [String],
options: NSKeyValueObservingOptions
) -> Observable<AnyObject?> {
weak var weakTarget: AnyObject? = target
let propertyName = keyPathSections[0]
let remainingPaths = Array(keyPathSections[1..<keyPathSections.count])
let property = class_getProperty(object_getClass(target), propertyName);
if property == nil {
return failWith(rxError(.KeyPathInvalid, "Object \(target) doesn't have property named `\(propertyName)`"))
}
let propertyAttributes = property_getAttributes(property);
// should dealloc hook be in place if week property, or just create strong reference because it doesn't matter
let isWeak = isWeakProperty(String.fromCString(propertyAttributes) ?? "")
let propertyObservable = KVOObservable(object: target, keyPath: propertyName, options: options.union(.Initial), retainTarget: false) as KVOObservable<AnyObject>
// KVO recursion for value changes
return propertyObservable
>- map { (nextTarget: AnyObject?) in
if nextTarget == nil {
return just(nil)
}
let nextObject = nextTarget! as? NSObject
let strongTarget: AnyObject? = weakTarget
if nextObject == nil {
return failWith(rxError(.KeyPathInvalid, "Observed \(nextTarget) as property `\(propertyName)` on `\(strongTarget)` which is not `NSObject`."))
}
// if target is alive, then send change
// if it's deallocated, don't send anything
if strongTarget == nil {
return empty()
}
let nextElementsObservable = keyPathSections.count == 1
? just(nextTarget)
: observeWeaklyKeyPathFor(nextObject!, keyPathSections: remainingPaths, options: options)
if isWeak {
return nextElementsObservable
>- finishWithNilWhenDealloc(nextObject!)
}
else {
return nextElementsObservable
}
}
>- switchLatest
}
#endif
| mit | 2423060a1fa42f18966d9cf47f4e0e15 | 32.223776 | 164 | 0.615449 | 5.320269 | false | false | false | false |
CatchChat/Yep | Yep/Views/Cells/DeletedFeedConversation/DeletedFeedConversationCell.swift | 1 | 969 | //
// DeletedFeedConversationCell.swift
// Yep
//
// Created by nixzhu on 15/10/29.
// Copyright © 2015年 Catch Inc. All rights reserved.
//
import UIKit
import YepKit
final class DeletedFeedConversationCell: UITableViewCell {
@IBOutlet weak var typeImageView: UIImageView!
@IBOutlet weak var deletedPromptLabel: UILabel!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var chatLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
deletedPromptLabel.text = NSLocalizedString("[Deleted]", comment: "")
deletedPromptLabel.textColor = UIColor.lightGrayColor()
selectionStyle = .None
}
func configureWithConversation(conversation: Conversation) {
guard let feed = conversation.withGroup?.withFeed else {
return
}
nameLabel.text = feed.body
chatLabel.text = NSLocalizedString("Feed has been deleted by creator.", comment: "")
}
}
| mit | 5e07e959118b16217516421c82021b6f | 25.108108 | 92 | 0.6853 | 4.878788 | false | false | false | false |
mcomella/prox | Prox/Prox/PlaceCarousel/PlaceCarousel.swift | 1 | 6155 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import UIKit
import AFNetworking
private let CellReuseIdentifier = "PlaceCarouselCell"
protocol PlaceCarouselDelegate: class {
func placeCarousel(placeCarousel: PlaceCarousel, didSelectPlaceAtIndex index: Int)
}
class PlaceCarousel: NSObject {
lazy var imageDownloader: AFImageDownloader = {
// TODO: Maybe we want more control over the configuration.
let sessionManager = AFHTTPSessionManager(sessionConfiguration: .default)
sessionManager.responseSerializer = AFImageResponseSerializer() // sets correct mime-type.
let activeDownloadCount = 4 // TODO: value?
let cache = AFAutoPurgingImageCache() // defaults 100 MB max -> 60 MB after purge
return AFImageDownloader(sessionManager: sessionManager, downloadPrioritization: .FIFO,
maximumActiveDownloads: activeDownloadCount, imageCache: cache)
}()
let defaultPadding: CGFloat = 15.0
weak var delegate: PlaceCarouselDelegate?
weak var dataSource: PlaceDataSource?
weak var locationProvider: LocationProvider?
private lazy var carouselLayout: UICollectionViewFlowLayout = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
layout.minimumLineSpacing = self.defaultPadding
layout.sectionInset = UIEdgeInsets(top: 0.0, left: self.defaultPadding, bottom: 0.0, right: self.defaultPadding)
return layout
}()
lazy var carousel: UICollectionView = {
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: self.carouselLayout)
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(PlaceCarouselCollectionViewCell.self, forCellWithReuseIdentifier: CellReuseIdentifier)
collectionView.backgroundColor = .clear
collectionView.showsHorizontalScrollIndicator = false
collectionView.showsVerticalScrollIndicator = false
return collectionView
}()
func refresh() {
carousel.reloadData()
}
}
extension PlaceCarousel: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return dataSource?.numberOfPlaces() ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CellReuseIdentifier, for: indexPath) as! PlaceCarouselCollectionViewCell
if !isCellReused(cell) {
cell.yelpReview.reviewSiteLogo.image = UIImage(named: "logo_yelp")
cell.tripAdvisorReview.reviewSiteLogo.image = UIImage(named: "logo_ta")
}
// TODO: this view is only partially filled in
guard let dataSource = dataSource,
let place = try? dataSource.place(forIndex: indexPath.item) else {
return cell
}
cell.category.text = PlaceUtilities.getString(forCategories: place.categories)
cell.name.text = place.name
downloadAndSetImage(for: place, into: cell)
PlaceUtilities.updateReviewUI(fromProvider: place.yelpProvider, onView: cell.yelpReview)
PlaceUtilities.updateReviewUI(fromProvider: place.tripAdvisorProvider, onView: cell.tripAdvisorReview)
if let location = locationProvider?.getCurrentLocation() {
place.travelTimes(fromLocation: location, withCallback: { travelTimes in
self.setTravelTimes(travelTimes: travelTimes, forCell: cell)
})
}
return cell
}
private func isCellReused(_ cell: PlaceCarouselCollectionViewCell) -> Bool {
return cell.yelpReview.reviewSiteLogo.image != nil
}
private func downloadAndSetImage(for place: Place, into cell: PlaceCarouselCollectionViewCell) {
guard let urlStr = place.photoURLs.first, let url = URL(string: urlStr) else {
print("lol unable to create URL from photo url")
cell.placeImage.image = UIImage(named: "place-placeholder")
return
}
cell.placeImage.setImageWith(url)
}
private func setTravelTimes(travelTimes: TravelTimes?, forCell cell: PlaceCarouselCollectionViewCell) {
guard let travelTimes = travelTimes else {
return
}
if let walkingTimeSeconds = travelTimes.walkingTime {
let walkingTimeMinutes = Int(round(walkingTimeSeconds / 60.0))
if walkingTimeMinutes <= TravelTimesProvider.MIN_WALKING_TIME {
if walkingTimeMinutes < TravelTimesProvider.YOU_ARE_HERE_WALKING_TIME {
cell.locationImage.image = UIImage(named: "icon_location")?.withRenderingMode(UIImageRenderingMode.alwaysTemplate)
cell.location.text = "You're here"
cell.isSelected = true
} else {
cell.location.text = "\(walkingTimeMinutes) min walk away"
cell.isSelected = false
}
return
}
}
if let drivingTimeSeconds = travelTimes.drivingTime {
let drivingTimeMinutes = Int(round(drivingTimeSeconds / 60.0))
cell.location.text = "\(drivingTimeMinutes) min drive away"
cell.isSelected = false
}
}
}
extension PlaceCarousel: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout: UICollectionViewLayout, sizeForItemAt: IndexPath) -> CGSize {
return CGSize(width: 200, height: 275)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
delegate?.placeCarousel(placeCarousel: self, didSelectPlaceAtIndex: indexPath.item)
}
}
| mpl-2.0 | 9536434c71864b179afec0ac6356de48 | 39.228758 | 147 | 0.688221 | 5.352174 | false | false | false | false |
simplepanda/SimpleSQL | Sources/SSRow.swift | 1 | 4985 | //
// Part of SimpleSQL
// https://github.com/simplepanda/SimpleSQL
//
// Created by Dylan Neild - July 2016
// [email protected]
//
// 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
/**
A row of data that has been retrieved from a MySQL server as part of a
result set. An array of ```SSRow``` objects is typically retrieved by
calling the ```executeQuery``` method of an ```SSStatement``` object,
then accessing the ```rows``` property of the resulting ```SSResults```
return value.
```SSRow``` provides translation between the raw results returned by
MySQL and Swift native data formats.
*/
public class SSRow {
/**
The row fields, as retrieved from the MySQL Server. This is a ```Dictionary```
object, where the key is a ```String``` corresponding to the field name and
and the value is an ```Any``` object containing the Swift native object representing
the data.
*/
public let fields : [String:Any]
/**
Private initializer, accepting a single row of fields. This is called by ```SSRow``
when creating the row objects.
- Parameters:
- _ The ```Dictionary``` of fields, where the key is a ```String``` and the value is an
```Any``` containing the field data.
*/
init(_ fields: [String:Any]) {
self.fields = fields
}
/**
A basic ```get``` function to retrieve any ```Any``` object for the specific field in the
row.
- Parameters:
- _ The field to retrieve, as a ```String``` representing the field / column name.
- Returns: An ```Any``` object, containing the Swift native data representing of the field.
*/
public func get(_ field: String) -> Any? {
return self.fields[field]
}
public func getString(_ field: String) -> String? {
let target : Any? = fields[field]
guard target != nil else {
return nil
}
guard target is String else {
return nil
}
return target as! String!
}
public func getInt(_ field: String) -> Int? {
let target : Any? = fields[field]
guard target != nil else {
return nil
}
guard target is Int else {
return nil
}
return target as! Int!
}
public func getInt64(_ field: String) -> Int64? {
let target : Any? = fields[field]
guard target != nil else {
return nil
}
guard target is Int64 else {
return nil
}
return target as! Int64!
}
public func getDouble(_ field: String) -> Double? {
let target : Any? = fields[field]
guard target != nil else {
return nil
}
guard target is Double else {
return nil
}
return target as! Double!
}
#if os(Linux)
public func getData(_ field: String) -> NSData? {
let target : Any? = fields[field]
guard target != nil else {
return nil
}
guard target is NSData else {
return nil
}
return target as! NSData!
}
public func getDate(_ field: String) -> NSDate? {
let target : Any? = fields[field]
guard target != nil else {
return nil
}
guard target is NSDate else {
return nil
}
return target as! NSDate!
}
#else
public func getData(_ field: String) -> Data? {
let target : Any? = fields[field]
guard target != nil else {
return nil
}
guard target is Data else {
return nil
}
return target as! Data!
}
public func getDate(_ field: String) -> Date? {
let target : Any? = fields[field]
guard target != nil else {
return nil
}
guard target is Date else {
return nil
}
return target as! Date!
}
#endif
}
| apache-2.0 | b75036e95bf4a8566bd0de2f257f5496 | 24.176768 | 99 | 0.52337 | 4.91133 | false | false | false | false |
Erin-Mounts/BridgeAppSDK | BridgeAppSDK/ProfileHeaderView.swift | 1 | 2153 | /*
Copyright (c) 2015, Apple Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. 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.
3. Neither the name of the copyright holder(s) nor the names of any contributors
may be used to endorse or promote products derived from this software without
specific prior written permission. No license is granted to the trademarks of
the copyright holders even if such marks are included in this software.
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 OWNER 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
@IBDesignable
public class ProfileHeaderView: UIView {
// MARK: Properties
var seperatorHeight = CGFloat(0.5)
var seperatorColor = UIColor.lightGrayColor()
// MARK: UIView
override public func drawRect(rect: CGRect) {
// Draw a seperator line at the bottom of the view.
var fillRect = bounds
fillRect.origin.y = bounds.size.height - seperatorHeight
fillRect.size.height = seperatorHeight
seperatorColor.setFill()
UIRectFill(fillRect)
}
}
| bsd-3-clause | 0cb40b134a04367fb3a640f4336d53f0 | 40.403846 | 81 | 0.770088 | 4.882086 | false | false | false | false |
avaidyam/Parrot | Hangouts/PBLiteDecoder.swift | 1 | 40015 | import Foundation
/* TODO: Support sharing the Coder with super. */
//
// MARK: PBLiteDecoder
//
///
/// Note: performs string numeric casting on FixedWidthInteger types.
public class PBLiteDecoder {
///
public struct Options: OptionSet {
public typealias RawValue = Int
public var rawValue: Int
public init(rawValue: RawValue) {
self.rawValue = rawValue
}
///
public static let multipleRootContainers = Options(rawValue: 1 << 0)
///
public static let primitiveRootValues = Options(rawValue: 1 << 1)
// zeroindex
}
public let options: Options
public init(options: Options = []) {
self.options = options
}
private var root: DecoderContainer? = nil
public func decode<T: Decodable>(_ value: Any) throws -> T {
self.root = DecoderContainer(owner: self, codingPath: [], content: value)
return try T(from: self.root!)
}
// Data-based wrapper...
public func decode<T: Decodable>(data: Data) throws -> T? {
guard let script = String(data: data, encoding: .utf8) else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: [], debugDescription: "Data corrupted."))
}
guard var parsed = PBLiteDecoder.sanitize(script) else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: [], debugDescription: "Data corrupted: \(script)"))
}
parsed.remove(at: 0) // FIXME: for the header thing?
return try self.decode(parsed) as T
}
/// Sanitize and decode JSON from a server PBLite response.
/// Note: This assumes the output will always be an array.
// Precompile the regex so we don't fiddle around with slow loading times.
internal static func sanitize(_ string: String) -> [Any]? {
let st = reg.stringByReplacingMatches(in: string, options: [], range: NSMakeRange(0, string.utf16.count), withTemplate: "$1null")
return try! st.decodeJSON() as? [Any]
}
private static let reg = try! NSRegularExpression(pattern: "(?<=,|\\[)(\\s)*(?=,)", options: [])
//
// MARK: PBLiteDecoder -> KeyedContainer
//
///
private class KeyedContainer<Key: CodingKey>: KeyedDecodingChildContainer {
var codingPath: [CodingKey]
var children: [DecodingChildContainer] = []
private let content: [Int: Any]
let owner: PBLiteDecoder
init(owner: PBLiteDecoder, codingPath: [CodingKey], content: [Any]) {
self.owner = owner
self.codingPath = codingPath
self.content = KeyedContainer.transform(content)
}
//
// MARK: PBLiteDecoder -> KeyedContainer -> Decoding
//
func matchesType<T: Decodable>(_: T.Type, forKey key: Key) -> Bool {
guard let outerValue = self.content[key.value()], !(outerValue is NSNull) else {
print("\(key) was null!")
return false
}
guard let _ = outerValue as? T else {
print("\(key) was of type \(type(of: outerValue)) instead of \(T.self)")
return false
}
return true
}
func matchesNumericType<T: Decodable & FixedWidthInteger>(_: T.Type, forKey key: Key) -> Bool {
guard let outerValue = self.content[key.value()], !(outerValue is NSNull) else {
print("NUMERIC: \(key) was null!")
return false
}
guard let _ = outerValue as? T else {
if let innerValue = outerValue as? String, let _ = T(innerValue) {
print("NUMERIC: \(key) was of type \(type(of: outerValue)) instead of \(T.self)")
return false
}
return false
}
return true
}
func decodeNil(forKey key: Key) throws -> Bool {
if let outerValue = self.content[key.value()], (outerValue is NSNull) {
return true
}
return false
}
func decodeNumeric<T: Decodable & FixedWidthInteger>(forKey key: Key) throws -> T {
guard let outerValue = self.content[key.value()], !(outerValue is NSNull) else {
let desc = "Expected type \(T.self) for \(key) but container stored nil."
throw DecodingError.typeMismatch(T.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: desc))
}
guard let value = outerValue as? T else {
if let value2 = outerValue as? String, let value3 = T(value2) {
return value3
}
let desc = "Expected type \(T.self) for \(key) but container stored value \(String(reflecting: outerValue))."
throw DecodingError.typeMismatch(T.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: desc))
}
return value
}
func decodeValue<T: Decodable>(forKey key: Key) throws -> T {
guard let outerValue = self.content[key.value()], !(outerValue is NSNull) else {
let desc = "Expected type \(T.self) for \(key) but container stored nil."
throw DecodingError.typeMismatch(T.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: desc))
}
guard let value = outerValue as? T else {
let desc = "Expected type \(T.self) for \(key) but container stored value \(String(reflecting: outerValue))."
throw DecodingError.typeMismatch(T.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: desc))
}
return value
}
func decode<T: Decodable>(_ type: T.Type, forKey key: Key) throws -> T {
guard let outerValue = self.content[key.value()], !(outerValue is NSNull) else {
if "\(type)".starts(with: "Array<") {
return ([] as! T)
}
let desc = "Expected type \(T.self) for \(key) but container stored nil."
throw DecodingError.typeMismatch(T.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: desc))
}
return try T(from: DecoderContainer(owner: self.owner, codingPath: self.codingPath + [key], content: outerValue))
}
//
// MARK: PBLiteDecoder -> KeyedContainer -> ChildContainer
//
func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> {
guard let outerValue = self.content[key.value()], !(outerValue is NSNull) else {
let desc = "No element matching key \(key) in the container."
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.codingPath, debugDescription: desc))
}
guard let inside = outerValue as? [Any] else {
let desc = "Expected type \(Array<Any>.self) for \(key) but container stored value \(String(reflecting: outerValue))."
throw DecodingError.typeMismatch(Array<Any>.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: desc))
}
let container = KeyedContainer<NestedKey>(owner: self.owner, codingPath: self.codingPath + [key], content: inside)
self.children.append(container)
return KeyedDecodingContainer(container)
}
func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer {
guard let outerValue = self.content[key.value()], !(outerValue is NSNull) else {
let desc = "No element matching key \(key) in the container."
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.codingPath, debugDescription: desc))
}
guard let inside = outerValue as? [Any] else {
let desc = "Expected type \(Array<Any>.self) for \(key) but container stored value \(String(reflecting: outerValue))."
throw DecodingError.typeMismatch(Array<Any>.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: desc))
}
let container = UnkeyedContainer(owner: self.owner, codingPath: self.codingPath + [key], content: inside)
self.children.append(container)
return container
}
func superDecoder() throws -> Decoder {
let key = Key(intValue: 0)! // TODO: will this even work?
return try self.superDecoder(forKey: key)
}
func superDecoder(forKey key: Key) throws -> Decoder {
guard let inside = self.content[key.value()], !(inside is NSNull) else {
let desc = "No superDecoder element found in the container."
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.codingPath, debugDescription: desc))
}
let container = DecoderContainer(owner: self.owner, codingPath: self.codingPath + [key], content: inside)
self.children.append(container)
return container
}
//
// MARK: PBLiteDecoder -> KeyedContainer -> Misc
//
var allKeys: [Key] {
return Array(self.content.keys).compactMap { Key(intValue: $0) }
}
func contains(_ key: Key) -> Bool {
return self.content.keys.contains(key.value())
}
/// Convert between an Int-keyed Dictionary and Array.
/// Note: k + 1 because message indexes start at 1.
private static func transform(_ content: [Any]) -> [Int: Any] {
var dicted: [Int: Any] = [:]
for (k, v) in content.enumerated() {
if case Optional<Any>.none = v {
// ignore nils
} else if case Optional<Any>.some(let val) = v, !(val is NSNull) {
dicted[k + 1] = val
} else if !(v is NSNull) {
dicted[k + 1] = v
}
}
/// PBLite comes with some extras...
if let extras = dicted[content.count] as? NSDictionary {
dicted.removeValue(forKey: content.count)
for (k, v) in extras {
let idx = Int(k as! String)!
dicted[idx] = v
}
}
return dicted
}
}
//
// MARK: PBLiteDecoder -> UnkeyedContainer
//
/// TODO: Fix the NSNull stuff here
private class UnkeyedContainer: UnkeyedDecodingChildContainer {
private let content: [Any]
var codingPath: [CodingKey]
var count: Int? = nil
var children: [DecodingChildContainer] = []
var currentIndex: Int {
return self.content.count - (self.count ?? 0)
}
let owner: PBLiteDecoder
init(owner: PBLiteDecoder, codingPath: [CodingKey], content: [Any]) {
self.owner = owner
self.codingPath = codingPath
self.content = content
self.count = content.count
}
//
// MARK: PBLiteDecoder -> UnkeyedContainer -> Decoding
//
func matchesType<T: Decodable>(_: T.Type) -> Bool {
guard let count = self.count, count > 0 else {
return false
}
let outerValue = self.content[self.content.count - count]
guard let _ = outerValue as? T else {
return false
}
return true
}
func matchesNumericType<T: Decodable & FixedWidthInteger>(_: T.Type) -> Bool {
guard let count = self.count, count > 0 else {
return false
}
let outerValue = self.content[self.content.count - count]
guard let _ = outerValue as? T else {
if let innerValue = outerValue as? String, let _ = T(innerValue) {
return false
}
return false
}
return true
}
func decodeNil() throws -> Bool {
return (self.count ?? 0) == 0
}
func decodeNumeric<T: Decodable & FixedWidthInteger>() throws -> T {
guard let count = self.count, count > 0 else {
let desc = "Expected type \(T.self) but container had nothing left."
throw DecodingError.typeMismatch(T.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: desc))
}
let outerValue = self.content[self.content.count - count]
guard let value = outerValue as? T else {
if let value2 = outerValue as? String, let value3 = T(value2) {
return value3
}
let desc = "Expected type \(T.self) but container stored value \(String(reflecting: outerValue))."
throw DecodingError.typeMismatch(T.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: desc))
}
self.count = count - 1 // decrement
return value
}
func decodeValue<T: Decodable>() throws -> T {
guard let count = self.count, count > 0 else {
let desc = "Expected type \(T.self) but container had nothing left."
throw DecodingError.typeMismatch(T.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: desc))
}
let outerValue = self.content[self.content.count - count]
guard let value = outerValue as? T else {
let desc = "Expected type \(T.self) but container stored value \(String(reflecting: outerValue))."
throw DecodingError.typeMismatch(T.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: desc))
}
self.count = count - 1 // decrement
return value
}
func decode<T: Decodable>(_ type: T.Type) throws -> T {
guard let count = self.count, count > 0 else {
let desc = "Expected type \(T.self) but container had nothing left."
throw DecodingError.typeMismatch(T.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: desc))
}
let outerValue = self.content[self.content.count - count]
self.count = count - 1 // decrement
return try T(from: DecoderContainer(owner: self.owner, codingPath: self.codingPath + [PBLiteKey(intValue: self.count ?? 0)!], content: outerValue))
}
//
// MARK: PBLiteDecoder -> UnkeyedContainer -> ChildContainer
//
func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer<NestedKey> {
guard let count = self.count, count > 0 else {
let desc = "No more elements remaining in the container."
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: desc))
}
let outerValue = self.content[self.content.count - count]
guard let inside = outerValue as? [Any] else {
let desc = "Expected type \(Array<Any>.self) but container stored value \(String(reflecting: outerValue))."
throw DecodingError.typeMismatch(Array<Any>.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: desc))
}
let container = KeyedContainer<NestedKey>(owner: self.owner, codingPath: self.codingPath + [PBLiteKey(intValue: self.count ?? 0)!], content: inside)
self.children.append(container)
self.count = count - 1 // decrement
return KeyedDecodingContainer(container)
}
func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer {
guard let count = self.count, count > 0 else {
let desc = "No more elements remaining in the container."
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: desc))
}
let outerValue = self.content[self.content.count - count]
guard let inside = outerValue as? [Any] else {
let desc = "Expected type \(Array<Any>.self) but container stored value \(String(reflecting: outerValue))."
throw DecodingError.typeMismatch(Array<Any>.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: desc))
}
let container = UnkeyedContainer(owner: self.owner, codingPath: self.codingPath + [PBLiteKey(intValue: self.count ?? 0)!], content: inside)
self.children.append(container)
self.count = count - 1 // decrement
return container
}
func superDecoder() throws -> Decoder {
guard let count = self.count, count > 0 else {
let desc = "No more elements remaining in the container."
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: desc))
}
let outerValue = self.content[self.content.count - count]
let container = DecoderContainer(owner: self.owner, codingPath: self.codingPath + [PBLiteKey(intValue: self.count ?? 0)!], content: outerValue)
self.children.append(container)
self.count = count - 1 // decrement
return container
}
//
// MARK: PBLiteDecoder -> UnkeyedContainer -> Misc
//
var isAtEnd: Bool {
return self.count == nil || self.count == 0
}
}
//
// MARK: PBLiteDecoder -> SingleValueContainer
//
///
private class SingleValueContainer: SingleValueDecodingChildContainer {
private let content: Any
fileprivate var children: [DecodingChildContainer] {
get { return [] } set { }
}
var codingPath: [CodingKey] {
return []
}
let owner: PBLiteDecoder
init(owner: PBLiteDecoder, content: Any) {
self.owner = owner
self.content = content
}
//
// MARK: PBLiteDecoder -> SingleValueContainer -> Decoding
//
func matchesType<T: Decodable>(_: T.Type) -> Bool {
guard case Optional<Any>.some(let val) = self.content, !(val is NSNull) else {
return false
}
guard let _ = self.content as? T else {
//if let innerValue = outerValue as? String, let _ = T(innerValue) {
// return false
//}
return false
}
return true
}
func decodeNil() -> Bool {
if case Optional<Any>.none = self.content {
return true
} else if case Optional<Any>.some(let val) = self.content, !(val is NSNull) {
return false
}
return true // uh...?
}
func decodeNumeric<T: Decodable & FixedWidthInteger>() throws -> T {
guard case Optional<Any>.some(let val) = self.content, !(val is NSNull) else {
let desc = "Expected type \(T.self) but container stored nil."
throw DecodingError.valueNotFound(T.self, DecodingError.Context(codingPath: [], debugDescription: desc))
}
guard let value = self.content as? T else {
if let value2 = self.content as? String, let value3 = T(value2) {
return value3
}
let desc = "Expected type \(T.self) but container stored value \(String(reflecting: self.content))."
throw DecodingError.typeMismatch(T.self, DecodingError.Context(codingPath: [], debugDescription: desc))
}
return value
}
func decodeValue<T: Decodable>() throws -> T {
guard case Optional<Any>.some(let val) = self.content, !(val is NSNull) else {
let desc = "Expected type \(T.self) but container stored nil."
throw DecodingError.valueNotFound(T.self, DecodingError.Context(codingPath: [], debugDescription: desc))
}
guard let value = self.content as? T else {
let desc = "Expected type \(T.self) but container stored value \(String(reflecting: self.content))."
throw DecodingError.typeMismatch(T.self, DecodingError.Context(codingPath: [], debugDescription: desc))
}
return value
}
// TODO: should this be allowed?
func decode<T: Decodable>(_ type: T.Type) throws -> T {
guard case Optional<Any>.some(let val) = self.content, !(val is NSNull) else {
let desc = "Expected type \(T.self) but container stored nil."
throw DecodingError.valueNotFound(T.self, DecodingError.Context(codingPath: [], debugDescription: desc))
}
guard let value = self.content as? [Any] else {
let desc = "Expected type \(T.self) but container stored value \(String(reflecting: self.content))."
throw DecodingError.typeMismatch(T.self, DecodingError.Context(codingPath: [], debugDescription: desc))
}
return try T(from: DecoderContainer(owner: self.owner, codingPath: [PBLiteKey(intValue: 0)!], content: value))
}
}
//
// MARK: PBLiteDecoder -> DecoderContainer
//
private class DecoderContainer: DecoderDecodingChildContainer {
public var codingPath: [CodingKey]
public var userInfo: [CodingUserInfoKey : Any] = [:]
fileprivate let owner: PBLiteDecoder
internal var children: [DecodingChildContainer] = []
fileprivate var content: Any = Optional<Any>.none as Any
fileprivate init(owner: PBLiteDecoder, codingPath: [CodingKey], content: Any) {
self.owner = owner
self.codingPath = codingPath
self.content = content
}
//
// MARK: PBLiteDecoder -> DecoderContainer -> ChildContainer
//
public func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> {
try! throwIfExists()
guard let inside = self.content as? [Any] else {
let desc = "This decoder's content could not support a keyed container."
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: desc))
}
let container = KeyedContainer<Key>(owner: self.owner, codingPath: self.codingPath, content: inside)
self.children.append(container)
return KeyedDecodingContainer(container)
}
public func unkeyedContainer() throws -> UnkeyedDecodingContainer {
try! throwIfExists()
guard let inside = self.content as? [Any] else {
let desc = "This decoder's content could not support an unkeyed container."
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: desc))
}
let container = UnkeyedContainer(owner: self.owner, codingPath: self.codingPath, content: inside)
self.children.append(container)
return container
}
public func singleValueContainer() throws -> SingleValueDecodingContainer {
try! throwIfExists()
let container = SingleValueContainer(owner: self.owner, content: self.content)
self.children.append(container)
return container
}
//
// MARK: PBLiteDecoder -> DecoderContainer -> Misc
//
private func throwIfExists() throws {
if self.children.count > 0 && !self.owner.options.contains(.multipleRootContainers) {
let desc = "This decoder is not configured to support multiple root containers."
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: desc))
}
}
}
}
//
// MARK: Helpers
//
internal struct PBLiteKey: CodingKey {
init?(intValue: Int) {
self.intValue = intValue
}
init?(stringValue: String) {
return nil
}
var intValue: Int?
var stringValue: String {
return "\(self.intValue ?? 0)"
}
}
///
fileprivate extension CodingKey {
func value() -> String {
return self.stringValue
}
func value() -> Int {
if let i = self.intValue { return i }
fatalError("requires an integer coding key")
}
}
///
fileprivate protocol DecodingChildContainer {}
// TODO: Type matching first before decodeIfPresent:
//CodingKeys(stringValue: "phoneData", intValue: 7) was of type __NSArrayM instead of ClientPhoneData
//CodingKeys(stringValue: "configurationBitType", intValue: 1) was of type __NSCFNumber instead of ClientConfigurationBitType
fileprivate protocol DecoderDecodingChildContainer: Decoder, DecodingChildContainer {}
fileprivate protocol KeyedDecodingChildContainer: KeyedDecodingContainerProtocol, DecodingChildContainer {
func matchesType<T: Decodable>(_: T.Type, forKey key: Key) -> Bool
func matchesNumericType<T: Decodable & FixedWidthInteger>(_: T.Type, forKey key: Key) -> Bool
//func decodeNil(forKey key: Self.Key) throws -> Bool
func decodeValue<T: Decodable>(forKey: Key) throws -> T
func decodeNumeric<T: Decodable & FixedWidthInteger>(forKey: Key) throws -> T
}
fileprivate protocol UnkeyedDecodingChildContainer: UnkeyedDecodingContainer, DecodingChildContainer {
func matchesType<T: Decodable>(_: T.Type) -> Bool
func matchesNumericType<T: Decodable & FixedWidthInteger>(_: T.Type) -> Bool
//mutating func decodeNil() throws -> Bool
mutating func decodeValue<T: Decodable>() throws -> T
mutating func decodeNumeric<T: Decodable & FixedWidthInteger>() throws -> T
}
fileprivate protocol SingleValueDecodingChildContainer: SingleValueDecodingContainer, DecodingChildContainer {
//func decodeNil() -> Bool
func decodeValue<T: Decodable>() throws -> T
func decodeNumeric<T: Decodable & FixedWidthInteger>() throws -> T
}
fileprivate extension KeyedDecodingChildContainer {
func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool {
return try decodeValue(forKey: key)
}
func decode(_ type: Int.Type, forKey key: Key) throws -> Int {
return try decodeNumeric(forKey: key)
}
func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 {
return try decodeNumeric(forKey: key)
}
func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 {
return try decodeNumeric(forKey: key)
}
func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 {
return try decodeNumeric(forKey: key)
}
func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 {
return try decodeNumeric(forKey: key)
}
func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt {
return try decodeNumeric(forKey: key)
}
func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 {
return try decodeNumeric(forKey: key)
}
func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 {
return try decodeNumeric(forKey: key)
}
func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 {
return try decodeNumeric(forKey: key)
}
func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 {
return try decodeNumeric(forKey: key)
}
func decode(_ type: Float.Type, forKey key: Key) throws -> Float {
return try decodeValue(forKey: key)
}
func decode(_ type: Double.Type, forKey key: Key) throws -> Double {
return try decodeValue(forKey: key)
}
func decode(_ type: String.Type, forKey key: Key) throws -> String {
return try decodeValue(forKey: key)
}
//
//
//
/*
func decodeIfPresent(_ type: Bool.Type, forKey key: Key) throws -> Bool? {
guard try self.contains(key) && !self.decodeNil(forKey: key) else { return nil }
guard self.matchesType(type, forKey: key) else { return nil }
return try decodeValue(forKey: key)
}
func decodeIfPresent(_ type: Int.Type, forKey key: Key) throws -> Int? {
guard try self.contains(key) && !self.decodeNil(forKey: key) else { return nil }
guard self.matchesNumericType(type, forKey: key) else { return nil }
return try decodeNumeric(forKey: key)
}
func decodeIfPresent(_ type: Int8.Type, forKey key: Key) throws -> Int8? {
guard try self.contains(key) && !self.decodeNil(forKey: key) else { return nil }
guard self.matchesNumericType(type, forKey: key) else { return nil }
return try decodeNumeric(forKey: key)
}
func decodeIfPresent(_ type: Int16.Type, forKey key: Key) throws -> Int16? {
guard try self.contains(key) && !self.decodeNil(forKey: key) else { return nil }
guard self.matchesNumericType(type, forKey: key) else { return nil }
return try decodeNumeric(forKey: key)
}
func decodeIfPresent(_ type: Int32.Type, forKey key: Key) throws -> Int32? {
guard try self.contains(key) && !self.decodeNil(forKey: key) else { return nil }
guard self.matchesNumericType(type, forKey: key) else { return nil }
return try decodeNumeric(forKey: key)
}
func decodeIfPresent(_ type: Int64.Type, forKey key: Key) throws -> Int64? {
guard try self.contains(key) && !self.decodeNil(forKey: key) else { return nil }
guard self.matchesNumericType(type, forKey: key) else { return nil }
return try decodeNumeric(forKey: key)
}
func decodeIfPresent(_ type: UInt.Type, forKey key: Key) throws -> UInt? {
guard try self.contains(key) && !self.decodeNil(forKey: key) else { return nil }
guard self.matchesNumericType(type, forKey: key) else { return nil }
return try decodeNumeric(forKey: key)
}
func decodeIfPresent(_ type: UInt8.Type, forKey key: Key) throws -> UInt8? {
guard try self.contains(key) && !self.decodeNil(forKey: key) else { return nil }
guard self.matchesNumericType(type, forKey: key) else { return nil }
return try decodeNumeric(forKey: key)
}
func decodeIfPresent(_ type: UInt16.Type, forKey key: Key) throws -> UInt16? {
guard try self.contains(key) && !self.decodeNil(forKey: key) else { return nil }
guard self.matchesNumericType(type, forKey: key) else { return nil }
return try decodeNumeric(forKey: key)
}
func decodeIfPresent(_ type: UInt32.Type, forKey key: Key) throws -> UInt32? {
guard try self.contains(key) && !self.decodeNil(forKey: key) else { return nil }
guard self.matchesNumericType(type, forKey: key) else { return nil }
return try decodeNumeric(forKey: key)
}
func decodeIfPresent(_ type: UInt64.Type, forKey key: Key) throws -> UInt64? {
guard try self.contains(key) && !self.decodeNil(forKey: key) else { return nil }
guard self.matchesNumericType(type, forKey: key) else { return nil }
return try decodeNumeric(forKey: key)
}
func decodeIfPresent(_ type: Float.Type, forKey key: Key) throws -> Float? {
guard try self.contains(key) && !self.decodeNil(forKey: key) else { return nil }
guard self.matchesType(type, forKey: key) else { return nil }
return try decodeValue(forKey: key)
}
func decodeIfPresent(_ type: Double.Type, forKey key: Key) throws -> Double? {
guard try self.contains(key) && !self.decodeNil(forKey: key) else { return nil }
guard self.matchesType(type, forKey: key) else { return nil }
return try decodeValue(forKey: key)
}
func decodeIfPresent(_ type: String.Type, forKey key: Key) throws -> String? {
guard try self.contains(key) && !self.decodeNil(forKey: key) else { return nil }
guard self.matchesType(type, forKey: key) else { return nil }
return try decodeValue(forKey: key)
}
func decodeIfPresent<T: Decodable>(_ type: T.Type, forKey key: Key) throws -> T? {
guard try self.contains(key) && !self.decodeNil(forKey: key) else { return nil }
guard self.matchesType(type, forKey: key) else { return nil }
return try decodeValue(forKey: key)
}*/
}
fileprivate extension UnkeyedDecodingChildContainer {
mutating func decode(_ type: Bool.Type) throws -> Bool {
return try decodeValue()
}
mutating func decode(_ type: Int.Type) throws -> Int {
return try decodeNumeric()
}
mutating func decode(_ type: Int8.Type) throws -> Int8 {
return try decodeNumeric()
}
mutating func decode(_ type: Int16.Type) throws -> Int16 {
return try decodeNumeric()
}
mutating func decode(_ type: Int32.Type) throws -> Int32 {
return try decodeNumeric()
}
mutating func decode(_ type: Int64.Type) throws -> Int64 {
return try decodeNumeric()
}
mutating func decode(_ type: UInt.Type) throws -> UInt {
return try decodeNumeric()
}
mutating func decode(_ type: UInt8.Type) throws -> UInt8 {
return try decodeNumeric()
}
mutating func decode(_ type: UInt16.Type) throws -> UInt16 {
return try decodeNumeric()
}
mutating func decode(_ type: UInt32.Type) throws -> UInt32 {
return try decodeNumeric()
}
mutating func decode(_ type: UInt64.Type) throws -> UInt64 {
return try decodeNumeric()
}
mutating func decode(_ type: Float.Type) throws -> Float {
return try decodeValue()
}
mutating func decode(_ type: Double.Type) throws -> Double {
return try decodeValue()
}
mutating func decode(_ type: String.Type) throws -> String {
return try decodeValue()
}
//
//
//
/*
mutating func decodeIfPresent(_ type: Bool.Type) throws -> Bool? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
guard self.matchesType(type) else { return nil }
return try decodeValue()
}
mutating func decodeIfPresent(_ type: Int.Type) throws -> Int? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
guard self.matchesNumericType(type) else { return nil }
return try decodeValue()
}
mutating func decodeIfPresent(_ type: Int8.Type) throws -> Int8? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
guard self.matchesNumericType(type) else { return nil }
return try decodeValue()
}
mutating func decodeIfPresent(_ type: Int16.Type) throws -> Int16? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
guard self.matchesNumericType(type) else { return nil }
return try decodeValue()
}
mutating func decodeIfPresent(_ type: Int32.Type) throws -> Int32? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
guard self.matchesNumericType(type) else { return nil }
return try decodeValue()
}
mutating func decodeIfPresent(_ type: Int64.Type) throws -> Int64? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
guard self.matchesNumericType(type) else { return nil }
return try decodeValue()
}
mutating func decodeIfPresent(_ type: UInt.Type) throws -> UInt? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
guard self.matchesNumericType(type) else { return nil }
return try decodeValue()
}
mutating func decodeIfPresent(_ type: UInt8.Type) throws -> UInt8? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
guard self.matchesNumericType(type) else { return nil }
return try decodeValue()
}
mutating func decodeIfPresent(_ type: UInt16.Type) throws -> UInt16? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
guard self.matchesNumericType(type) else { return nil }
return try decodeValue()
}
mutating func decodeIfPresent(_ type: UInt32.Type) throws -> UInt32? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
guard self.matchesNumericType(type) else { return nil }
return try decodeValue()
}
mutating func decodeIfPresent(_ type: UInt64.Type) throws -> UInt64? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
guard self.matchesNumericType(type) else { return nil }
return try decodeValue()
}
mutating func decodeIfPresent(_ type: Float.Type) throws -> Float? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
guard self.matchesType(type) else { return nil }
return try decodeValue()
}
mutating func decodeIfPresent(_ type: Double.Type) throws -> Double? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
guard self.matchesType(type) else { return nil }
return try decodeValue()
}
mutating func decodeIfPresent(_ type: String.Type) throws -> String? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
guard self.matchesType(type) else { return nil }
return try decodeValue()
}
mutating func decodeIfPresent<T: Decodable>(_ type: T.Type) throws -> T? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
guard self.matchesType(type) else { return nil }
return try decodeValue()
}*/
}
fileprivate extension SingleValueDecodingChildContainer {
func decode(_ type: Bool.Type) throws -> Bool {
return try decodeValue()
}
func decode(_ type: Int.Type) throws -> Int {
return try decodeNumeric()
}
func decode(_ type: Int8.Type) throws -> Int8 {
return try decodeNumeric()
}
func decode(_ type: Int16.Type) throws -> Int16 {
return try decodeNumeric()
}
func decode(_ type: Int32.Type) throws -> Int32 {
return try decodeNumeric()
}
func decode(_ type: Int64.Type) throws -> Int64 {
return try decodeNumeric()
}
func decode(_ type: UInt.Type) throws -> UInt {
return try decodeNumeric()
}
func decode(_ type: UInt8.Type) throws -> UInt8 {
return try decodeNumeric()
}
func decode(_ type: UInt16.Type) throws -> UInt16 {
return try decodeNumeric()
}
func decode(_ type: UInt32.Type) throws -> UInt32 {
return try decodeNumeric()
}
func decode(_ type: UInt64.Type) throws -> UInt64 {
return try decodeNumeric()
}
func decode(_ type: Float.Type) throws -> Float {
return try decodeValue()
}
func decode(_ type: Double.Type) throws -> Double {
return try decodeValue()
}
func decode(_ type: String.Type) throws -> String {
return try decodeValue()
}
}
| mpl-2.0 | f709962e33b8b8d9eae17d761d37eed4 | 42.306277 | 160 | 0.5987 | 4.825736 | false | false | false | false |
4np/UitzendingGemist | UitzendingGemist/OnDeckCollectionViewCell.swift | 1 | 2043 | //
// OnDeckCollectionViewCell.swift
// UitzendingGemist
//
// Created by Jeroen Wesbeek on 16/08/16.
// Copyright © 2016 Jeroen Wesbeek. All rights reserved.
//
import Foundation
import UIKit
import NPOKit
import CocoaLumberjack
class OnDeckCollectionViewCell: UICollectionViewCell {
@IBOutlet weak fileprivate var imageView: UIImageView!
@IBOutlet weak fileprivate var programNameLabel: UILabel!
@IBOutlet weak fileprivate var episodeNameLabel: UILabel!
@IBOutlet weak fileprivate var dateLabel: UILabel!
// MARK: Lifecycle
override func layoutSubviews() {
super.layoutSubviews()
}
override func prepareForReuse() {
super.prepareForReuse()
self.imageView.image = nil
self.programNameLabel.text = nil
self.episodeNameLabel.text = nil
self.dateLabel.text = nil
}
// MARK: Focus engine
override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {
self.imageView.adjustsImageWhenAncestorFocused = self.isFocused
}
// MARK: Configuration
internal func configure(withProgram program: NPOProgram, unWachtedEpisodeCount unwatchedCount: Int, andEpisode episode: NPOEpisode) {
self.programNameLabel.text = program.getDisplayNameWithFavoriteIndicator()
self.programNameLabel.textColor = program.getDisplayColor()
self.episodeNameLabel.text = episode.getDisplayName()
self.dateLabel.text = episode.broadcastedDisplayValue
// Somehow in tvOS 10 / Xcode 8 / Swift 3 the frame will initially be 1000x1000
// causing the images to look compressed so hardcode the dimensions for now...
// TODO: check if this is solved in later releases...
//let size = self.imageView.frame.size
let size = CGSize(width: 375, height: 211)
_ = episode.getImage(ofSize: size) { [weak self] image, _, _ in
self?.imageView.image = image
}
}
}
| apache-2.0 | 2a0ab81ac8e60b735ab6dbc21e52c9e1 | 33.610169 | 137 | 0.686582 | 4.920482 | false | false | false | false |
rmavani/SocialQP | QPrint/Controllers/MyProfile/ChangePasswordViewController.swift | 1 | 2804 | //
// ChangePasswordViewController.swift
// QPrint
//
// Created by Admin on 27/02/17.
// Copyright © 2017 Admin. All rights reserved.
//
import UIKit
protocol ChangePasswordDelegate : class {
func hideSavePasswordPopup(controller:ChangePasswordViewController)
func hideCancelPasswordPopup()
}
class ChangePasswordViewController: UIViewController {
// MARK: - Initialize IBOutlets
@IBOutlet var txtOldPassword : UITextField!
@IBOutlet var txtNewPassword : UITextField!
@IBOutlet var txtConfirmPassword : UITextField!
@IBOutlet var btnSave : UIButton!
@IBOutlet var btnCancel : UIButton!
// MARK: - Initialize Variables
weak var delegate : ChangePasswordDelegate?
// MARK: - Initialize
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.isHidden = true
self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false
}
// MARK: - UIButton Click Events
@IBAction func btn_SaveClick(_ sender: UIButton) {
self.view.endEditing(true)
if ((txtOldPassword.text?.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)) == "") {
AppUtilities.sharedInstance.showAlert(title: App_Title as NSString, msg: "Please Enter Valid Old Password.")
return
}
if ((txtNewPassword.text?.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)) == "") {
AppUtilities.sharedInstance.showAlert(title: App_Title as NSString, msg: "Please Enter Valid New Password.")
return
}
if ((txtConfirmPassword.text?.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)) == "") {
AppUtilities.sharedInstance.showAlert(title: App_Title as NSString, msg: "Please Enter Valid Confirm Password.")
return
}
if ((txtNewPassword.text?.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)) != (txtConfirmPassword.text?.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines))) {
AppUtilities.sharedInstance.showAlert(title: App_Title as NSString, msg: "Password not mathched.")
return
}
delegate?.hideSavePasswordPopup(controller: self)
// self.dismissPopupViewController(animationType: SLpopupViewAnimationType.BottomBottom)
delegate?.hideCancelPasswordPopup()
}
@IBAction func btn_CancelClick(_ sender: UIButton) {
self.view.endEditing(true)
delegate?.hideCancelPasswordPopup()
}
// MARK: - Other Methods
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 1768a3b666a2b9a7268c10e48004d9db | 34.935897 | 187 | 0.676418 | 5.308712 | false | false | false | false |
mrdepth/EVEUniverse | Neocom/Neocom/Database/TypeInfo/NPCInfo.swift | 2 | 12383 | //
// NPCInfo.swift
// Neocom
//
// Created by Artem Shimanski on 12/31/19.
// Copyright © 2019 Artem Shimanski. All rights reserved.
//
import SwiftUI
import Expressible
import Dgmpp
struct NPCInfo: View {
var type: SDEInvType
private var attributes: FetchedResultsController<SDEDgmTypeAttribute> {
let controller = managedObjectContext.from(SDEDgmTypeAttribute.self)
.filter(/\SDEDgmTypeAttribute.type == type && /\SDEDgmTypeAttribute.attributeType?.published == true)
.sort(by: \SDEDgmTypeAttribute.attributeType?.attributeCategory?.categoryID, ascending: true)
.sort(by: \SDEDgmTypeAttribute.attributeType?.attributeID, ascending: true)
.fetchedResultsController(sectionName: /\SDEDgmTypeAttribute.attributeType?.attributeCategory?.categoryID, cacheName: nil)
return FetchedResultsController(controller)
}
private func section(for section: FetchedResultsController<SDEDgmTypeAttribute>.Section) -> some View {
let attributeCategory = section.objects.first?.attributeType?.attributeCategory
let categoryID = attributeCategory.flatMap{SDEAttributeCategoryID(rawValue: $0.categoryID)}
let sectionTitle: String = categoryID == .null ? NSLocalizedString("Other", comment: "") : attributeCategory?.categoryName ?? NSLocalizedString("Other", comment: "")
func turrets() -> some View {
func row(speed: Double) -> some View {
let damageMultiplier = type[SDEAttributeID.damageMultiplier]?.value ?? 1
let maxRange = type[SDEAttributeID.maxRange]?.value ?? 0
let falloff = type[SDEAttributeID.falloff]?.value ?? 0
let duration: Double = speed / 1000
let em = type[SDEAttributeID.emDamage]?.value ?? 0
let explosive = type[SDEAttributeID.explosiveDamage]?.value ?? 0
let kinetic = type[SDEAttributeID.kineticDamage]?.value ?? 0
let thermal = type[SDEAttributeID.thermalDamage]?.value ?? 0
let total = (em + explosive + kinetic + thermal) * damageMultiplier
let interval = duration > 0 ? duration : 1
let dps = total / interval
return Group {
DamageVectorView(damage: DGMDamageVector(em: em * damageMultiplier,
thermal: thermal * damageMultiplier,
kinetic: kinetic * damageMultiplier,
explosive: explosive * damageMultiplier), percentStyle: false)
TypeInfoAttributeCell(title: Text("Damage per Second"),
subtitle: Text(UnitFormatter.localizedString(from: dps, unit: .none, style: .long)),
image: Image("turrets"))
TypeInfoAttributeCell(title: Text("Rate of Fire"),
subtitle: Text(TimeIntervalFormatter.localizedString(from: TimeInterval(duration), precision: .seconds)),
image: Image("rateOfFire"))
TypeInfoAttributeCell(title: Text("Optimal Range"),
subtitle: Text(UnitFormatter.localizedString(from: maxRange, unit: .meter, style: .long)),
image: Image("targetingRange"))
TypeInfoAttributeCell(title: Text("Falloff"),
subtitle: Text(UnitFormatter.localizedString(from: falloff, unit: .meter, style: .long)),
image: Image("falloff"))
}
}
return type[SDEAttributeID.speed].map{row(speed: $0.value)}
}
func missiles() -> some View {
func row(missile: SDEInvType) -> some View {
let duration: Double = (type[SDEAttributeID.missileLaunchDuration]?.value ?? 1000) / 1000
let damageMultiplier = type[SDEAttributeID.missileDamageMultiplier]?.value ?? 1
let velocityMultiplier = type[SDEAttributeID.missileEntityVelocityMultiplier]?.value ?? 1
let flightTimeMultiplier = type[SDEAttributeID.missileEntityFlightTimeMultiplier]?.value ?? 1
let em = missile[SDEAttributeID.emDamage]?.value ?? 0
let explosive = missile[SDEAttributeID.explosiveDamage]?.value ?? 0
let kinetic = missile[SDEAttributeID.kineticDamage]?.value ?? 0
let thermal = missile[SDEAttributeID.thermalDamage]?.value ?? 0
let total = (em + explosive + kinetic + thermal) * damageMultiplier
let velocity: Double = (missile[SDEAttributeID.maxVelocity]?.value ?? 0) * velocityMultiplier
let flightTime: Double = (missile[SDEAttributeID.explosionDelay]?.value ?? 1) * flightTimeMultiplier / 1000
let agility: Double = missile[SDEAttributeID.agility]?.value ?? 0
let mass = missile.mass
let accelTime = min(flightTime, mass * agility / 1000000.0)
let duringAcceleration = velocity / 2 * accelTime
let fullSpeed = velocity * (flightTime - accelTime)
let maxRange = duringAcceleration + fullSpeed;
let interval = duration > 0 ? duration : 1
let dps = total / interval
return Group {
NavigationLink(destination: TypeInfo(type: missile)) {
TypeInfoAttributeCell(title: Text("Missile"),
subtitle: Text(missile.typeName ?? ""),
image: missile.image,
targetType: missile)
}
DamageVectorView(damage: DGMDamageVector(em: em * damageMultiplier,
thermal: thermal * damageMultiplier,
kinetic: kinetic * damageMultiplier,
explosive: explosive * damageMultiplier), percentStyle: false)
TypeInfoAttributeCell(title: Text("Damage per Second"),
subtitle: Text(UnitFormatter.localizedString(from: dps, unit: .none, style: .long)),
image: Image("turrets"))
TypeInfoAttributeCell(title: Text("Rate of Fire"),
subtitle: Text(TimeIntervalFormatter.localizedString(from: TimeInterval(duration), precision: .seconds)),
image: Image("rateOfFire"))
TypeInfoAttributeCell(title: Text("Optimal Range"),
subtitle: Text(UnitFormatter.localizedString(from: maxRange, unit: .meter, style: .long)),
image: Image("targetingRange"))
}
}
let attribute = type[SDEAttributeID.entityMissileTypeID].map{Int32($0.value)}
let missile = attribute.flatMap{attribute in try? managedObjectContext.from(SDEInvType.self).filter(/\SDEInvType.typeID == attribute).first()}
return missile.map{row(missile: $0)}
}
func shield() -> some View {
func capacity() -> String? {
guard let capacity = type[SDEAttributeID.shieldCapacity]?.value,
let rechargeRate = type[SDEAttributeID.shieldRechargeRate]?.value,
rechargeRate > 0 && capacity > 0 else {return nil}
let passive = 10.0 / (rechargeRate / 1000.0) * 0.5 * (1 - 0.5) * capacity
return UnitFormatter.localizedString(from: passive, unit: .hpPerSecond, style: .long)
}
func repair() -> String? {
guard let amount = type[SDEAttributeID.entityShieldBoostAmount]?.value,
let duration = type[SDEAttributeID.entityShieldBoostDuration]?.value,
duration > 0 && amount > 0 else {return nil}
let chance = (type[SDEAttributeID.entityShieldBoostDelayChance] ??
type[SDEAttributeID.entityShieldBoostDelayChanceSmall] ??
type[SDEAttributeID.entityShieldBoostDelayChanceMedium] ??
type[SDEAttributeID.entityShieldBoostDelayChanceLarge])?.value ?? 0
let repair = amount / (duration * (1 + chance) / 1000.0)
return UnitFormatter.localizedString(from: repair, unit: .hpPerSecond, style: .long)
}
return Group {
capacity().map{
TypeInfoAttributeCell(title: Text("Passive Recharge Rate"),
subtitle: Text($0),
image: Image("shieldRecharge"))
}
repair().map{
TypeInfoAttributeCell(title: Text("Repair Rate"),
subtitle: Text($0),
image: Image("shieldBooster"))
}
}
}
func armor() -> some View {
func repair() -> String? {
guard let amount = type[SDEAttributeID.entityArmorRepairAmount]?.value,
let duration = type[SDEAttributeID.entityArmorRepairDuration]?.value,
duration > 0 && amount > 0 else {return nil}
let chance = (type[SDEAttributeID.entityArmorRepairDelayChance] ??
type[SDEAttributeID.entityArmorRepairDelayChanceSmall] ??
type[SDEAttributeID.entityArmorRepairDelayChanceMedium] ??
type[SDEAttributeID.entityArmorRepairDelayChanceLarge])?.value ?? 0
let repair = amount / (duration * (1 + chance) / 1000.0)
return UnitFormatter.localizedString(from: repair, unit: .hpPerSecond, style: .long)
}
return repair().map{
TypeInfoAttributeCell(title: Text("Repair Rate"),
subtitle: Text($0),
image: Image("armorRepairer"))
}
}
return Section(header: Text(sectionTitle.uppercased())) {
if categoryID == .turrets {
turrets()
}
else if categoryID == .missile {
missiles()
}
else {
ForEach(section.objects, id: \.objectID) { attribute in
AttributeInfo(attribute: attribute, attributeValues: nil)
}
if categoryID == .shield {
shield()
}
else if categoryID == .armor {
armor()
}
}
}
}
@Environment(\.managedObjectContext) var managedObjectContext
var body: some View {
var sections = attributes.sections
_ = sections.partition{$0.objects.first?.attributeType?.attributeCategory?.categoryID != SDEAttributeCategoryID.entityRewards.rawValue}
return ForEach(sections, id: \.name) { section in
self.section(for: section)
}
}
}
#if DEBUG
struct NPCInfo_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
List {
NPCInfo(type: try! Storage.testStorage.persistentContainer.viewContext
.from(SDEInvType.self)
.filter((/\SDEInvType.group?.npcGroups).count > 0)
.first()!)
}.listStyle(GroupedListStyle())
}.modifier(ServicesViewModifier.testModifier())
}
}
#endif
| lgpl-2.1 | 1af29d158997de4710b8453236b61c58 | 51.91453 | 173 | 0.530124 | 6.078547 | false | false | false | false |
iosdevvivek/MarkupKit | MarkupKitDemos/CustomCellViewController.swift | 2 | 3178 | //
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
class CustomCellViewController: UITableViewController {
var pharmacies: NSArray!
override func viewDidLoad() {
super.viewDidLoad()
title = "Custom Cell View"
// Configure table view
tableView.registerClass(PharmacyCell.self, forCellReuseIdentifier: PharmacyCell.self.description())
tableView.estimatedRowHeight = 2
// Load pharmacy list from JSON
let path = NSBundle.mainBundle().pathForResource("pharmacies", ofType: "json")
let data = NSData(contentsOfFile: path!)
pharmacies = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.allZeros, error: nil) as! [[String: AnyObject]]
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return pharmacies.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// Get pharmacy data
var index = indexPath.row
var pharmacy = pharmacies.objectAtIndex(index) as! [String: AnyObject]
// Configure cell with pharmacy data
let cell = tableView.dequeueReusableCellWithIdentifier(PharmacyCell.self.description()) as! PharmacyCell
cell.nameLabel.text = String(format: "%d. %@", index + 1, pharmacy["name"] as! String)
cell.distanceLabel.text = String(format: "%.2f miles", pharmacy["distance"] as! Double)
cell.addressLabel.text = String(format: "%@\n%@ %@ %@",
pharmacy["address1"] as! String,
pharmacy["city"] as! String, pharmacy["state"] as! String,
pharmacy["zipCode"] as! String)
let phoneNumberFormatter = PhoneNumberFormatter()
let phone = pharmacy["phone"] as? NSString
cell.phoneLabel.text = (phone == nil) ? nil : phoneNumberFormatter.stringForObjectValue(phone!)
let fax = pharmacy["fax"] as? NSString
cell.faxLabel.text = (fax == nil) ? nil : phoneNumberFormatter.stringForObjectValue(fax!)
cell.emailLabel.text = pharmacy["email"] as? String
return cell
}
}
class PhoneNumberFormatter: NSFormatter {
override func stringForObjectValue(obj: AnyObject) -> String? {
var val = obj as! NSString
return String(format:"(%@) %@-%@",
val.substringWithRange(NSMakeRange(0, 3)),
val.substringWithRange(NSMakeRange(3, 3)),
val.substringWithRange(NSMakeRange(6, 4))
)
}
}
| apache-2.0 | 3dceb314449ecc414b5f64a3fe717ac2 | 36.833333 | 144 | 0.674638 | 4.736215 | false | false | false | false |
jum/Charts | Source/Charts/Renderers/YAxisRendererHorizontalBarChart.swift | 4 | 12288 | //
// YAxisRendererHorizontalBarChart.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
open class YAxisRendererHorizontalBarChart: YAxisRenderer
{
public override init(viewPortHandler: ViewPortHandler, yAxis: YAxis?, transformer: Transformer?)
{
super.init(viewPortHandler: viewPortHandler, yAxis: yAxis, transformer: transformer)
}
/// Computes the axis values.
open override func computeAxis(min: Double, max: Double, inverted: Bool)
{
guard let transformer = self.transformer else { return }
var min = min, max = max
// calculate the starting and entry point of the y-labels (depending on zoom / contentrect bounds)
if viewPortHandler.contentHeight > 10.0 && !viewPortHandler.isFullyZoomedOutX
{
let p1 = transformer.valueForTouchPoint(CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop))
let p2 = transformer.valueForTouchPoint(CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentTop))
if !inverted
{
min = Double(p1.x)
max = Double(p2.x)
}
else
{
min = Double(p2.x)
max = Double(p1.x)
}
}
computeAxisValues(min: min, max: max)
}
/// draws the y-axis labels to the screen
open override func renderAxisLabels(context: CGContext)
{
guard let yAxis = axis as? YAxis else { return }
if !yAxis.isEnabled || !yAxis.isDrawLabelsEnabled
{
return
}
let lineHeight = yAxis.labelFont.lineHeight
let baseYOffset: CGFloat = 2.5
let dependency = yAxis.axisDependency
let labelPosition = yAxis.labelPosition
var yPos: CGFloat = 0.0
if dependency == .left
{
if labelPosition == .outsideChart
{
yPos = viewPortHandler.contentTop - baseYOffset
}
else
{
yPos = viewPortHandler.contentTop - baseYOffset
}
}
else
{
if labelPosition == .outsideChart
{
yPos = viewPortHandler.contentBottom + lineHeight + baseYOffset
}
else
{
yPos = viewPortHandler.contentBottom + lineHeight + baseYOffset
}
}
// For compatibility with Android code, we keep above calculation the same,
// And here we pull the line back up
yPos -= lineHeight
drawYLabels(
context: context,
fixedPosition: yPos,
positions: transformedPositions(),
offset: yAxis.yOffset)
}
open override func renderAxisLine(context: CGContext)
{
guard let yAxis = axis as? YAxis else { return }
if !yAxis.isEnabled || !yAxis.drawAxisLineEnabled
{
return
}
context.saveGState()
context.setStrokeColor(yAxis.axisLineColor.cgColor)
context.setLineWidth(yAxis.axisLineWidth)
if yAxis.axisLineDashLengths != nil
{
context.setLineDash(phase: yAxis.axisLineDashPhase, lengths: yAxis.axisLineDashLengths)
}
else
{
context.setLineDash(phase: 0.0, lengths: [])
}
if yAxis.axisDependency == .left
{
context.beginPath()
context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop))
context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentTop))
context.strokePath()
}
else
{
context.beginPath()
context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom))
context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentBottom))
context.strokePath() }
context.restoreGState()
}
/// draws the y-labels on the specified x-position
@objc open func drawYLabels(
context: CGContext,
fixedPosition: CGFloat,
positions: [CGPoint],
offset: CGFloat)
{
guard let
yAxis = axis as? YAxis
else { return }
let labelFont = yAxis.labelFont
let labelTextColor = yAxis.labelTextColor
let from = yAxis.isDrawBottomYLabelEntryEnabled ? 0 : 1
let to = yAxis.isDrawTopYLabelEntryEnabled ? yAxis.entryCount : (yAxis.entryCount - 1)
for i in stride(from: from, to: to, by: 1)
{
let text = yAxis.getFormattedLabel(i)
ChartUtils.drawText(
context: context,
text: text,
point: CGPoint(x: positions[i].x, y: fixedPosition - offset),
align: .center,
attributes: [NSAttributedString.Key.font: labelFont, NSAttributedString.Key.foregroundColor: labelTextColor])
}
}
open override var gridClippingRect: CGRect
{
var contentRect = viewPortHandler.contentRect
let dx = self.axis?.gridLineWidth ?? 0.0
contentRect.origin.x -= dx / 2.0
contentRect.size.width += dx
return contentRect
}
open override func drawGridLine(
context: CGContext,
position: CGPoint)
{
context.beginPath()
context.move(to: CGPoint(x: position.x, y: viewPortHandler.contentTop))
context.addLine(to: CGPoint(x: position.x, y: viewPortHandler.contentBottom))
context.strokePath()
}
open override func transformedPositions() -> [CGPoint]
{
guard
let yAxis = self.axis as? YAxis,
let transformer = self.transformer
else { return [CGPoint]() }
var positions = [CGPoint]()
positions.reserveCapacity(yAxis.entryCount)
let entries = yAxis.entries
for i in stride(from: 0, to: yAxis.entryCount, by: 1)
{
positions.append(CGPoint(x: entries[i], y: 0.0))
}
transformer.pointValuesToPixel(&positions)
return positions
}
/// Draws the zero line at the specified position.
open override func drawZeroLine(context: CGContext)
{
guard
let yAxis = self.axis as? YAxis,
let transformer = self.transformer,
let zeroLineColor = yAxis.zeroLineColor
else { return }
context.saveGState()
defer { context.restoreGState() }
var clippingRect = viewPortHandler.contentRect
clippingRect.origin.x -= yAxis.zeroLineWidth / 2.0
clippingRect.size.width += yAxis.zeroLineWidth
context.clip(to: clippingRect)
context.setStrokeColor(zeroLineColor.cgColor)
context.setLineWidth(yAxis.zeroLineWidth)
let pos = transformer.pixelForValues(x: 0.0, y: 0.0)
if yAxis.zeroLineDashLengths != nil
{
context.setLineDash(phase: yAxis.zeroLineDashPhase, lengths: yAxis.zeroLineDashLengths!)
}
else
{
context.setLineDash(phase: 0.0, lengths: [])
}
context.move(to: CGPoint(x: pos.x - 1.0, y: viewPortHandler.contentTop))
context.addLine(to: CGPoint(x: pos.x - 1.0, y: viewPortHandler.contentBottom))
context.drawPath(using: CGPathDrawingMode.stroke)
}
private var _limitLineSegmentsBuffer = [CGPoint](repeating: CGPoint(), count: 2)
open override func renderLimitLines(context: CGContext)
{
guard
let yAxis = axis as? YAxis,
let transformer = self.transformer
else { return }
var limitLines = yAxis.limitLines
if limitLines.count <= 0
{
return
}
context.saveGState()
let trans = transformer.valueToPixelMatrix
var position = CGPoint(x: 0.0, y: 0.0)
for i in 0 ..< limitLines.count
{
let l = limitLines[i]
if !l.isEnabled
{
continue
}
context.saveGState()
defer { context.restoreGState() }
var clippingRect = viewPortHandler.contentRect
clippingRect.origin.x -= l.lineWidth / 2.0
clippingRect.size.width += l.lineWidth
context.clip(to: clippingRect)
position.x = CGFloat(l.limit)
position.y = 0.0
position = position.applying(trans)
context.beginPath()
context.move(to: CGPoint(x: position.x, y: viewPortHandler.contentTop))
context.addLine(to: CGPoint(x: position.x, y: viewPortHandler.contentBottom))
context.setStrokeColor(l.lineColor.cgColor)
context.setLineWidth(l.lineWidth)
if l.lineDashLengths != nil
{
context.setLineDash(phase: l.lineDashPhase, lengths: l.lineDashLengths!)
}
else
{
context.setLineDash(phase: 0.0, lengths: [])
}
context.strokePath()
let label = l.label
// if drawing the limit-value label is enabled
if l.drawLabelEnabled && label.count > 0
{
let labelLineHeight = l.valueFont.lineHeight
let xOffset: CGFloat = l.lineWidth + l.xOffset
let yOffset: CGFloat = 2.0 + l.yOffset
if l.labelPosition == .topRight
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: position.x + xOffset,
y: viewPortHandler.contentTop + yOffset),
align: .left,
attributes: [NSAttributedString.Key.font: l.valueFont, NSAttributedString.Key.foregroundColor: l.valueTextColor])
}
else if l.labelPosition == .bottomRight
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: position.x + xOffset,
y: viewPortHandler.contentBottom - labelLineHeight - yOffset),
align: .left,
attributes: [NSAttributedString.Key.font: l.valueFont, NSAttributedString.Key.foregroundColor: l.valueTextColor])
}
else if l.labelPosition == .topLeft
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: position.x - xOffset,
y: viewPortHandler.contentTop + yOffset),
align: .right,
attributes: [NSAttributedString.Key.font: l.valueFont, NSAttributedString.Key.foregroundColor: l.valueTextColor])
}
else
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: position.x - xOffset,
y: viewPortHandler.contentBottom - labelLineHeight - yOffset),
align: .right,
attributes: [NSAttributedString.Key.font: l.valueFont, NSAttributedString.Key.foregroundColor: l.valueTextColor])
}
}
}
context.restoreGState()
}
}
| apache-2.0 | 9134acac9ca86a952abf43fb9d79c570 | 32.85124 | 137 | 0.541341 | 5.488164 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/UserInterface/Conversation/Content/Cells/MessageAction.swift | 1 | 7047 | //
// Wire
// Copyright (C) 2019 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import WireCommonComponents
import UIKit
enum MessageAction: CaseIterable {
case
digitallySign,
copy,
reply,
openDetails,
edit,
delete,
save,
cancel,
download,
forward,
like,
unlike,
resend,
showInConversation,
sketchDraw,
sketchEmoji,
// Not included in ConversationMessageActionController.allMessageActions, for image viewer/open quote
present,
openQuote,
resetSession
var title: String? {
let key: String?
switch self {
case .copy:
key = "content.message.copy"
case .digitallySign:
key = "content.message.sign"
case .reply:
key = "content.message.reply"
case .openDetails:
key = "content.message.details"
case .edit:
key = "message.menu.edit.title"
case .delete:
key = "content.message.delete"
case .save:
key = "content.message.save"
case .cancel:
key = "general.cancel"
case .download:
key = "content.message.download"
case .forward:
key = "content.message.forward"
case .like:
key = "content.message.like"
case .unlike:
key = "content.message.unlike"
case .resend:
key = "content.message.resend"
case .showInConversation:
key = "content.message.go_to_conversation"
case .sketchDraw:
key = "image.add_sketch"
case .sketchEmoji:
key = "image.add_emoji"
case .present,
.openQuote,
.resetSession:
key = nil
}
return key?.localized
}
var icon: StyleKitIcon? {
switch self {
case .copy:
return .copy
case .reply:
return .reply
case .openDetails:
return .about
case .edit:
return .pencil
case .delete:
return .trash
case .save:
return .save
case .cancel:
return .cross
case .download:
return .downArrow
case .forward:
return .export
case .like:
return .liked
case .unlike:
return .like
case .resend:
return .redo
case .showInConversation:
return .eye
case .sketchDraw:
return .brush
case .sketchEmoji:
return .emoji
case .present,
.openQuote,
.digitallySign,
.resetSession:
return nil
}
}
func systemIcon() -> UIImage? {
return imageSystemName().flatMap(UIImage.init(systemName:))
}
private func imageSystemName() -> String? {
let imageName: String?
switch self {
case .copy:
imageName = "doc.on.doc"
case .reply:
imageName = "arrow.uturn.left"
case .openDetails:
imageName = "info.circle"
case .edit:
imageName = "pencil"
case .delete:
imageName = "trash"
case .save:
imageName = "arrow.down.to.line"
case .cancel:
imageName = "xmark"
case .download:
imageName = "chevron.down"
case .forward:
imageName = "square.and.arrow.up"
case .like:
imageName = "suit.heart"
case .unlike:
imageName = "suit.heart.fill"
case .resend:
imageName = "arrow.clockwise"
case .showInConversation:
imageName = "eye.fill"
case .sketchDraw:
imageName = "scribble"
case .sketchEmoji:
imageName = "smiley.fill"
case .present,
.openQuote,
.digitallySign,
.resetSession:
imageName = nil
}
return imageName
}
var selector: Selector? {
switch self {
case .copy:
return #selector(ConversationMessageActionController.copyMessage)
case .digitallySign:
return #selector(ConversationMessageActionController.digitallySignMessage)
case .reply:
return #selector(ConversationMessageActionController.quoteMessage)
case .openDetails:
return #selector(ConversationMessageActionController.openMessageDetails)
case .edit:
return #selector(ConversationMessageActionController.editMessage)
case .delete:
return #selector(ConversationMessageActionController.deleteMessage)
case .save:
return #selector(ConversationMessageActionController.saveMessage)
case .cancel:
return #selector(ConversationMessageActionController.cancelDownloadingMessage)
case .download:
return #selector(ConversationMessageActionController.downloadMessage)
case .forward:
return #selector(ConversationMessageActionController.forwardMessage)
case .like:
return #selector(ConversationMessageActionController.likeMessage)
case .unlike:
return #selector(ConversationMessageActionController.unlikeMessage)
case .resend:
return #selector(ConversationMessageActionController.resendMessage)
case .showInConversation:
return #selector(ConversationMessageActionController.revealMessage)
case .present,
.sketchDraw,
.sketchEmoji,
.openQuote,
.resetSession:
// no message related actions are not handled in ConversationMessageActionController
return nil
}
}
var accessibilityLabel: String? {
switch self {
case .copy:
return "copy"
case .save:
return "save"
case .sketchDraw:
return "sketch over image"
case .sketchEmoji:
return "sketch emoji over image"
case .showInConversation:
return "reveal in conversation"
case .delete:
return "delete"
case .unlike:
return "unlike"
case .like:
return "like"
default:
return nil
}
}
}
| gpl-3.0 | c37035709229fe48f4c70c392b7984ab | 28.3625 | 105 | 0.572158 | 5.091763 | false | false | false | false |
emericspiroux/Open42 | correct42/Controllers/WebViewController.swift | 1 | 1573 | //
// WebViewController.swift
// Open42
//
// Created by larry on 03/09/2016.
// Copyright © 2016 42. All rights reserved.
//
import UIKit
class WebViewController: UIViewController, UIWebViewDelegate {
// MARK: - IBOutlets
/// Webview
@IBOutlet weak var webView: UIWebView!
/// Progress Bar View
@IBOutlet weak var progressBarView: UIView!
/// Progress Bar
@IBOutlet weak var progressBar: UIProgressView!
/// Localized label to waiting for downloading.
@IBOutlet weak var downloadingMessage: UILabel!
// MARK: - Proprieties
/// Url of the ressource
var urlPathOpt:NSURL?
// MARK: - View life cycle
/// Delegate `webView`
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
webView.delegate = self
}
/// Set `webView` alpha to 0.0 and `progressBarView` alpha to 1.0, set the downloading text and load url.
override func viewWillAppear(animated: Bool) {
webView.alpha = 0.0
progressBarView.alpha = 1.0
downloadingMessage.text = NSLocalizedString("downloadingFile", comment: "")
reloadView()
}
/// Use to refresh or load a page.
private func reloadView(){
if let urlPath = urlPathOpt {
let request = NSURLRequest(URL: urlPath)
webView.loadRequest(request)
}
}
// MARK: - UIWebView delegation
/// Set `webView` alpha to 1.0 and `progressBarView` alpha to 0.0 when webview did finish load
func webViewDidFinishLoad(webView: UIWebView) {
UIView.animateWithDuration(0.5) {
self.webView.alpha = 1.0
self.progressBarView.alpha = 0.0
}
}
}
| apache-2.0 | 30b17e55e9278fea8eb4af0657c726b4 | 26.103448 | 106 | 0.704835 | 3.725118 | false | false | false | false |
primetimer/PrimeFactors | Example/PrimeFactors/AsyncCalc.swift | 1 | 1863 | //
// AsyncCalc.swift
// PFactors_Example
//
// Created by Stephan Jancar on 22.10.17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import Foundation
import BigInt
import PrimeFactors
protocol ProtShowResult {
func ShowCalcResult()
}
class AsyncCalc: Operation, CalcCancelProt {
func IsCancelled() -> Bool {
return isCancelled
}
private var type : CalcType!
private var rpn : RPNCalc!
var resultdelegate : ProtShowResult? = nil
override var isAsynchronous: Bool {
get{
return true
}
}
private var _executing: Bool = false
override var isExecuting:Bool {
get { return _executing }
set {
willChangeValue(forKey: "isExecuting")
_executing = newValue
didChangeValue(forKey: "isExecuting")
if _cancelled == true {
self.isFinished = true
}
}
}
private var _finished: Bool = false
override var isFinished:Bool {
get { return _finished }
set {
willChangeValue(forKey: "isFinished")
_finished = newValue
didChangeValue(forKey: "isFinished")
}
}
private var _cancelled: Bool = false
override var isCancelled: Bool {
get { return _cancelled }
set {
willChangeValue(forKey: "isCancelled")
_cancelled = newValue
didChangeValue(forKey: "isCancelled")
}
}
init(rpn: RPNCalc, type : CalcType) {
self.rpn = rpn
self.type = type
}
override func start() {
super.start()
self.isExecuting = true
rpn.canceldelegate = self
rpn.Calculation(type: self.type)
if !isCancelled {
OperationQueue.main.addOperation {
self.resultdelegate?.ShowCalcResult()
}
} else {
print("was cancelled")
}
}
override func cancel() {
super.cancel()
isCancelled = true
if isExecuting {
isExecuting = false
isFinished = true
}
}
override func main() {
if isCancelled {
self.isExecuting = false
self.isFinished = true
return
}
}
}
| mit | 8425474f153afbf8f7baeadc53d5f444 | 17.808081 | 52 | 0.67884 | 3.39781 | false | false | false | false |
CGRrui/TestKitchen_1606 | TestKitchen/TestKitchen/classes/cookbook/recommend/view/CBHeaderView.swift | 1 | 1719 | //
// CBHeaderView.swift
// TestKitchen
//
// Created by Rui on 16/8/19.
// Copyright © 2016年 Rui. All rights reserved.
//
import UIKit
//灰色的背景视图和今日新品的显示(今日新品根据json传过来的数据会改变的)
class CBHeaderView: UIView {
//标题
private var titleLabel: UILabel?
//图片
private var imageView: UIImageView?
override init(frame: CGRect) {
super.init(frame: frame)
//背景视图
let bgView = UIView.createView()
bgView.frame = CGRectMake(0, 10, bounds.size.width, bounds.size.height-10)
bgView.backgroundColor = UIColor.whiteColor()
addSubview(bgView)
let titleW: CGFloat = 160
let imageW: CGFloat = 24
let x = (bounds.size.width-titleW-imageW)/2
//标题文字
titleLabel = UILabel.createLabel(nil, font: UIFont.systemFontOfSize(18), textAlignment: .Center, textColor: UIColor.blackColor())
titleLabel?.frame = CGRectMake(x, 10, titleW, bounds.size.height-10)
addSubview(titleLabel!)
//右边的图片
imageView = UIImageView.createImageView("more_icon")
imageView?.frame = CGRectMake(x+titleW, 14, imageW, imageW)
addSubview(imageView!)
//灰色
backgroundColor = UIColor(white: 0.8, alpha: 1.0)
}
//显示标题(会变化)
func configTitle(title: String) {
titleLabel?.text = title
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 6ba77bb47ca841da7f00c874bdfbfb06 | 11.919355 | 137 | 0.571785 | 4.318059 | false | false | false | false |
PatrickChow/Swift-Awsome | News/Mediator/Mediator.swift | 1 | 6789 | //
// Created by Patrick Chow on 2017/4/22.
// Copyright (c) 2017 Jiemian Technology. All rights reserved.
import UIKit
enum ModuleNavigator {
/// URL scheme
///
enum ModuleViewControllerURLScheme {
case viewController(scheme: String)
case alert(scheme: String, title: String, description: String)
case provider(title: String,token: API)
}
/// 调用新闻相关模块视图的方案
/// - channel
enum HomeGroupModuleNavigator {
case main
case channel(uniString: String)
}
/// 调用试听相关模块视图的方案
/// - videoChannel 视频列表
/// - video 视频详情
/// - audioChannel 音频列表
/// - audio 音频详情
enum MediaGroupModuleNavigator {
case main
case videoChannel(uniString: String)
case video(id: String)
case audioChannel(uniString: String)
case audio(id: String)
}
enum CommunityGroupModuleNavigator {
case main
case wozai
case viewController(scheme: String)
}
/// 调用我和设置相关模块视图的方案
/// - setting 设置
/// - integralMall 面点商城页面
/// - favorite 我收藏的精华
/// - subscribe
/// -- theme 我订阅的主题
/// -- album 我收听的专辑
/// -- author 我关注的作者
/// - offline 离线阅读
/// - feedback 意见反馈
/// - messages 消息
/// - submissions 爆料
/// - signIn 登录
/// - register 注册
/// - scan 扫一扫
enum ProfileGroupModuleNavigator {
case main
case setting
case integralMall
case favorite
case subscription(ProfileFeature.SubscriptionType)
case offline
case feedback
case messages
case submissions
case scan
}
enum AuthModuleNavigator {
case auth(AuthRootViewControllerType)
case signIn
case signUp
}
case youWu
case url(_ : ModuleViewControllerURLScheme)
case home(_: HomeGroupModuleNavigator)
case media(_: MediaGroupModuleNavigator)
case community(_: CommunityGroupModuleNavigator)
case profile(_: ProfileGroupModuleNavigator)
case auth(_: AuthModuleNavigator)
}
protocol ModuleViewControllerConvertible {
var underlyingViewController: UIViewController { get }
}
extension ModuleNavigator: ModuleViewControllerConvertible {
var underlyingViewController: UIViewController {
switch self {
case let .home(m):
return m.underlyingViewController
case let .url(m):
return m.underlyingViewController
case let .media(m):
return m.underlyingViewController
case let .community(m):
return m.underlyingViewController
case let .profile(m):
return m.underlyingViewController
case let .auth(m):
return m.underlyingViewController
case .youWu:
return MainViewController()
}
}
}
extension ModuleNavigator.HomeGroupModuleNavigator: ModuleViewControllerConvertible {
var underlyingViewController: UIViewController {
switch self {
case .main:
return MainViewController()
case let .channel(u):
return UIViewController()
}
}
}
extension ModuleNavigator.ModuleViewControllerURLScheme: ModuleViewControllerConvertible {
var underlyingViewController: UIViewController {
switch self {
case let .alert(url,title,description):
return UIViewController()
case let .viewController(m):
return UIViewController()
case let .provider(t0,t1):
return WebViewController(t1,title: t0)
}
}
}
extension ModuleNavigator.MediaGroupModuleNavigator: ModuleViewControllerConvertible {
var underlyingViewController: UIViewController {
switch self {
case .main:
return MediaMainViewController()
case let .videoChannel(u):
return VideoListingsViewController()
case let .video(id):
return UIViewController()
case let .audioChannel(u):
return UIViewController()
case let.audio(id):
return UIViewController()
}
}
}
extension ModuleNavigator.CommunityGroupModuleNavigator: ModuleViewControllerConvertible {
var underlyingViewController: UIViewController {
switch self {
case .main:
return MediaMainViewController()
case .wozai:
return UIViewController()
case let.viewController(p):
return UIViewController()
}
}
}
extension ModuleNavigator.ProfileGroupModuleNavigator: ModuleViewControllerConvertible {
var underlyingViewController: UIViewController {
switch self {
case .main:
return ProfileViewController()
case .setting:
return SettingsViewController()
case .integralMall:
return UIViewController()
case .favorite:
return UIViewController()
case let .subscription(t) where t == .album:
return UIViewController()
case let .subscription(t) where t == .author:
return UIViewController()
case let .subscription(t) where t == .theme:
return UIViewController()
case .offline:
return UIViewController()
case .feedback:
return UIViewController()
case .messages:
return MessagesListingViewController()
case .submissions:
return UIViewController()
case .scan:
return ScanViewController()
default: fatalError()
}
}
}
extension ModuleNavigator.AuthModuleNavigator: ModuleViewControllerConvertible {
var underlyingViewController: UIViewController {
switch self {
case let .auth(t):
return AuthViewController(t)
case .signIn:
return SignInViewController()
case .signUp:
return SignUpViewController()
}
}
}
open class Mediator {
static func viewController(for navigation: ModuleNavigator) -> UIViewController {
return navigation.underlyingViewController
}
}
| mit | a7d3fe8991bb33b54668dbdc30891259 | 28.877273 | 90 | 0.582687 | 5.842667 | false | false | false | false |
obrichak/discounts | discounts/Classes/Managers/DiscountsManager/DiscountsManager.swift | 1 | 3378 | //
// DiscountsManager.swift
// discounts
//
// Created by Alexandr Chernyy on 9/15/14.
// Copyright (c) 2014 Alexandr Chernyy. All rights reserved.
//
import Foundation
class DiscountsManager {
class var sharedManager: DiscountsManager {
struct Static {
static var instance: DiscountsManager?
static var token: dispatch_once_t = 0
}
dispatch_once(&Static.token) {
Static.instance = DiscountsManager()
}
return Static.instance!
}
var discountsArrayData = Array<CompanyObject>()
var discountsCategoryArrayData = Array<CompanyObject>()
func loadJSONFromBundle(filename: String) -> Dictionary<String, AnyObject>? {
let path = NSBundle.mainBundle().pathForResource(filename, ofType: "json")
if (path == nil) {
println("Could not find level file: \(filename)")
return nil
}
var error: NSError?
let data: NSData? = NSData(contentsOfFile: path!, options: NSDataReadingOptions(), error: &error)
if data == nil {
println("Could not load level file: \(filename), error: \(error!)")
return nil
}
let dictionary: AnyObject! = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(), error: &error)
if (dictionary == nil) {
println("Level file '\(filename)' is not valid JSON: \(error!)")
return nil
}
return dictionary as? Dictionary<String, AnyObject>
}
func loadDataFromJSON(filename: String)
{
if(discountsArrayData.count > 0)
{
return;
}
if let dictionary = self.loadJSONFromBundle(filename)
{
let companysArray: NSArray? = dictionary["companys"] as NSArray?
if (companysArray != nil)
{
for item in companysArray!
{
var discount:CompanyObject = CompanyObject()
// we convert each key to a String
discount.companyId = item["companyId"] as Int
discount.categoryId = item["categoryId"] as Int
discount.companyName = item["companyName"] as String
discount.discount = item["discount"] as String
discount.imageName = item["imageName"] as String
discount.discountCode = item["discountCode"] as String
discountsArrayData.append(discount)
}
}
}
}
func getCompanyWithCategory(categoryIndex: Int)
{
if(discountsCategoryArrayData.count > 0)
{
discountsCategoryArrayData.removeAll(keepCapacity: false)
discountsCategoryArrayData = Array<CompanyObject>()
}
println("\n array count: \(discountsCategoryArrayData.count) \n")
for var i = 0; i < discountsArrayData.count; i++ {
var discount:CompanyObject = discountsArrayData[i]
if(discount.categoryId == categoryIndex)
{
discountsCategoryArrayData.append(discount)
}
}
println("\n array count: \(discountsCategoryArrayData.count) \n")
println(discountsCategoryArrayData)
}
} | gpl-3.0 | 22dfafc2a8bca5d38edafd806ff4249b | 32.79 | 130 | 0.571344 | 5.328076 | false | false | false | false |
robzimpulse/mynurzSDK | mynurzSDK/Classes/Realm Model/Country.swift | 1 | 6147 | //
// Country.swift
// Pods
//
// Created by Robyarta on 6/5/17.
//
//
import UIKit
import RealmSwift
public class Country: Object{
public dynamic var id = 0
public dynamic var name = ""
public dynamic var countryCode = ""
public dynamic var countryCodeIso3 = ""
public dynamic var enable = 0
}
public class CountryController {
public static let sharedInstance = CountryController()
var realm: Realm?
public func put(id:Int, name:String, countryCode:String, countryCodeIso3:String, enable:Int) {
self.realm = try! Realm()
try! self.realm!.write {
let object = Country()
object.id = id
object.name = name
object.countryCode = countryCode
object.countryCodeIso3 = countryCodeIso3
object.enable = enable
self.realm!.add(object)
}
}
public func get() -> Results<Country> {
self.realm = try! Realm()
return self.realm!.objects(Country.self)
}
public func get(byId id: Int) -> Country? {
self.realm = try! Realm()
return self.realm!.objects(Country.self).filter("id = '\(id)'").first
}
public func get(byName name: String) -> Country? {
self.realm = try! Realm()
return self.realm!.objects(Country.self).filter("name = '\(name)'").first
}
public func get(byCountryCode countryCode: String) -> Country? {
self.realm = try! Realm()
return self.realm!.objects(Country.self).filter("countryCode = '\(countryCode)'").first
}
public func get(byCountryCodeIso3 countryCodeIso3: String) -> Country? {
self.realm = try! Realm()
return self.realm!.objects(Country.self).filter("countryCodeIso3 = '\(countryCodeIso3)'").first
}
public func get(byEnabled enable: Int) -> Results<Country> {
self.realm = try! Realm()
return self.realm!.objects(Country.self).filter("enable = \(enable)")
}
public func drop() {
self.realm = try! Realm()
try! self.realm!.write {
self.realm!.delete(self.realm!.objects(Country.self))
}
}
}
public class CountryTablePicker: UITableViewController, UISearchResultsUpdating {
var searchController: UISearchController?
open var customFont: UIFont?
open var didSelectClosure: ((Int, String, String, String) -> ())?
var filteredData = [Country]()
var data = [Country]()
let controller = CountryController.sharedInstance
override public func viewDidLoad() {
super.viewDidLoad()
self.automaticallyAdjustsScrollViewInsets = false
self.tableView.tableFooterView = UIView()
self.tableView.separatorInset = UIEdgeInsets.zero
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
if self.tableView.tableHeaderView == nil {
let mySearchController = UISearchController(searchResultsController: nil)
mySearchController.searchResultsUpdater = self
mySearchController.dimsBackgroundDuringPresentation = false
self.tableView.tableHeaderView = mySearchController.searchBar
searchController = mySearchController
}
self.tableView.reloadData()
self.definesPresentationContext = true
for appenData in controller.get(byEnabled: 1) {
data.append(appenData)
}
}
override public func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func filter(_ searchText: String){
filteredData = [Country]()
self.data.forEach({ country in
if country.name.characters.count > searchText.characters.count {
let result = country.name.compare(searchText, options: [.caseInsensitive, .diacriticInsensitive], range: searchText.characters.startIndex ..< searchText.characters.endIndex)
if result == .orderedSame {
filteredData.append(country)
}
}
})
}
public func updateSearchResults(for searchController: UISearchController) {
guard let validText = searchController.searchBar.text else {return}
filter(validText)
self.tableView.reloadData()
}
// MARK: - Table view data source
override public func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let validSearchController = searchController else {return self.data.count}
guard let validText = validSearchController.searchBar.text else {return self.data.count}
if validText.characters.count > 0 {
return self.filteredData.count
}
return self.data.count
}
override public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .default, reuseIdentifier: "reuseIdentifier")
if let validLabel = cell.textLabel {
if let validSearchController = searchController {
if validSearchController.searchBar.text!.characters.count > 0 {
validLabel.text = filteredData[indexPath.row].name
}else{
validLabel.text = data[indexPath.row].name
}
}
if let validFont = customFont {
validLabel.font = validFont
}
}
return cell
}
override public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
guard let validClosure = self.didSelectClosure else {return}
let selectedData = self.data[indexPath.row]
validClosure(selectedData.id,selectedData.name, selectedData.countryCode, selectedData.countryCodeIso3)
}
}
| mit | e1ffbee5ccdfc152d0fef8acb02aa89f | 33.533708 | 189 | 0.624858 | 5.169891 | false | false | false | false |
blue42u/swift-t | stc/tests/3891-struct-deepwait.swift | 4 | 320 | type person {
string name;
int age;
}
type megastruct {
person people[];
person person;
}
main {
megastruct s;
s.person.name = "Bob";
s.person.age = 100;
person t;
t.name = "X";
t.age = 1;
s.people[0] = t;
s.people[1] = s.person;
s.people[2] = t;
wait deep (s) {
trace("DONE");
}
}
| apache-2.0 | 3b5aae7f1b9b82af1597a5006fc5fbaa | 11.307692 | 25 | 0.546875 | 2.519685 | false | false | false | false |
bromas/Architect | UIArchitect/DirectionalLayouts.swift | 1 | 2310 | //
// DirectionalLayouts.swift
// LayoutArchitect
//
// Created by Brian Thomas on 3/9/15.
// Copyright (c) 2015 Brian Thomas. All rights reserved.
//
import Foundation
extension Blueprint {
public class func verticalLayout(views: [UIView], inView: UIView) -> [UIView] {
return verticalLayout(views, inView: inView, spaced: 0.0, with: [.Top: 0, .Right: 0, .Bottom: 0, .Left: 0])
}
public class func verticalLayout(views: [UIView], inView: UIView, with: [BlueprintGuide: CGFloat]) -> [UIView] {
return verticalLayout(views, inView: inView, spaced: 0.0, with: with)
}
public class func verticalLayout(views: [UIView], inView: UIView, spaced: CGFloat, with: [BlueprintGuide: CGFloat]) -> [UIView] {
assert(with.indexForKey(.Top) != .None
&& with.indexForKey(.Right) != .None
&& with.indexForKey(.Bottom) != .None
&& with.indexForKey(.Left) != .None, "You must provide all edges for the insets of a vertical layout.")
let count = views.count
var lastManagedView: UIView?
for (index, view) in enumerate(views) {
align(center: view, with: [.X: 0])
switch count {
case 1:
inset(view, with: [.Top: with[.Top]!, .Left: with[.Left]!, .Right: with[.Right]!, .Bottom: with[.Bottom]!])
case 2:
inset(views[0], with: [.Top: with[.Top]!, .Left: with[.Left]!, .Right: with[.Right]!])
pin(top: views[1], toBottom: views[0], magnitude: CGFloat(spaced))
inset(views[1], with: [.Left: with[.Left]!, .Right: with[.Right]!, .Bottom: with[.Bottom]!])
default:
switch index {
case 0:
inset(view, with: [.Top: with[.Top]!, .Left: with[.Left]!, .Right: with[.Right]!])
case 1...(count-2):
pin(top: view, toBottom: lastManagedView!, magnitude: CGFloat(spaced))
inset(view, with: [.Left: with[.Left]!, .Right: with[.Right]!])
case count-1:
pin((view, .Top), to: (lastManagedView!, .Bottom), magnitude: CGFloat(spaced))
inset(view, with: [.Left: with[.Left]!, .Right: with[.Right]!, .Bottom: with[.Bottom]!])
default:
inset(view, with: [.Top: with[.Top]!, .Left: with[.Left]!, .Right: with[.Right]!, .Bottom: with[.Bottom]!])
}
}
lastManagedView = view
}
return views
}
}
| mit | a98406ed2973925ff9a9bcc10081c4a3 | 39.526316 | 131 | 0.599134 | 3.643533 | false | false | false | false |
blockstack/blockstack-browser | native/macos/Blockstack/Pods/Swifter/Sources/DemoServer.swift | 2 | 6277 | //
// DemoServer.swift
// Swifter
//
// Copyright (c) 2014-2016 Damian Kołakowski. All rights reserved.
//
import Foundation
public func demoServer(_ publicDir: String) -> HttpServer {
print(publicDir)
let server = HttpServer()
server["/public/:path"] = shareFilesFromDirectory(publicDir)
server["/files/:path"] = directoryBrowser("/")
server["/"] = scopes {
html {
body {
ul(server.routes) { service in
li {
a { href = service; inner = service }
}
}
}
}
}
server["/magic"] = { .ok(.html("You asked for " + $0.path)) }
server["/test/:param1/:param2"] = { r in
scopes {
html {
body {
h3 { inner = "Address: \(r.address ?? "unknown")" }
h3 { inner = "Url: \(r.path)" }
h3 { inner = "Method: \(r.method)" }
h3 { inner = "Query:" }
table(r.queryParams) { param in
tr {
td { inner = param.0 }
td { inner = param.1 }
}
}
h3 { inner = "Headers:" }
table(r.headers) { header in
tr {
td { inner = header.0 }
td { inner = header.1 }
}
}
h3 { inner = "Route params:" }
table(r.params) { param in
tr {
td { inner = param.0 }
td { inner = param.1 }
}
}
}
}
}(r)
}
server.GET["/upload"] = scopes {
html {
body {
form {
method = "POST"
action = "/upload"
enctype = "multipart/form-data"
input { name = "my_file1"; type = "file" }
input { name = "my_file2"; type = "file" }
input { name = "my_file3"; type = "file" }
button {
type = "submit"
inner = "Upload"
}
}
}
}
}
server.POST["/upload"] = { r in
var response = ""
for multipart in r.parseMultiPartFormData() {
guard let name = multipart.name, let fileName = multipart.fileName else { continue }
response += "Name: \(name) File name: \(fileName) Size: \(multipart.body.count)<br>"
}
return HttpResponse.ok(.html(response))
}
server.GET["/login"] = scopes {
html {
head {
script { src = "http://cdn.staticfile.org/jquery/2.1.4/jquery.min.js" }
stylesheet { href = "http://cdn.staticfile.org/twitter-bootstrap/3.3.0/css/bootstrap.min.css" }
}
body {
h3 { inner = "Sign In" }
form {
method = "POST"
action = "/login"
fieldset {
input { placeholder = "E-mail"; name = "email"; type = "email"; autofocus = "" }
input { placeholder = "Password"; name = "password"; type = "password"; autofocus = "" }
a {
href = "/login"
button {
type = "submit"
inner = "Login"
}
}
}
}
javascript {
src = "http://cdn.staticfile.org/twitter-bootstrap/3.3.0/js/bootstrap.min.js"
}
}
}
}
server.POST["/login"] = { r in
let formFields = r.parseUrlencodedForm()
return HttpResponse.ok(.html(formFields.map({ "\($0.0) = \($0.1)" }).joined(separator: "<br>")))
}
server["/demo"] = scopes {
html {
body {
center {
h2 { inner = "Hello Swift" }
img { src = "https://devimages.apple.com.edgekey.net/swift/images/swift-hero_2x.png" }
}
}
}
}
server["/raw"] = { r in
return HttpResponse.raw(200, "OK", ["XXX-Custom-Header": "value"], { try $0.write([UInt8]("test".utf8)) })
}
server["/redirect/permanently"] = { r in
return .movedPermanently("http://www.google.com")
}
server["/redirect/temporarily"] = { r in
return .movedTemporarily("http://www.google.com")
}
server["/long"] = { r in
var longResponse = ""
for k in 0..<1000 { longResponse += "(\(k)),->" }
return .ok(.html(longResponse))
}
server["/wildcard/*/test/*/:param"] = { r in
return .ok(.html(r.path))
}
server["/stream"] = { r in
return HttpResponse.raw(200, "OK", nil, { w in
for i in 0...100 {
try w.write([UInt8]("[chunk \(i)]".utf8))
}
})
}
server["/websocket-echo"] = websocket(text: { (session, text) in
session.writeText(text)
}, binary: { (session, binary) in
session.writeBinary(binary)
}, pong: { (session, pong) in
// Got a pong frame
}, connected: { (session) in
// New client connected
}, disconnected: { (session) in
// Client disconnected
})
server.notFoundHandler = { r in
return .movedPermanently("https://github.com/404")
}
server.middleware.append { r in
print("Middleware: \(r.address ?? "unknown address") -> \(r.method) -> \(r.path)")
return nil
}
return server
}
| mpl-2.0 | 59b73825d09d280ce5c480dcba6cbea8 | 29.466019 | 114 | 0.391173 | 4.718797 | false | false | false | false |
yoshinorisano/RxSwift | RxExample/RxExample/Examples/GitHubSignup/GitHubAPI/GitHubAPI.swift | 11 | 1998 | //
// GitHubAPI.swift
// RxExample
//
// Created by Krunoslav Zaher on 4/25/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
enum SignupState: Equatable {
case InitialState
case SigningUp
case SignedUp(signedUp: Bool)
}
func ==(lhs: SignupState, rhs: SignupState) -> Bool {
switch (lhs, rhs) {
case (.InitialState, .InitialState):
return true
case (.SigningUp, .SigningUp):
return true
case (.SignedUp(let lhsSignup), .SignedUp(let rhsSignup)):
return lhsSignup == rhsSignup
default:
return false
}
}
class GitHubAPI {
let dataScheduler: ImmediateSchedulerType
let URLSession: NSURLSession
init(dataScheduler: ImmediateSchedulerType, URLSession: NSURLSession) {
self.dataScheduler = dataScheduler
self.URLSession = URLSession
}
func usernameAvailable(username: String) -> Observable<Bool> {
// this is ofc just mock, but good enough
let URL = NSURL(string: "https://github.com/\(URLEscape(username))")!
let request = NSURLRequest(URL: URL)
return self.URLSession.rx_response(request)
.map { (maybeData, maybeResponse) in
if let response = maybeResponse as? NSHTTPURLResponse {
return response.statusCode == 404
}
else {
return false
}
}
.observeOn(self.dataScheduler)
.catchErrorJustReturn(false)
}
func signup(username: String, password: String) -> Observable<SignupState> {
// this is also just a mock
let signupResult = SignupState.SignedUp(signedUp: arc4random() % 5 == 0 ? false : true)
return [just(signupResult), never()]
.concat()
.throttle(2, MainScheduler.sharedInstance)
.startWith(SignupState.SigningUp)
}
} | mit | 208cf5c515f6ba0d1fb310c0dd077ce0 | 27.971014 | 95 | 0.613614 | 4.510158 | false | false | false | false |
Diuit/DUMessagingUIKit-iOS | DUMessagingUIKit/DUMediaContentViewFactory.swift | 1 | 7513 | //
// DUMediaContentViewFactory.swift
// DUMessagingUIKit
//
// Created by Pofat Diuit on 2016/6/20.
// Copyright © 2016年 duolC. All rights reserved.
//
import UIKit
import URLEmbeddedView
import MisterFusion
/// Generate media content views for each media message type.
open class DUMediaContentViewFactory {
/// Maximum characters in the title label of URL media view
static let kMaximumURLCharacterNumbersInURLMediaContentView: Int = 23
/**
Generate content view of image message.
- parameter image: Main image.
- parameter highlightedImage: Highlighted image.
- parameter frame: The frame size of this content view.
- returns: UIImageView instance with image of the message. Return `nil` if image is nil
*/
public static func makeImageContentView(image: UIImage?, highlightedImage: UIImage? = nil, frame: CGRect? = CGRect(x: 0,y: 0, width: 212, height: 158)) -> DUMediaContentImageView? {
guard image != nil else {
return nil
}
let imageView = DUMediaContentImageView.init(frame: frame ?? CGRect.zero)
imageView.contentMode = .scaleAspectFill
imageView.image = image
imageView.highlightedImage = highlightedImage
return imageView
}
/**
Generate content view of an URL message.
- parameter url: URL string of the web page.
- parameter frame: The frame size of dthis content view.
- returns: A composed UIView of URL preview result.
*/
public static func makeURLContentView(url: String, frame: CGRect) -> DUURLMediaContentView {
// FIXME: size of each subviews are fixed. UI will go nuts when using customized frame.
let contentView = DUURLMediaContentView.init(frame: frame)
let urlFrame: CGRect = CGRect(x: 0, y: 33, width: frame.size.width, height: frame.size.height - 33)
let urlView = URLEmbeddedView.init(frame: urlFrame)
contentView.addSubview(urlView)
urlView.cornerRaidus = 0
urlView.backgroundColor = .white
urlView.borderWidth = 0
urlView.textProvider[.title].font = UIFont.DUURLPreviewTitleFont()
urlView.textProvider[.description].font = UIFont.DUURLPreviewDescriptionFont()
urlView.loadURL(url)
let textFrame: CGRect = CGRect(x: 0, y: 0, width: frame.size.width, height: 33)
let textView: UITextView = UITextView.init(frame: textFrame)
contentView.addSubview(textView)
textView.isScrollEnabled = false
textView.isEditable = false
textView.backgroundColor = UIColor.DULightgreyColor()
textView.textContainerInset = UIEdgeInsetsMake(7, 14, 7, 14)
textView.font = UIFont.DUBodyFont()
// FIXME: truncate too long url string, a stupid way
var truncatedString: String = ""
if url.characters.count > kMaximumURLCharacterNumbersInURLMediaContentView {
truncatedString = url.substring(to: url.characters.index(url.startIndex, offsetBy: kMaximumURLCharacterNumbersInURLMediaContentView - 1))
truncatedString += "..."
} else {
truncatedString = url
}
let underline = NSUnderlineStyle.styleSingle.rawValue | NSUnderlineStyle.patternSolid.rawValue
textView.attributedText = NSAttributedString(string: truncatedString, attributes:
[ NSForegroundColorAttributeName : UIColor.blue,
NSFontAttributeName: UIFont.DUBodyFont(),
NSUnderlineStyleAttributeName: underline])
return contentView
}
/**
Generate content view of a file message. The file here refers to non-video and non-audio file. The content view will have a file icon, a file anme label and an description label(optional).
- parameter name: The file name which will be displayed on the screen.
- parameter description: The description about the file, which is optional. Set to `nil` if you don't have any further information.
- parameter frame: The frame size of this content view.
- returns: A composed view of a file message.
- note: Typically you will use this for non-video and non-audio file. Just for general files which have only download operation.
*/
public static func makeFileContentView(name: String, description: String?, frame: CGRect) -> DUFileMediaContentView {
// FIXME: size of each subviews are fixed. UI will go nuts when using customized frame.
let contentView = DUFileMediaContentView.init(frame: frame)
let imageView = UIImageView.init(image: UIImage.DUFileIconImage())
imageView.contentMode = .scaleAspectFill
let fileNameLabel = UILabel.init()
fileNameLabel.font = UIFont.DUFileTitleFont()
fileNameLabel.text = name
let fileDescLabel = UILabel.init()
fileDescLabel.font = UIFont.DUFileDescLabelFont()
fileDescLabel.text = description ?? ""
contentView.addLayoutSubview(imageView, andConstraints:
imageView.centerY |==| contentView.centerY,
imageView.left |+| 12,
imageView.width |==| 32,
imageView.height |==| 36
)
contentView.addLayoutSubview(fileNameLabel, andConstraints:
fileNameLabel.top |==| imageView.top,
fileNameLabel.left |==| imageView.right |+| 18,
fileNameLabel.right |-| 12,
fileNameLabel.height |==| 20
)
contentView.addLayoutSubview(fileDescLabel, andConstraints:
fileDescLabel.top |==| fileNameLabel.bottom |+| 2,
fileDescLabel.left |==| imageView.right |+| 18,
fileDescLabel.right |-| 12,
fileDescLabel.height |==| 14
)
return contentView
}
/**
Generate content view of a playable video message. You can set a preivew image as background image of this video message cell, otherwise the background will be all black.
- parameter previewImage: An UIImage as a preview of the video. Set to `nil` if you just want a pure black background.
- parameter frame: The frame size of this content view.
- returns: A composed content view of playable video message.
*/
public static func makeVideoContentView(previewImage: UIImage?, frame: CGRect) -> DUMediaContentView {
let contentView = DUMediaContentView.init(frame: frame)
let playIconImageView = UIImageView.init(image: UIImage.DUPlayIcon())
playIconImageView.contentMode = .center
playIconImageView.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height)
if previewImage != nil {
let backgroundImageView = UIImageView.init(image: previewImage!)
backgroundImageView.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height)
backgroundImageView.contentMode = .scaleAspectFill
playIconImageView.backgroundColor = UIColor.clear
backgroundImageView.addSubview(playIconImageView)
contentView.addSubview(backgroundImageView)
} else {
playIconImageView.backgroundColor = UIColor.black
contentView.addSubview(playIconImageView)
}
return contentView
}
}
| mit | 5d4320436b88f5f42cadd852baf6fb17 | 43.702381 | 193 | 0.656059 | 5.168617 | false | false | false | false |
vegather/A-World-of-Circles | A World of Circles.playgroundbook/Contents/Sources/CirclesView.swift | 1 | 5400 | //
// CirclesView.swift
// Sine Demo
//
// Created by Vegard Solheim Theriault on 09/03/2017.
// Copyright © 2017 Vegard Solheim Theriault. All rights reserved.
//
import UIKit
public class CirclesView: UIView {
public var radiusMultiplier: CGFloat = 1
public var circles = [Circle]()
public var shouldDrawMarker = true
public var periodsToDraw = 2.0
internal var graphStartX: CGFloat = 0
internal var graphEndX: CGFloat = 1
public var circlesCenterX: CGFloat = 0
private var displayLink: CADisplayLink?
private var duration = 0.0
// -------------------------------
// MARK: Initialization
// -------------------------------
override public init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
isOpaque = false
backgroundColor = .clear
contentMode = .redraw
displayLink = CADisplayLink(target: self, selector: #selector(renderLoop))
displayLink?.add(to: .main, forMode: .defaultRunLoopMode)
}
func reset() {
duration = 0
}
// -------------------------------
// MARK: Drawing
// -------------------------------
@objc private func renderLoop() {
guard circles.count > 0 else { return }
guard let delta = displayLink?.duration else { return }
// Update circles
for i in 0..<circles.count {
circles[i].rotate(withDelta: delta)
}
duration += delta
// If we've done one full round, reset all the circles.
// If they're not all harmonies of the root circle, they
// would get out of sync otherwise.
if duration > (1/circles[0].frequency) * periodsToDraw {
duration = 0
for i in 0..<circles.count {
circles[i].rotation = 0
}
}
// Re-draw
setNeedsDisplay()
}
public override func draw(_ rect: CGRect) {
var circlesCenter = CGPoint(x: circlesCenterX * bounds.width, y: bounds.midY)
var whiteLevel: CGFloat = 0.5
let whiteLevelDelta = 0.4 / CGFloat(circles.count)
for circle in circles {
circlesCenter = draw(
circle: circle,
at: circlesCenter,
with: UIColor(white: 0, alpha: whiteLevel)
)
whiteLevel -= whiteLevelDelta
}
if shouldDrawMarker {
drawGraphMarker(from: circlesCenter)
}
}
private func draw(circle: Circle, at point: CGPoint, with color: UIColor) -> CGPoint {
color.setStroke()
let radius = CGFloat(circle.radius) * radiusMultiplier
let centerDotRadius: CGFloat = -pow(radius - 100, 2) * 0.0007 + 7
// Circumference
let circumferenceFrame = CGRect(
x: point.x - radius,
y: point.y - radius,
width: radius * 2,
height: radius * 2
)
let circumference = UIBezierPath(ovalIn: circumferenceFrame)
circumference.lineWidth = radius * 0.015 + 1.5
circumference.stroke()
// Center
let centerDotFrame = CGRect(
x: point.x - centerDotRadius,
y: point.y - centerDotRadius,
width: centerDotRadius * 2,
height: centerDotRadius * 2
)
let centerDot = UIBezierPath(ovalIn: centerDotFrame)
centerDot.fill()
// Rod
UIColor.black.setStroke()
let rodEnd = CGPoint(
x: CGFloat( cos(circle.rotation + circle.phaseShift)) * radius + point.x,
y: CGFloat(-sin(circle.rotation + circle.phaseShift)) * radius + point.y
)
let rod = UIBezierPath()
rod.move(to: point)
rod.addLine(to: rodEnd)
rod.lineWidth = 3
rod.stroke()
return rodEnd
}
private func drawGraphMarker(from: CGPoint) {
guard circles.count > 0 else { return }
UIColor(white: 0, alpha: 0.3).set()
let cycleDuration = (1/circles[0].frequency) * periodsToDraw
let drawProgress = duration.truncatingRemainder(dividingBy: cycleDuration) / cycleDuration
let graphWidth = (graphEndX - graphStartX) * bounds.width
let to = CGPoint(x: graphStartX * bounds.width + graphWidth * CGFloat(drawProgress), y: from.y)
let horizontalMarker = UIBezierPath()
horizontalMarker.move(to: from)
horizontalMarker.addLine(to: to)
horizontalMarker.lineWidth = 3
var dashPattern: [CGFloat] = [10.0, 10.0]
horizontalMarker.setLineDash(&dashPattern, count: dashPattern.count, phase: 0)
horizontalMarker.lineCapStyle = .round
horizontalMarker.stroke()
let dotRadius = CGFloat(4)
let dotFrame = CGRect(
x: to.x - dotRadius,
y: to.y - dotRadius,
width: dotRadius * 2,
height: dotRadius * 2
)
let dot = UIBezierPath(ovalIn: dotFrame)
dot.fill()
}
}
| mit | 9c62c972cda75273886f7f10a262eff0 | 28.994444 | 103 | 0.545471 | 4.799111 | false | false | false | false |
jmfieldman/Mortar | Examples/MortarVFL/MortarVFL/Examples/VFL_Example3ViewController.swift | 1 | 1776 | //
// VFL_Example3ViewController.swift
// MortarVFL
//
// Created by Jason Fieldman on 4/8/17.
// Copyright © 2017 Jason Fieldman. All rights reserved.
//
import Foundation
import UIKit
class VFL_Example3ViewController: UIViewController {
let red = UIView.m_create {
$0.backgroundColor = .red
}
let blue = UIView.m_create {
$0.backgroundColor = .blue
}
let green = UIView.m_create {
$0.backgroundColor = .green
}
let orange = UIView.m_create {
$0.backgroundColor = .orange
}
let yellow = UIView.m_create {
$0.backgroundColor = .yellow
}
let darkGray = UIView.m_create {
$0.backgroundColor = .darkGray
}
let lightGray = UIView.m_create {
$0.backgroundColor = .lightGray
}
let magenta = UIView.m_create {
$0.backgroundColor = .magenta
}
override func viewDidLoad() {
self.view.backgroundColor = .white
self.view |+| [
red,
blue,
green,
orange,
yellow,
darkGray,
lightGray,
magenta
]
self.view ||>> red[~~1] || blue[==40] || green[~~2]
self.view ||>> [orange, yellow][~~1]
self.m_visibleRegion ||^^ [red, blue, green][~~1] || orange[==44] || yellow[==44]
// Insert gray in green
green |>> ~~1 | [darkGray, lightGray][==44] | ~~1
green |^^ ~~1 | darkGray[==44] | ~~1 | lightGray[==44] | ~~1
// Insert magenta between grays
darkGray.m_bottom |^ ~~1 | magenta[==22] | ~~1 ^| lightGray.m_top
darkGray |>> ~~1 | magenta[==22] | ~~1
}
}
| mit | b4f89dcb88b3906e971f55d0610df653 | 22.355263 | 89 | 0.500845 | 4.071101 | false | false | false | false |
jamy0801/LGWeChatKit | LGWeChatKit/LGChatKit/conversionList/view/LGConversionListCell.swift | 1 | 3974 | //
// LGConversionListCell.swift
// LGChatViewController
//
// Created by jamy on 10/19/15.
// Copyright © 2015 jamy. All rights reserved.
//
import UIKit
class LGConversionListCell: LGConversionListBaseCell {
let iconView: UIImageView!
let userNameLabel: UILabel!
let messageLabel: UILabel!
let timerLabel: UILabel!
let messageListCellHeight = 64
var viewModel: LGConversionListCellModel? {
didSet {
viewModel?.iconName.observe {
[unowned self] in
self.iconView.image = UIImage(named: $0)
}
viewModel?.lastMessage.observe {
[unowned self] in
self.messageLabel.text = $0
}
viewModel?.userName.observe {
[unowned self] in
self.userNameLabel.text = $0
}
viewModel?.timer.observe {
[unowned self] in
self.timerLabel.text = $0
}
}
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
iconView = UIImageView(frame: CGRectMake(5, CGFloat(messageListCellHeight - 50) / 2, 50, 50))
iconView.layer.cornerRadius = 5.0
iconView.layer.masksToBounds = true
userNameLabel = UILabel()
userNameLabel.textAlignment = .Left
userNameLabel.font = UIFont.systemFontOfSize(14.0)
messageLabel = UILabel()
messageLabel.textAlignment = .Left
messageLabel.font = UIFont.systemFontOfSize(13.0)
messageLabel.textColor = UIColor.lightGrayColor()
timerLabel = UILabel()
timerLabel.textAlignment = .Right
timerLabel.font = UIFont.systemFontOfSize(14.0)
timerLabel.textColor = UIColor.lightGrayColor()
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(iconView)
contentView.addSubview(userNameLabel)
contentView.addSubview(messageLabel)
contentView.addSubview(timerLabel)
userNameLabel.translatesAutoresizingMaskIntoConstraints = false
messageLabel.translatesAutoresizingMaskIntoConstraints = false
timerLabel.translatesAutoresizingMaskIntoConstraints = false
contentView.addConstraint(NSLayoutConstraint(item: userNameLabel, attribute: .Left, relatedBy: .Equal, toItem: contentView, attribute: .Left, multiplier: 1, constant: CGFloat(messageListCellHeight + 8)))
contentView.addConstraint(NSLayoutConstraint(item: userNameLabel, attribute: .Top, relatedBy: .Equal, toItem: contentView, attribute: .Top, multiplier: 1, constant: 5))
contentView.addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .Left, relatedBy: .Equal, toItem: userNameLabel, attribute: .Left, multiplier: 1, constant: 0))
contentView.addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .Top, relatedBy: .Equal, toItem: userNameLabel, attribute: .Bottom, multiplier: 1, constant: 10))
contentView.addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .Right, relatedBy: .Equal, toItem: contentView, attribute: .Right, multiplier: 1, constant: -70))
contentView.addConstraint(NSLayoutConstraint(item: timerLabel, attribute: .Left, relatedBy: .Equal, toItem: contentView, attribute: .Right, multiplier: 1, constant: -65))
contentView.addConstraint(NSLayoutConstraint(item: timerLabel, attribute: .Top, relatedBy: .Equal, toItem: userNameLabel, attribute: .Top, multiplier: 1, constant: 0))
contentView.addConstraint(NSLayoutConstraint(item: timerLabel, attribute: .Right, relatedBy: .Equal, toItem: contentView, attribute: .Right, multiplier: 1, constant: -5))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 082b999249c077c58964bd972821cb98 | 42.184783 | 211 | 0.660458 | 5.283245 | false | false | false | false |
grpc/grpc-swift | Sources/GRPCInteroperabilityTestsImplementation/InteroperabilityTestServer.swift | 1 | 2619 | /*
* Copyright 2019, gRPC Authors All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import GRPC
import Logging
import NIOCore
#if canImport(NIOSSL)
import NIOSSL
#endif
/// Makes a server for gRPC interoperability testing.
///
/// - Parameters:
/// - host: The host to bind the server socket to, defaults to "localhost".
/// - port: The port to bind the server socket to.
/// - eventLoopGroup: Event loop group to run the server on.
/// - serviceProviders: Service providers to handle requests with, defaults to provider for the
/// "Test" service.
/// - useTLS: Whether to use TLS or not. If `true` then the server will use the "server1"
/// certificate and CA as set out in the interoperability test specification. The common name
/// is "*.test.google.fr"; clients should set their hostname override accordingly.
/// - Returns: A future `Server` configured to serve the test service.
public func makeInteroperabilityTestServer(
host: String = "localhost",
port: Int,
eventLoopGroup: EventLoopGroup,
serviceProviders: [CallHandlerProvider] = [TestServiceProvider()],
useTLS: Bool,
logger: Logger? = nil
) throws -> EventLoopFuture<Server> {
let builder: Server.Builder
if useTLS {
#if canImport(NIOSSL)
let caCert = InteroperabilityTestCredentials.caCertificate
let serverCert = InteroperabilityTestCredentials.server1Certificate
let serverKey = InteroperabilityTestCredentials.server1Key
builder = Server.usingTLSBackedByNIOSSL(
on: eventLoopGroup,
certificateChain: [serverCert],
privateKey: serverKey
)
.withTLS(trustRoots: .certificates([caCert]))
#else
fatalError("'useTLS: true' passed to \(#function) but NIOSSL is not available")
#endif // canImport(NIOSSL)
} else {
builder = Server.insecure(group: eventLoopGroup)
}
if let logger = logger {
builder.withLogger(logger)
}
return builder
.withMessageCompression(.enabled(.init(decompressionLimit: .absolute(1024 * 1024))))
.withServiceProviders(serviceProviders)
.bind(host: host, port: port)
}
| apache-2.0 | 22f214bbd6cf9129349c0dcc79ad3db3 | 35.375 | 97 | 0.724322 | 4.224194 | false | true | false | false |
PrinceChen/DouYu | DouYu/DouYu/Classes/Home/Model/AnchorModel.swift | 1 | 648 | //
// AnchorModel.swift
// DouYu
//
// Created by prince.chen on 2017/3/2.
// Copyright © 2017年 prince.chen. All rights reserved.
//
import UIKit
class AnchorModel: NSObject {
var room_id: Int = 0
var vertical_src: String = ""
// 0: 电脑直播,1:手机直播
var isVertical: Int = 0
var room_name: String = ""
var nickname: String = ""
var online: Int = 0
var anchor_city: String = ""
init(dict: [String: Any]) {
super.init()
setValuesForKeys(dict)
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {
}
}
| mit | 99d4911cfd82fbe7350af2d1e1542c90 | 16.857143 | 72 | 0.5568 | 3.76506 | false | false | false | false |
hathway/JSONRequest | JSONRequest/JSONRequestSSLPinningHandler.swift | 1 | 4484 | //
// JSONRequestSSLPinningHandler.swift
// JSONRequest
//
// Created by Yevhenii Hutorov on 11.11.2019.
// Copyright © 2019 Hathway. All rights reserved.
//
import Foundation
import CommonCrypto
///JSONRequestSSLPinningHandler helps to associate a host with their hash of expected certificate public key
/// - Example:
///````
/// let sslPinningHandler = JSONRequestSSLPinningHandler()
/// sslPinningHandler["ordering.api.com"] = "<cert key>"
/// JSONRequest.authChallengeHandler = sslPinningHandler
///````
/// - Note: To obtain a hash of cerificate public key You should run these commands on terminal
///
///openssl s_client -connect **host**:**port** -showcerts < /dev/null | openssl x509 -outform DER > certificate.der
///
///openssl x509 -pubkey -noout -in certificate.der -inform DER | openssl rsa -outform DER -pubin -in /dev/stdin 2>/dev/null > certificatekey.der
///
///python -sBc \"from \_\_future\_\_ import print_function;import hashlib;print(hashlib.sha256(open(\'certificatekey.der\',\'rb\').read()).digest(), end=\'\')\" | base64
///
///[Certificate and Public Key Pinning]: https://www.owasp.org/index.php/Certificate_and_Public_Key_Pinning
///For more information, see [Certificate and Public Key Pinning].
@available(iOS 10.3, *)
public final class JSONRequestSSLPinningHandler: JSONRequestAuthChallengeHandler {
let rsa2048Asn1Header: [UInt8] = [
0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00
]
/// dictionary with SSL pinning info
/// # Parameters:
/// key: Host
/// value: Certificate Public Key hash
/// - Important: Host must be used without a schema
/// ````
///let sslPinningHandler = JSONRequestSSLPinningHandler()
///sslPinningHandler["ordering.api.olo.com"] = "EXEMPLRQHWwFk9jBZYEayPhZnPvUMtJpQ" // Correct host
///sslPinningHandler["https://peetniks.okta.com"] = "EXEMPLRQHWwFk9jBZYEayPhZnPvUMtJpQ" // Incorrect host
///````
public var cerificatePublicKeys: [String: String]
public init() {
cerificatePublicKeys = [:]
}
private func sha256(data: Data) -> String {
var keyWithHeader = Data(rsa2048Asn1Header)
keyWithHeader.append(data)
var hash = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
#warning("Check this code for warning fix")
// keyWithHeader.withUnsafeBytes { (data: UnsafeRawBufferPointer) in
// _ = CC_SHA256(data.baseAddress, CC_LONG(keyWithHeader.count), &hash)
// }
keyWithHeader.withUnsafeBytes {
_ = CC_SHA256($0, CC_LONG(keyWithHeader.count), &hash)
}
return Data(hash).base64EncodedString()
}
public func handle(_ session: URLSession, challenge: URLAuthenticationChallenge) -> JSONRequestAuthChallengeResult {
guard let serverTrust = challenge.protectionSpace.serverTrust else {
return JSONRequestAuthChallengeResult(disposition: .performDefaultHandling)
}
let policies = NSMutableArray()
let host = challenge.protectionSpace.host
guard let pinnedPublicKeyHash = cerificatePublicKeys[host] else { return JSONRequestAuthChallengeResult(disposition: .performDefaultHandling) }
policies.add(SecPolicyCreateSSL(true, host as CFString))
SecTrustSetPolicies(serverTrust, policies)
var result: SecTrustResultType = SecTrustResultType(rawValue: 0)!
SecTrustEvaluate(serverTrust, &result)
guard result == .unspecified || result == .proceed, let serverCertificate = SecTrustGetCertificateAtIndex(serverTrust, 0) else {
return JSONRequestAuthChallengeResult(disposition: .cancelAuthenticationChallenge)
}
guard let serverPublicKey = SecCertificateCopyPublicKey(serverCertificate),
let serverPublicKeyData: NSData = SecKeyCopyExternalRepresentation(serverPublicKey, nil ) else {
return JSONRequestAuthChallengeResult(disposition: .performDefaultHandling)
}
let keyHash = sha256(data: serverPublicKeyData as Data)
if keyHash == pinnedPublicKeyHash {
// Success! This is our server
return JSONRequestAuthChallengeResult(disposition: .useCredential, credential: URLCredential(trust: serverTrust))
} else {
return JSONRequestAuthChallengeResult(disposition: .cancelAuthenticationChallenge)
}
}
}
| mit | 7c5f7023cb7ee49b92fefa039febf61b | 44.282828 | 169 | 0.695516 | 4.302303 | false | false | false | false |
ishkawa/DIKit | Example/Example/AppDelegate.swift | 1 | 831 | //
// AppDelegate.swift
// Example
//
// Created by Yosuke Ishikawa on 2017/09/17.
// Copyright © 2017年 ishkawa. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
let appResolver = AppResolverImpl()
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let viewController = appResolver.resolveListViewController()
let navigationController = UINavigationController(rootViewController: viewController)
window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = navigationController
window?.backgroundColor = .white
window?.makeKeyAndVisible()
return true
}
}
| mit | e7e70fe13e869b0145f40c3bd6da42af | 28.571429 | 145 | 0.728261 | 5.273885 | false | false | false | false |
benlangmuir/swift | test/Interpreter/SDK/objc_fast_enumeration.swift | 27 | 2048 | // RUN: %target-run-simple-swift | %FileCheck %s
// REQUIRES: executable_test
// REQUIRES: objc_interop
import Foundation
var a: NSArray = ["one", 2, [1,2,3]]
var a_m: NSMutableArray = ["two", 12, [11,12,13]]
// CHECK: one
// CHECK: 2
// CHECK: (
// CHECK: 1,
// CHECK: 2,
// CHECK: 3
// CHECK: )
for x in a {
print(x)
}
// CHECK: two
// CHECK: 12
// CHECK: (
// CHECK: 11,
// CHECK: 12,
// CHECK: 13
// CHECK: )
for x in a_m {
print(x)
}
class Canary {
var x: Int
deinit { print("dead \(x)") }
init(_ x: Int) { self.x = x }
func chirp() { print("\(x)") }
}
autoreleasepool {
print("making array")
var b: NSArray = NSArray(objects: [Canary(1), Canary(2), Canary(3)], count: 3)
print("iterating array")
// CHECK-DAG: 1
for x in b {
(x as! Canary).chirp()
break
}
// CHECK-DAG: exiting
print("exiting")
}
// CHECK-DAG: dead 1
// CHECK-DAG: dead 2
// CHECK-DAG: dead 3
// CHECK: exited
print("exited")
var d : NSDictionary = [415 : "Giants" , 510 : "A's"]
var d_m : NSMutableDictionary = [1415 : "Big Giants", 11510 : "B's"]
// CHECK: 510 => A's
for (key, value) in d {
print("\(key) => \(value)")
}
// CHECK: 11510 => B's
for (key, value) in d_m {
print("\(key) => \(value)")
}
var s = NSSet(object: "the most forward-thinking test yet")
var s_m = NSMutableSet(object: "the next most forward-thinking test yet")
// CHECK: the most forward-thinking test yet
for x in s {
print(x)
}
// CHECK: the next most forward-thinking test yet
for x in s_m {
print(x)
}
// Enumeration over a __SwiftDeferredNSArray
// CHECK: 3
// CHECK: 2
// CHECK: 1
var a2 = [3, 2, 1]
var nsa2: NSArray = a2._bridgeToObjectiveC()
for x in nsa2 {
print(x)
}
class X : CustomStringConvertible {
init(_ value: Int) { self.value = value }
var value: Int
var description: String { return "X(\(value))" }
}
// Enumeration over a _ContiguousArrayBuffer
// CHECK: X(3)
// CHECK: X(2)
// CHECK: X(1)
var a3 = [X(3), X(2), X(1)]
var nsa3: NSArray = a3._bridgeToObjectiveC()
for x in nsa3 {
print(x)
}
| apache-2.0 | ece801aae127793521f945d2473b46f4 | 17.123894 | 80 | 0.595703 | 2.805479 | false | false | false | false |
harlanhaskins/Swips | Sources/Swips/ProgramSerializer.swift | 1 | 4525 | /// Serializes a MIPS program as an assembly string
struct ProgramSerializer {
/// The program that will be serialized
let program: Program
/// Serializes an instruction with the correct MIPS syntax
func serialize(_ instruction: Instruction) -> String {
switch instruction {
case .lw(let destination, let offset, let addr):
return instr("lw", destination, "\(offset)(\(addr))")
case .lb(let destination, let offset, let addr):
return instr("lb", destination, "\(offset)(\(addr))")
case .li(let reg, let imm):
return instr("li", reg, imm)
case .la(let reg, let decl):
return instr("la", reg, decl.label)
case .sw(let source, let offset, let addr):
return instr("sw", source, "\(offset)(\(addr))")
case .sb(let source, let offset, let addr):
return instr("sb", source, "\(offset)(\(addr))")
case .rtype(let name, let dst, let r1, let r2, let signed):
let suffix = signed ? "" : "u"
return instr("\(name)\(suffix)", dst, r1, r2)
case .itype(let name, let dst, let r, let imm, let signed):
let suffix = signed ? "" : "u"
return instr("\(name)i\(suffix)", dst, r, imm)
case .j(let block):
return instr("j", block.label)
case .jal(let block):
return instr("jal", block.label)
case .br(let cmp, let s, let t, let target):
return instr("b\(cmp.rawValue)", s, t, target.label)
case .jr(let reg):
return instr("jr", reg)
case .mult(let s, let t):
return instr("mult", s, t)
case .multu(let s, let t):
return instr("multu", s, t)
case .mfhi(let reg):
return instr("mfhi", reg)
case .mflo(let reg):
return instr("mflo", reg)
case .noop:
return "noop"
case .syscall:
return "syscall"
}
}
/// Serializes a basic block by serializing the instructions and label
func serialize(_ basicBlock: BasicBlock) -> String {
var instrText = basicBlock.instructions.map {
"\t\t\(serialize($0))"
}
instrText.insert("\(basicBlock.label):", at: 0)
if basicBlock.global {
instrText.insert("\t\t.globl \(basicBlock.label)", at: 0)
}
return instrText.joined(separator: "\n")
}
/// Serializes a program by serializing the text and data sections
func serialize(_ program: Program) -> String {
var sections = [String]()
if !program.blocks.isEmpty {
let code = program.blocks.map(serialize).joined(separator: "\n")
sections.append([
"\t\t.text",
"\t\t.align \(program.align)",
code
].joined(separator: "\n"))
}
if !program.data.isEmpty {
let code = program.data.map(serialize).joined(separator: "\n")
sections.append("\t\t.data\n\(code)")
}
return sections.joined(separator: "\n\n")
}
/// Serializes the provided data declaration label and kind
func serialize(_ dataDeclaration: DataDeclaration) -> String {
return "\(dataDeclaration.label):\n\t\t\(serialize(dataDeclaration.kind))"
}
/// Serializes the provided data declaration kind as a MIPS assembly string
func serialize(_ dataDeclarationKind: DataDeclarationKind) -> String {
switch dataDeclarationKind {
case .byte(let bytes):
return ".byte \(commaSep(bytes))"
case .word(let words):
return ".word \(commaSep(words))"
case .halfword(let halfwords):
return ".halfword \(commaSep(halfwords))"
case .ascii(let str, let terminated):
let suffix = terminated ? "z" : ""
return ".ascii\(suffix) \"\(str)\""
case .space(let length):
return ".space \(length)"
}
}
/// Serializes a register
func serialize(_ register: Register) -> String {
return "\(register)"
}
/// Serializes the provided program
func serialize() -> String {
return serialize(program)
}
}
fileprivate func commaSep(_ values: [Any]) -> String {
return values.map { String(describing: $0) }.joined(separator: ", ")
}
fileprivate func instr(_ name: String, _ args: Any...) -> String {
return "\(name)\t\t\(commaSep(Array(args)))"
}
| mit | 03c38f6c313e8354a0ad4c8ff3a1a8cf | 37.02521 | 82 | 0.556022 | 4.244841 | false | false | false | false |
Otbivnoe/Routing | Routing/Routing/Transitions/PushTransition.swift | 1 | 1790 | //
// PushTransition.swift
// Routing
//
// Created by Nikita Ermolenko on 28/10/2017.
//
import UIKit
class PushTransition: NSObject {
var animator: Animator?
var isAnimated: Bool = true
var completionHandler: (() -> Void)?
weak var viewController: UIViewController?
init(animator: Animator? = nil, isAnimated: Bool = true) {
self.animator = animator
self.isAnimated = isAnimated
}
}
// MARK: - Transition
extension PushTransition: Transition {
func open(_ viewController: UIViewController) {
self.viewController?.navigationController?.delegate = self
self.viewController?.navigationController?.pushViewController(viewController, animated: isAnimated)
}
func close(_ viewController: UIViewController) {
self.viewController?.navigationController?.popViewController(animated: isAnimated)
}
}
// MARK: - UINavigationControllerDelegate
extension PushTransition: UINavigationControllerDelegate {
func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
completionHandler?()
}
func navigationController(_ navigationController: UINavigationController,
animationControllerFor operation: UINavigationControllerOperation,
from fromVC: UIViewController,
to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
guard let animator = animator else {
return nil
}
if operation == .push {
animator.isPresenting = true
return animator
}
else {
animator.isPresenting = false
return animator
}
}
}
| mit | d3891aa9bf9bca6e93dcc581dd4caed9 | 27.870968 | 137 | 0.661453 | 6.006711 | false | false | false | false |
sstanic/OnTheMap | On The Map/On The Map/DataStore.swift | 1 | 2388 | //
// DataStore.swift
// On The Map
//
// Created by Sascha Stanic on 03.05.16.
// Copyright © 2016 Sascha Stanic. All rights reserved.
//
import Foundation
class DataStore: NSObject {
//# MARK: Attributes
var studentInformationList: [StudentInformation]? = []
dynamic var isLoading = false
var isNotLoading: Bool {
return !isLoading
}
fileprivate let concurrentDataQueue = DispatchQueue(label: "com.savvista.udacity.OnTheMap.dataQueue", attributes: DispatchQueue.Attributes.concurrent)
//# MARK: Load Student Data
func loadStudentData(_ loadCompletionHandler : @escaping (_ success: Bool, _ error: NSError?) -> Void) {
self.notifyLoadingStudentData(true)
self.concurrentDataQueue.sync(flags: .barrier, execute: {
self.studentInformationList = nil
})
OTMClient.sharedInstance().getStudentLocations() { (success, results, error) in
if success {
self.notifyLoadingStudentData(false)
self.concurrentDataQueue.sync(flags: .barrier, execute: {
self.studentInformationList = results!
})
// return with success and load async the udacity user names
loadCompletionHandler(true, nil)
}
else {
self.notifyLoadingStudentData(false)
loadCompletionHandler(false, error)
}
}
}
func reloadStudentData(_ reloadCompletionHandler : @escaping (_ success: Bool, _ error: NSError?) -> Void) {
if isNotLoading {
loadStudentData() { (success, error) in
if success {
reloadCompletionHandler(true, nil)
}
else {
reloadCompletionHandler(false, error)
}
}
}
}
//# MARK: Notifications
fileprivate func notifyLoadingStudentData(_ isLoading: Bool) {
Utils.GlobalMainQueue.async {
self.isLoading = isLoading
}
}
//# MARK: Shared Instance
class func sharedInstance() -> DataStore {
struct Singleton {
static var sharedInstance = DataStore()
}
return Singleton.sharedInstance
}
}
| mit | 45359f8665584950386ce07fc5324d95 | 28.469136 | 154 | 0.56305 | 5.412698 | false | false | false | false |
powerytg/Accented | Accented/UI/Gallery/Models/UserGalleryListViewModel.swift | 1 | 5005 | //
// UserGalleryListViewModel.swift
// Accented
//
// View model for a user's gallery list
//
// Created by You, Tiangong on 9/6/17.
// Copyright © 2017 Tiangong You. All rights reserved.
//
import UIKit
import RMessage
class UserGalleryListViewModel: InfiniteLoadingViewModel<GalleryModel> {
private let galleryRendererIdentifier = "gallery"
private let streamHeaderReuseIdentifier = "streamHeader"
private let headerSection = 0
private var user : UserModel
init(user : UserModel, collection: CollectionModel<GalleryModel>, collectionView: UICollectionView) {
self.user = user
super.init(collection: collection, collectionView: collectionView)
// Register cell types
let galleryCell = UINib(nibName: "GalleryListRenderer", bundle: nil)
collectionView.register(galleryCell, forCellWithReuseIdentifier: galleryRendererIdentifier)
let streamHeaderNib = UINib(nibName: "DefaultSingleStreamHeaderCell", bundle: nil)
collectionView.register(streamHeaderNib, forCellWithReuseIdentifier: streamHeaderReuseIdentifier)
// Events
NotificationCenter.default.addObserver(self, selector: #selector(galleryListDidUpdate(_:)), name: StorageServiceEvents.userGalleryListDidUpdate, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
override func createCollectionViewLayout() {
layout = UserGalleryListLayout()
layout.collection = collection
}
override func loadPageAt(_ page : Int) {
APIService.sharedInstance.getGalleries(userId: collection.modelId!, page: page, parameters: [String : String](), success: nil) { [weak self] (errorMessage) in
self?.collectionFailedLoading(errorMessage)
RMessage.showNotification(withTitle: errorMessage, subtitle: nil, type: .error, customTypeName: nil, callback: nil)
}
}
@objc private func galleryListDidUpdate(_ notification : Notification) {
let userId = notification.userInfo![StorageServiceEvents.userId] as! String
let page = notification.userInfo![StorageServiceEvents.page] as! Int
guard userId == collection.modelId else { return }
// Get a new copy of the comment collection
collection = StorageService.sharedInstance.getUserGalleries(userId: userId)
updateCollectionView(page == 1)
streamState.loading = false
if page == 1 {
streamState.refreshing = false
delegate?.viewModelDidRefresh()
}
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if !collection.loaded {
let loadingCell = collectionView.dequeueReusableCell(withReuseIdentifier: initialLoadingRendererReuseIdentifier, for: indexPath)
return loadingCell
} else if indexPath.section == headerSection {
if indexPath.item == 0 {
return streamHeader(indexPath)
} else {
fatalError("There is no header cells beyond index 0")
}
} else {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: galleryRendererIdentifier, for: indexPath) as! GalleryListRenderer
cell.gallery = collection.items[indexPath.item]
cell.setNeedsLayout()
return cell
}
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 2
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if section == headerSection {
return 2
} else {
if !collection.loaded {
return 1
} else {
return collection.items.count
}
}
}
private func streamHeader(_ indexPath : IndexPath) -> UICollectionViewCell {
let streamHeaderCell = collectionView.dequeueReusableCell(withReuseIdentifier: streamHeaderReuseIdentifier, for: indexPath) as! DefaultSingleStreamHeaderCell
let userName = TextUtils.preferredAuthorName(user).uppercased()
streamHeaderCell.titleLabel.text = "\(userName)'S \nGALLERIES"
if let galleryCount = user.galleryCount {
if galleryCount == 0 {
streamHeaderCell.subtitleLabel.text = "NO ITEMS"
} else if galleryCount == 1 {
streamHeaderCell.subtitleLabel.text = "1 ITEM"
} else {
streamHeaderCell.subtitleLabel.text = "\(galleryCount) ITEMS"
}
} else {
streamHeaderCell.subtitleLabel.isHidden = true
}
streamHeaderCell.displayStyleButton.isHidden = true
streamHeaderCell.orderButton.isHidden = true
streamHeaderCell.orderLabel.isHidden = true
return streamHeaderCell
}
}
| mit | 68c17095861a39a3b865d37c310b65f3 | 39.354839 | 166 | 0.663869 | 5.529282 | false | false | false | false |
danlozano/Filtr | FiltrMacDemo/ViewController.swift | 1 | 9259 | //
// ViewController.swift
// FiltrMacDemo
//
// Created by Daniel Lozano on 6/23/16.
// Copyright © 2016 danielozano. All rights reserved.
//
import Cocoa
import Filtr
class ViewController: NSViewController {
@IBOutlet weak var imageView: NSImageView!
@IBOutlet weak var filterView: NSImageView!
override func viewDidLoad() {
super.viewDidLoad()
//imageView.imageScaling = .ScaleAxesIndependently
//imageView.image = image
let filterImage = EffectFilterType.color2.thumbnail
filterView.image = filterImage
testCustomFilter()
//filter()
//filterMultipleTest()
//createfcube()
//createFcubes()
//transformLuts()
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
func createfcube(){
let filterName = "bottom"
let lutPath = Constants.documentsDirectory.stringByAppendingPathComponent("filtr/\(filterName).tif")
let lutImage = NSImage(contentsOfFile: lutPath)!
let lutData = LUTConverter.cubeDataForLut64(lutImage)!
let path = Constants.documentsDirectory.stringByAppendingPathComponent("filtr/\(filterName).fcube")
try? lutData.write(to: URL(fileURLWithPath: path), options: .atomic)
}
func createFcubes(){
let manager = FileManager()
do {
let lutsURL = URL(string: Constants.documentsDirectory.stringByAppendingPathComponent("filtr/otherluts"))!
let contents = try manager.contentsOfDirectory(at: lutsURL,
includingPropertiesForKeys: [],
options: .skipsHiddenFiles)
for fileURL in contents {
let image = NSImage(contentsOf: fileURL)!
let lutData = LUTConverter.cubeDataForLut32(image)
let fileName = fileURL.lastPathComponent.components(separatedBy: ".").first!
let filePath = Constants.documentsDirectory.stringByAppendingPathComponent("filtr/otherfcubes/\(fileName).fcube")
try? lutData!.write(to: URL(fileURLWithPath: filePath), options: .atomic)
print("SAVING \(fileName).fcube")
}
} catch {
print("ERROR = \(error)")
}
}
func transformLuts(){
let manager = FileManager()
do {
let lutsURL = URL(string: Constants.documentsDirectory.stringByAppendingPathComponent("filtr/imgly64luts"))!
let contents = try manager.contentsOfDirectory(at: lutsURL,
includingPropertiesForKeys: [],
options: .skipsHiddenFiles)
let inputPath = Constants.documentsDirectory.stringByAppendingPathComponent("filtr/identity32.png")
let inputImage = NSImage(contentsOfFile: inputPath)!
let inputCiImage = ImageConverter.CIImageFrom(inputImage)
for fileURL in contents {
let lutImage = NSImage(contentsOf: fileURL)!
let lutData = LUTConverter.cubeDataForLut64(lutImage)
let colorCubeFilter = CIFilter(name: "CIColorCubeWithColorSpace")!
colorCubeFilter.setValue(lutData, forKey: "inputCubeData")
colorCubeFilter.setValue(64, forKey: "inputCubeDimension")
colorCubeFilter.setValue(CGColorSpaceCreateDeviceRGB(), forKey: "inputColorSpace")
colorCubeFilter.setValue(inputCiImage, forKey: kCIInputImageKey)
let image = ImageConverter.NSImageFrom(colorCubeFilter.outputImage!)
let fileName = fileURL.lastPathComponent.components(separatedBy: ".").first!
let pngData = ImageConverter.imageDataFrom(image, compression: nil, type: .PNG)!
let path = Constants.documentsDirectory.stringByAppendingPathComponent("filtr/imgly32luts/\(fileName).png")
try? pngData.write(to: URL(fileURLWithPath: path), options: .atomic)
print("SAVING \(fileName).png")
}
} catch {
print("ERROR = \(error)")
}
}
func filterMultipleTest(){
let imagePath = Constants.documentsDirectory.stringByAppendingPathComponent("filtr/orig2.jpg")
let image = NSImage(contentsOfFile: imagePath)!
for effect in EffectFilterType.allFilters {
let fileName = effect.rawValue
print("PROCESSING FILTER = \(fileName)")
let effectFilter = effect.filter
effectFilter.inputIntensity = 1.0
// let fadeFilter = FadeFilter()
// fadeFilter.intensity = 0.33
let filterStack = FilterStack()
filterStack.effectFilter = effectFilter
//filterStack.fadeFilter = fadeFilter
let filteredImage = Filtr.process(image, filterStack: filterStack)!
let jpegData = ImageConverter.imageDataFrom(filteredImage, compression: 1.0, type: .JPEG)!
let path = Constants.documentsDirectory.stringByAppendingPathComponent("filtr/tests/\(fileName).jpg")
try? jpegData.write(to: URL(fileURLWithPath: path), options: .atomic)
}
}
func filter(){
// let imagePath = Constants.documentsDirectory.stringByAppendingPathComponent("filtr/orig2.jpg")
// let inputImage = NSImage(contentsOfFile: imagePath)!
// let inputCiImage = ImageConverter.CIImageFrom(inputImage)
//
// let lutPath = Constants.documentsDirectory.stringByAppendingPathComponent("filtr/strange32.tif")
// let lutImage = NSImage(contentsOfFile: lutPath)!
// let lutData = LUTConverter.cubeDataForLut32(lutImage)
//// let lutData = LUTConverter.cubeDataForLut64(lutImage)
//// let interpolatedLutData = LUTConverter.dataInterpolatedWithIdentity(lutData: lutData,
//// lutDimension: 32,
//// intensity: 0.5)
//
// let colorCubeFilter = CIFilter(name: "CIColorCubeWithColorSpace")!
// colorCubeFilter.setValue(lutData, forKey: "inputCubeData")
// colorCubeFilter.setValue(32, forKey: "inputCubeDimension")
// colorCubeFilter.setValue(CGColorSpaceCreateDeviceRGB(), forKey: "inputColorSpace")
// colorCubeFilter.setValue(inputCiImage, forKey: kCIInputImageKey)
//
// let filteredImage = ImageConverter.NSImageFrom(colorCubeFilter.outputImage!)
//
// let jpegData = ImageConverter.imageDataFrom(filteredImage, compression: 1.0, type: .JPEG)!
// let path = Constants.documentsDirectory.stringByAppendingPathComponent("filtr/edited.jpg")
// try? jpegData.write(to: URL(fileURLWithPath: path), options: .atomic)
// THIS IS THE CORRECT
let effectFilter = EffectFilter(type: .color1)
effectFilter.inputIntensity = 1.0
// let fadeFilter = FadeFilter()
// fadeFilter.intensity = 0.33
let filterStack = FilterStack()
filterStack.effectFilter = effectFilter
//filterStack.fadeFilter = fadeFilter
let imagePath = Constants.documentsDirectory.stringByAppendingPathComponent("filtr/orig4.jpg")
let inputImage = NSImage(contentsOfFile: imagePath)!
let filteredImage = Filtr.process(inputImage, filterStack: filterStack)!
// CREATE JPEG DATA
let jpegData = ImageConverter.imageDataFrom(filteredImage, compression: 1.0, type: .JPEG)!
let path = Constants.documentsDirectory.stringByAppendingPathComponent("filtr/tests/edited.jpg")
let url = URL(fileURLWithPath: path)
try? jpegData.write(to: url, options: .atomic)
}
func testCustomFilter() {
let lutPath = Constants.documentsDirectory.stringByAppendingPathComponent("filtr/otherluts/Z32.tif")
let lutImage = NSImage(contentsOfFile: lutPath)!
let lutData = LUTConverter.cubeDataForLut32(lutImage)!
let effectFilter = EffectFilter(customFilter: lutData, withDimension: .thirtyTwo)
let filterStack = FilterStack()
filterStack.effectFilter = effectFilter
let imagePath = Constants.documentsDirectory.stringByAppendingPathComponent("filtr/orig4.jpg")
let inputImage = NSImage(contentsOfFile: imagePath)!
let filteredImage = Filtr.process(inputImage, filterStack: filterStack)!
let jpegData = ImageConverter.imageDataFrom(filteredImage, compression: 1.0, type: .JPEG)!
let path = Constants.documentsDirectory.stringByAppendingPathComponent("filtr/tests/edited.jpg")
let url = URL(fileURLWithPath: path)
try? jpegData.write(to: url, options: .atomic)
}
}
| mit | 5eb518374c54af722e209741322ea2bb | 41.861111 | 129 | 0.61752 | 5.577108 | false | false | false | false |
recoveryrecord/SurveyNative | SurveyNative/Classes/SurveyDataSource.swift | 1 | 11878 | //
// SurveyDataSource.swift
// Pods
//
// Created by Nora Mullaney on 3/15/17.
//
//
import Foundation
open class SurveyDataSource : NSObject, UITableViewDataSource {
var surveyQuestions : SurveyQuestions
var surveyTheme : SurveyTheme
var tableCellDataDelegate : TableCellDataDelegate
weak var presentationDelegate : UIViewController?
public init(_ surveyQuestions : SurveyQuestions, surveyTheme : SurveyTheme, tableCellDataDelegate : TableCellDataDelegate, presentationDelegate: UIViewController) {
self.surveyQuestions = surveyQuestions
self.surveyTheme = surveyTheme
self.tableCellDataDelegate = tableCellDataDelegate
self.presentationDelegate = presentationDelegate
}
open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = surveyQuestions.type(for: indexPath)
let tableCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath)
return configure(tableCell, for: cellIdentifier, indexPath: indexPath)
/*
If any strangeness happens with cells then uncomment this part as first thing to do with testing. Disables the reusue of cells.
var cell : UITableViewCell?
let surveyBundle = SurveyBundle.bundle
switch cellIdentifier {
case "year_picker":
cell = YearPickerTableViewCell.init(style: UITableViewCellStyle.value1, reuseIdentifier: cellIdentifier)
case "date_picker":
cell = DatePickerTableViewCell.init(style: UITableViewCellStyle.value1, reuseIdentifier: cellIdentifier)
case "option":
cell = UINib(nibName: "OptionTableViewCell", bundle: SurveyBundle.bundle).instantiate(withOwner: tableView, options: nil)[0] as! OptionTableViewCell
case "other_option":
cell = UINib(nibName: "OtherOptionTableViewCell", bundle: surveyBundle).instantiate(withOwner: tableView, options: nil)[0] as! OtherOptionTableViewCell
case "text_field":
cell = UINib(nibName: "TextFieldTableViewCell", bundle: surveyBundle).instantiate(withOwner: tableView, options: nil)[0] as! TextFieldTableViewCell
case "question":
cell = UINib(nibName: "DynamicLabelTableViewCell", bundle: surveyBundle).instantiate(withOwner: tableView, options: nil)[0] as! DynamicLabelTableViewCell
case "segment_select":
cell = UINib(nibName: "SelectSegmentTableViewCell", bundle: surveyBundle).instantiate(withOwner: tableView, options: nil)[0] as! SelectSegmentTableViewCell
case "row_header":
cell = UINib(nibName: "TableRowHeaderTableViewCell", bundle: surveyBundle).instantiate(withOwner: tableView, options: nil)[0] as! TableRowHeaderTableViewCell
case "row_select":
cell = UINib(nibName: "TableRowTableViewCell", bundle: surveyBundle).instantiate(withOwner: tableView, options: nil)[0] as! TableRowTableViewCell
case "dynamic_label_text_field":
cell = UINib(nibName: "DynamicLabelTextFieldTableViewCell", bundle: surveyBundle).instantiate(withOwner: tableView, options: nil)[0] as! DynamicLabelTextFieldTableViewCell
case "add_text_field":
cell = UINib(nibName: "AddTextFieldTableViewCell", bundle: surveyBundle).instantiate(withOwner: tableView, options: nil)[0] as! AddTextFieldTableViewCell
case "submit":
cell = UINib(nibName: "SubmitButtonTableViewCell", bundle: surveyBundle).instantiate(withOwner: tableView, options: nil)[0] as! SubmitButtonTableViewCell
default:
cell = UITableViewCell.init(style: UITableViewCellStyle.value1, reuseIdentifier: cellIdentifier)
}
return configure(cell!, for: cellIdentifier, indexPath: indexPath)
*/
}
func configure(_ tableCell : UITableViewCell, for cellIdentifier: String, indexPath: IndexPath) -> UITableViewCell {
switch cellIdentifier {
case "year_picker":
let cell = (tableCell as! YearPickerTableViewCell)
cell.presentationDelegate = self.presentationDelegate
cell.dataDelegate = self.tableCellDataDelegate
cell.updateId = surveyQuestions.id(for: indexPath)
cell.selectedYear = surveyQuestions.answer(for: indexPath) as! String?
cell.setYearRange(minYear: surveyQuestions.minYear(for: indexPath), maxYear: surveyQuestions.maxYear(for: indexPath), numYears: surveyQuestions.numYears(for: indexPath), sortOrder: surveyQuestions.yearSortOrder(for: indexPath))
cell.initialYear = surveyQuestions.initialYear(for: indexPath)
case "date_picker":
let cell = (tableCell as! DatePickerTableViewCell)
cell.presentationDelegate = self.presentationDelegate
cell.dataDelegate = self.tableCellDataDelegate
cell.updateId = surveyQuestions.id(for: indexPath)
cell.setDateRange(currentDate: surveyQuestions.date(for: indexPath), minDate: surveyQuestions.minDate(for: indexPath), maxDate: surveyQuestions.maxDate(for: indexPath), dateDiff: surveyQuestions.dateDiff(for: indexPath))
cell.selectedDateStr = surveyQuestions.answer(for: indexPath) as! String?
case "option":
let cell = (tableCell as! OptionTableViewCell)
cell.optionLabel?.text = surveyQuestions.text(for: indexPath)
cell.surveyTheme = self.surveyTheme
cell.setSelectionState(surveyQuestions.isOptionSelected(indexPath))
cell.isSingleSelection = !surveyQuestions.isMultiSelect(indexPath)
case "other_option":
let cell = (tableCell as! OtherOptionTableViewCell)
cell.updateId = nil
cell.dataDelegate = self.tableCellDataDelegate
cell.surveyTheme = self.surveyTheme
cell.label?.text = surveyQuestions.text(for: indexPath)
cell.isSingleSelection = !surveyQuestions.isMultiSelect(indexPath)
let selected = surveyQuestions.isOptionSelected(indexPath)
cell.isSelectedOption = selected
if selected {
cell.optionText = surveyQuestions.otherAnswer(for: indexPath)
cell.setSelectionState(true)
} else {
cell.optionText = ""
}
cell.textField?.keyboardType = surveyQuestions.keyboardType(for: indexPath)
cell.shouldShowNextButton = surveyQuestions.showNextButton(for: indexPath)
cell.updateId = surveyQuestions.id(for: indexPath)
cell.validations = surveyQuestions.validations(for: indexPath)
case "text_field":
let cell = (tableCell as! TextFieldTableViewCell)
cell.updateId = nil
cell.dataDelegate = self.tableCellDataDelegate
cell.textFieldLabel?.text = surveyQuestions.text(for: indexPath)
cell.textField?.keyboardType = surveyQuestions.keyboardType(for: indexPath)
cell.maxCharacters = surveyQuestions.maxChars(for: indexPath)
cell.validations = surveyQuestions.validations(for: indexPath)
cell.textFieldText = surveyQuestions.partialAnswer(for: indexPath) as! String?
cell.shouldShowNextButton = surveyQuestions.showNextButton(for: indexPath)
cell.updateId = surveyQuestions.id(for: indexPath)
case "text_area":
let cell = (tableCell as! TextAreaTableViewCell)
cell.updateId = nil
cell.dataDelegate = self.tableCellDataDelegate
cell.myTextArea?.keyboardType = surveyQuestions.keyboardType(for: indexPath)
cell.maxCharacters = surveyQuestions.maxChars(for: indexPath)
cell.validations = surveyQuestions.validations(for: indexPath)
cell.textFieldText = surveyQuestions.partialAnswer(for: indexPath) as! String?
cell.updateId = surveyQuestions.id(for: indexPath)
case "next_button":
let nextButton = UIButtonWithId(type: UIButton.ButtonType.system)
nextButton.setTitle("Next", for: UIControl.State.normal)
let updateId = surveyQuestions.id(for: indexPath)
nextButton.updateId = updateId
nextButton.frame = CGRect(x: 0, y: 0, width: 100, height: 35)
nextButton.addTarget(self, action: #selector(nextButtonTapped(_:)), for: UIControl.Event.touchUpInside)
tableCell.addSubview(nextButton)
tableCell.accessoryView = nextButton
tableCell.selectionStyle = UITableViewCell.SelectionStyle.none
case "question":
(tableCell as! DynamicLabelTableViewCell).dynamicLabel?.text = surveyQuestions.text(for: indexPath)
case "segment_select":
let cell = (tableCell as! SelectSegmentTableViewCell)
cell.updateId = surveyQuestions.id(for: indexPath)
cell.dataDelegate = self.tableCellDataDelegate
cell.values = surveyQuestions.values(for: indexPath)
if let answer = surveyQuestions.answer(for: indexPath) as? String {
cell.setSelectedValue(answer)
}
cell.lowLabel?.text = surveyQuestions.lowTag(for: indexPath)
cell.highLabel?.text = surveyQuestions.highTag(for: indexPath)
case "row_header":
(tableCell as! TableRowHeaderTableViewCell).headers = surveyQuestions.headers(for: indexPath)
case "row_select":
let surveyTheme = self.surveyTheme
let cell = (tableCell as! TableRowTableViewCell)
cell.surveyTheme = surveyTheme
cell.updateId = surveyQuestions.id(for: indexPath)
cell.dataDelegate = self.tableCellDataDelegate
cell.headers = surveyQuestions.headers(for: indexPath)!
cell.question?.text = surveyQuestions.text(for: indexPath)
cell.selectedHeader = surveyQuestions.partialAnswer(for: indexPath) as! String?
case "dynamic_label_text_field":
let cell = (tableCell as! DynamicLabelTextFieldTableViewCell)
cell.dataDelegate = self.tableCellDataDelegate
cell.updateId = surveyQuestions.id(for: indexPath)
cell.presentationDelegate = self.presentationDelegate
cell.labelOptions = surveyQuestions.labelOptions(for: indexPath)
cell.optionsMetadata = surveyQuestions.optionsMetadata(for: indexPath)
cell.currentValue = surveyQuestions.answer(for: indexPath) as? [String : String]
cell.keyboardType = surveyQuestions.keyboardType(for: indexPath)
cell.validations = surveyQuestions.validations(for: indexPath)
case "add_text_field":
let cell = (tableCell as! AddTextFieldTableViewCell)
cell.dataDelegate = self.tableCellDataDelegate
cell.updateId = surveyQuestions.id(for: indexPath)
cell.currentValues = surveyQuestions.answer(for: indexPath) as? [String]
case "submit":
let cell = (tableCell as! SubmitButtonTableViewCell)
cell.dataDelegate = self.tableCellDataDelegate
cell.submitButton?.setTitle(surveyQuestions.submitTitle(), for: .normal)
default:
tableCell.textLabel?.text = surveyQuestions.text(for: indexPath)
tableCell.textLabel?.numberOfLines = 0
tableCell.imageView?.image = surveyQuestions.image(for: indexPath)
tableCell.selectionStyle = UITableViewCell.SelectionStyle.none
}
tableCell.setNeedsLayout()
return tableCell
}
open func numberOfSections(in tableView: UITableView) -> Int {
return surveyQuestions.numberOfSections()
}
open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return surveyQuestions.numberOfRows(for: section)
}
open func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return surveyQuestions.headerText(section: section)
}
@objc open func nextButtonTapped(_ sender: UIButton) {
if let buttonWithId = sender as? UIButtonWithId, let updateId = buttonWithId.updateId {
self.tableCellDataDelegate.markFinished(updateId: updateId)
}
}
}
public class UIButtonWithId: UIButton {
public var updateId: String?
}
| mit | 5ec98e0da06e60c5d619036e1e059c7b | 54.246512 | 236 | 0.717629 | 5.122035 | false | false | false | false |
Kofktu/KofktuSDK | KofktuSDK/Classes/Manager/KeychainManager.swift | 1 | 1247 | //
// KeychainManager.swift
// KofktuSDK
//
// Created by Kofktu on 2017. 1. 1..
// Copyright © 2017년 Kofktu. All rights reserved.
//
import UIKit
import ObjectMapper
import KeychainAccess
public class KeychainManager {
static public let shared = KeychainManager()
public var isSynchronizeWithICloud: Bool {
get { keychain.synchronizable }
set { _ = keychain.synchronizable(newValue) }
}
fileprivate lazy var keychain: Keychain = {
Keychain(service: Bundle.main.bundleIdentifier!)
}()
public func set(string value: String?, for key: String) {
keychain[string: key] = value
}
public func set(data value: Data?, for key: String) {
keychain[data: key] = value
}
public func set<T: BaseMappable>(object: T?, for key: String) {
set(string: object?.toJSONString(), for: key)
}
public func get(string key: String) -> String? {
return keychain[string: key]
}
public func get(data key: String) -> Data? {
return keychain[data: key]
}
public func get<T: BaseMappable>(object key: String) -> T? {
return get(string: key).flatMap { Mapper<T>().map(JSONString: $0) }
}
}
| mit | 6d9e41c462ea18fceaf9b1594401d450 | 24.916667 | 75 | 0.614952 | 4.105611 | false | false | false | false |
Isuru-Nanayakkara/IJProgressView | IJProgressView/IJProgressView/IJProgressView.swift | 1 | 4156 | //
// IJProgressView.swift
// IJProgressView
//
// Created by Isuru Nanayakkara on 1/14/15.
// Copyright (c) 2015 Appex. All rights reserved.
//
import UIKit
/// A simple progress view
open class IJProgressView {
// MARK: - Properities
// MARK: Class Properties
public static let shared = IJProgressView()
// MARK: Instance Properties
/// The background view
public var containerView = UIView()
/// The bounding box for the activity indicator (`activityIndicator`)
public var progressView = UIView()
/// The activity indicator
public var activityIndicator = UIActivityIndicatorView()
/// The background color for `containerView`
public var backgroundColor = UIColor.white.withAlphaComponent(0.3)
/// The background color for the bounding box of the activity indicator (`progressView`)
public var forgroundColor = UIColor(red: 27.0/255.0, green: 27.0/255.0, blue: 27.0/255.0, alpha: 0.7)
/// The size of the bounding box of the activity indicator (`progressView`)
public var size: CGSize {
// Sanity check the value
didSet {
if self.size.height < 0 {
self.size.height = 0
}
if self.size.width < 0 {
self.size.width = 0
}
}
}
/// The style of `activityIndicator`
public var activityStyle: UIActivityIndicatorView.Style = .whiteLarge
private var activeConstraints = [NSLayoutConstraint]()
// MARK: - Initializer
public init() {
self.size = CGSize(width: 80, height: 80)
self.containerView.translatesAutoresizingMaskIntoConstraints = false
self.progressView.clipsToBounds = true
self.progressView.layer.cornerRadius = 10
self.progressView.translatesAutoresizingMaskIntoConstraints = false
self.activityIndicator.translatesAutoresizingMaskIntoConstraints = false
}
// MARK: - Display
/// Adds the progress views to the top most view
open func showProgressView() {
guard let topView = UIApplication.shared.keyWindow?.rootViewController?.view else {
return
}
containerView.backgroundColor = self.backgroundColor
progressView.backgroundColor = self.forgroundColor
activityIndicator.style = self.activityStyle
UIApplication.shared.keyWindow?.addSubview(containerView)
progressView.addSubview(activityIndicator)
containerView.addSubview(progressView)
activeConstraints = [
containerView.heightAnchor.constraint(equalTo: topView.heightAnchor),
containerView.widthAnchor.constraint(equalTo: topView.widthAnchor),
containerView.leadingAnchor.constraint(equalTo: topView.leadingAnchor),
containerView.topAnchor.constraint(equalTo: topView.topAnchor),
progressView.heightAnchor.constraint(equalToConstant: self.size.height),
progressView.widthAnchor.constraint(equalToConstant: self.size.width),
progressView.centerYAnchor.constraint(equalTo: containerView.centerYAnchor),
progressView.centerXAnchor.constraint(equalTo: containerView.centerXAnchor),
activityIndicator.heightAnchor.constraint(equalToConstant: self.size.height),
activityIndicator.widthAnchor.constraint(equalToConstant: self.size.width),
activityIndicator.centerYAnchor.constraint(equalTo: progressView.centerYAnchor),
activityIndicator.centerXAnchor.constraint(equalTo: progressView.centerXAnchor)
]
for constraint in activeConstraints {
constraint.isActive = true
}
activityIndicator.startAnimating()
}
/// Hides the progress views from their superview
open func hideProgressView() {
DispatchQueue.main.async {
self.activityIndicator.stopAnimating()
self.containerView.removeFromSuperview()
for constraint in self.activeConstraints {
constraint.isActive = false
}
self.activeConstraints.removeAll()
}
}
}
| mit | b1d817b8bced8f2d94664dbc6b168acf | 37.12844 | 105 | 0.674206 | 5.548732 | false | false | false | false |
Acidburn0zzz/firefox-ios | StorageTests/TestSQLiteRemoteClientsAndTabs.swift | 1 | 13360 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
@testable import Storage
@testable import Client
import SwiftyJSON
import XCTest
open class MockRemoteClientsAndTabs: RemoteClientsAndTabs {
public let clientsAndTabs: [ClientAndTabs]
public init() {
let now = Date.now()
let client1GUID = Bytes.generateGUID()
let client2GUID = Bytes.generateGUID()
let u11 = URL(string: "http://test.com/test1")!
let tab11 = RemoteTab(clientGUID: client1GUID, URL: u11, title: "Test 1", history: [ ], lastUsed: (now - OneMinuteInMilliseconds), icon: nil)
let u12 = URL(string: "http://test.com/test2")!
let tab12 = RemoteTab(clientGUID: client1GUID, URL: u12, title: "Test 2", history: [], lastUsed: (now - OneHourInMilliseconds), icon: nil)
let tab21 = RemoteTab(clientGUID: client2GUID, URL: u11, title: "Test 1", history: [], lastUsed: (now - OneDayInMilliseconds), icon: nil)
let u22 = URL(string: "http://different.com/test2")!
let tab22 = RemoteTab(clientGUID: client2GUID, URL: u22, title: "Different Test 2", history: [], lastUsed: now + OneHourInMilliseconds, icon: nil)
let client1 = RemoteClient(guid: client1GUID, name: "Test client 1", modified: (now - OneMinuteInMilliseconds), type: "mobile", formfactor: "largetablet", os: "iOS", version: "55.0.1", fxaDeviceId: "fxa1")
let client2 = RemoteClient(guid: client2GUID, name: "Test client 2", modified: (now - OneHourInMilliseconds), type: "desktop", formfactor: "laptop", os: "Darwin", version: "55.0.1", fxaDeviceId: "fxa2")
let localClient = RemoteClient(guid: nil, name: "Test local client", modified: (now - OneMinuteInMilliseconds), type: "mobile", formfactor: "largetablet", os: "iOS", version: "55.0.1", fxaDeviceId: "fxa3")
let localUrl1 = URL(string: "http://test.com/testlocal1")!
let localTab1 = RemoteTab(clientGUID: nil, URL: localUrl1, title: "Local test 1", history: [], lastUsed: (now - OneMinuteInMilliseconds), icon: nil)
let localUrl2 = URL(string: "http://test.com/testlocal2")!
let localTab2 = RemoteTab(clientGUID: nil, URL: localUrl2, title: "Local test 2", history: [], lastUsed: (now - OneMinuteInMilliseconds), icon: nil)
// Tabs are ordered most-recent-first.
self.clientsAndTabs = [ClientAndTabs(client: client1, tabs: [tab11, tab12]),
ClientAndTabs(client: client2, tabs: [tab22, tab21]),
ClientAndTabs(client: localClient, tabs: [localTab1, localTab2])]
}
open func onRemovedAccount() -> Success {
return succeed()
}
open func wipeClients() -> Success {
return succeed()
}
open func wipeRemoteTabs() -> Deferred<Maybe<()>> {
return succeed()
}
open func wipeTabs() -> Success {
return succeed()
}
open func insertOrUpdateClients(_ clients: [RemoteClient]) -> Deferred<Maybe<Int>> {
return deferMaybe(0)
}
open func insertOrUpdateClient(_ client: RemoteClient) -> Deferred<Maybe<Int>> {
return deferMaybe(0)
}
open func insertOrUpdateTabs(_ tabs: [RemoteTab]) -> Deferred<Maybe<Int>> {
return insertOrUpdateTabsForClientGUID(nil, tabs: [RemoteTab]())
}
open func insertOrUpdateTabsForClientGUID(_ clientGUID: String?, tabs: [RemoteTab]) -> Deferred<Maybe<Int>> {
return deferMaybe(-1)
}
open func getRemoteDevices() -> Deferred<Maybe<[RemoteDevice]>> {
return deferMaybe([])
}
open func getClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>> {
return deferMaybe(self.clientsAndTabs)
}
open func getClients() -> Deferred<Maybe<[RemoteClient]>> {
return deferMaybe(self.clientsAndTabs.map { $0.client })
}
public func getClient(guid: GUID) -> Deferred<Maybe<RemoteClient?>> {
return deferMaybe(self.clientsAndTabs.find { clientAndTabs in
return clientAndTabs.client.guid == guid
}?.client)
}
public func getClient(fxaDeviceId: GUID) -> Deferred<Maybe<RemoteClient?>> {
return deferMaybe(self.clientsAndTabs.find { clientAndTabs in
return clientAndTabs.client.fxaDeviceId == fxaDeviceId
}?.client)
}
open func getClientGUIDs() -> Deferred<Maybe<Set<GUID>>> {
return deferMaybe(Set<GUID>(optFilter(self.clientsAndTabs.map { $0.client.guid })))
}
open func getTabsForClientWithGUID(_ guid: GUID?) -> Deferred<Maybe<[RemoteTab]>> {
return deferMaybe(optFilter(self.clientsAndTabs.map { $0.client.guid == guid ? $0.tabs : nil })[0])
}
open func deleteClient(guid: GUID) -> Success { return succeed() }
open func deleteCommands() -> Success { return succeed() }
open func deleteCommands(_ clientGUID: GUID) -> Success { return succeed() }
open func getCommands() -> Deferred<Maybe<[GUID: [SyncCommand]]>> { return deferMaybe([GUID: [SyncCommand]]()) }
open func insertCommand(_ command: SyncCommand, forClients clients: [RemoteClient]) -> Deferred<Maybe<Int>> { return deferMaybe(0) }
open func insertCommands(_ commands: [SyncCommand], forClients clients: [RemoteClient]) -> Deferred<Maybe<Int>> { return deferMaybe(0) }
}
func removeLocalClient(_ a: ClientAndTabs) -> Bool {
return a.client.guid != nil
}
func byGUID(_ a: ClientAndTabs, b: ClientAndTabs) -> Bool {
guard let aGUID = a.client.guid, let bGUID = b.client.guid else {
return false
}
return aGUID < bGUID
}
func byURL(_ a: RemoteTab, b: RemoteTab) -> Bool {
return a.URL.absoluteString < b.URL.absoluteString
}
class SQLRemoteClientsAndTabsTests: XCTestCase {
var clientsAndTabs: SQLiteRemoteClientsAndTabs!
lazy var clients: [ClientAndTabs] = MockRemoteClientsAndTabs().clientsAndTabs
override func setUp() {
let files = MockFiles()
do {
try files.remove("browser.db")
} catch _ {
}
clientsAndTabs = SQLiteRemoteClientsAndTabs(db: BrowserDB(filename: "browser.db", schema: BrowserSchema(), files: files))
}
func testInsertGetClear() {
// Insert some test data.
var remoteDevicesToInsert: [RemoteDevice] = []
// Filter the local client from mock test data.
let remoteClients = clients.filter(removeLocalClient)
for c in remoteClients {
let e = self.expectation(description: "Insert.")
clientsAndTabs.insertOrUpdateClient(c.client).upon {
XCTAssertTrue($0.isSuccess)
e.fulfill()
}
let remoteDevice = RemoteDevice(id: c.client.fxaDeviceId!, name: "FxA Device", type: "desktop", isCurrentDevice: false, lastAccessTime: 12345678, availableCommands: [:])
remoteDevicesToInsert.append(remoteDevice)
clientsAndTabs.insertOrUpdateTabsForClientGUID(c.client.guid, tabs: c.tabs).succeeded()
}
_ = clientsAndTabs.replaceRemoteDevices(remoteDevicesToInsert).succeeded()
let f = self.expectation(description: "Get after insert.")
clientsAndTabs.getClientsAndTabs().upon {
if let got = $0.successValue {
let expected = remoteClients.sorted(by: byGUID)
let actual = got.sorted(by: byGUID)
// This comparison will fail if the order of the tabs changes. We sort the result
// as part of the DB query, so it's not actively sorted in Swift.
XCTAssertEqual(expected, actual)
} else {
XCTFail("Expected clients!")
}
f.fulfill()
}
// Update the test data with a client with new tabs, and one with no tabs.
let client0NewTabs = clients[1].tabs.map { $0.withClientGUID(self.clients[0].client.guid) }
let client1NewTabs: [RemoteTab] = []
let expected = [
ClientAndTabs(client: clients[0].client, tabs: client0NewTabs),
ClientAndTabs(client: clients[1].client, tabs: client1NewTabs),
].sorted(by: byGUID)
func doUpdate(_ guid: String?, tabs: [RemoteTab]) {
let g0 = self.expectation(description: "Update client: \(guid ?? "nil").")
clientsAndTabs.insertOrUpdateTabsForClientGUID(guid, tabs: tabs).upon {
if let rowID = $0.successValue {
XCTAssertTrue(rowID > -1)
} else {
XCTFail("Didn't successfully update.")
}
g0.fulfill()
}
}
doUpdate(clients[0].client.guid, tabs: client0NewTabs)
doUpdate(clients[1].client.guid, tabs: client1NewTabs)
// Also update the local tabs list. It should still not appear in the expected tabs below.
doUpdate(clients[2].client.guid, tabs: client1NewTabs)
let h = self.expectation(description: "Get after update.")
clientsAndTabs.getClientsAndTabs().upon {
if let clients = $0.successValue {
XCTAssertEqual(expected, clients.sorted(by: byGUID))
} else {
XCTFail("Expected clients!")
}
h.fulfill()
}
// Now clear everything, and verify we have no clients or tabs whatsoever.
let i = self.expectation(description: "Clear.")
clientsAndTabs.clear().upon {
XCTAssertTrue($0.isSuccess)
i.fulfill()
}
let j = self.expectation(description: "Get after clear.")
clientsAndTabs.getClientsAndTabs().upon {
if let clients = $0.successValue {
XCTAssertEqual(0, clients.count)
} else {
XCTFail("Expected clients!")
}
j.fulfill()
}
self.waitForExpectations(timeout: 10, handler: nil)
}
func testGetTabsForClient() {
for c in clients {
let e = self.expectation(description: "Insert.")
clientsAndTabs.insertOrUpdateClient(c.client).upon {
XCTAssertTrue($0.isSuccess)
e.fulfill()
}
clientsAndTabs.insertOrUpdateTabsForClientGUID(c.client.guid, tabs: c.tabs).succeeded()
}
let e = self.expectation(description: "Get after insert.")
let ct = clients[0]
clientsAndTabs.getTabsForClientWithGUID(ct.client.guid).upon {
if let got = $0.successValue {
// This comparison will fail if the order of the tabs changes. We sort the result
// as part of the DB query, so it's not actively sorted in Swift.
XCTAssertEqual(ct.tabs.count, got.count)
XCTAssertEqual(ct.tabs.sorted(by: byURL), got.sorted(by: byURL))
} else {
XCTFail("Expected tabs!")
}
e.fulfill()
}
let f = self.expectation(description: "Get after insert.")
let localClient = clients[0]
clientsAndTabs.getTabsForClientWithGUID(localClient.client.guid).upon {
if let got = $0.successValue {
// This comparison will fail if the order of the tabs changes. We sort the result
// as part of the DB query, so it's not actively sorted in Swift.
XCTAssertEqual(localClient.tabs.count, got.count)
XCTAssertEqual(localClient.tabs.sorted(by: byURL), got.sorted(by: byURL))
} else {
XCTFail("Expected tabs!")
}
f.fulfill()
}
self.waitForExpectations(timeout: 10, handler: nil)
}
func testReplaceRemoteDevices() {
let device1 = RemoteDevice(id: "fx1", name: "Device 1", type: "mobile", isCurrentDevice: false, lastAccessTime: 12345678, availableCommands: [:])
let device2 = RemoteDevice(id: "fx2", name: "Device 2 (local)", type: "desktop", isCurrentDevice: true, lastAccessTime: nil, availableCommands: [:])
let device3 = RemoteDevice(id: nil, name: "Device 3 (fauly)", type: "desktop", isCurrentDevice: false, lastAccessTime: 12345678, availableCommands: [:])
let device4 = RemoteDevice(id: "fx4", name: "Device 4 (fauly)", type: nil, isCurrentDevice: false, lastAccessTime: 12345678, availableCommands: [:])
_ = clientsAndTabs.replaceRemoteDevices([device1, device2, device3, device4]).succeeded()
let devices = clientsAndTabs.db.runQuery("SELECT * FROM remote_devices", args: nil, factory: SQLiteRemoteClientsAndTabs.remoteDeviceFactory).value.successValue!.asArray()
XCTAssertEqual(devices.count, 1) // Fauly devices + local device were not inserted.
let device5 = RemoteDevice(id: "fx5", name: "Device 5", type: "mobile", isCurrentDevice: false, lastAccessTime: 12345678, availableCommands: [:])
_ = clientsAndTabs.replaceRemoteDevices([device5]).succeeded()
let newDevices = clientsAndTabs.db.runQuery("SELECT * FROM remote_devices", args: nil, factory: SQLiteRemoteClientsAndTabs.remoteDeviceFactory).value.successValue!.asArray()
XCTAssertEqual(newDevices.count, 1) // replaceRemoteDevices wipes the whole list before inserting.
}
}
| mpl-2.0 | f1bb3778e9d31472251dc29b6f48a7c4 | 44.288136 | 213 | 0.633608 | 4.56596 | false | true | false | false |
nathawes/swift | test/IRGen/prespecialized-metadata/struct-extradata-run.swift | 3 | 3571 | // RUN: %empty-directory(%t)
// RUN: %clang -c -v %target-cc-options -g -O0 -isysroot %sdk %S/Inputs/extraDataFields.cpp -o %t/extraDataFields.o -I %clang-include-dir -I %swift_src_root/include/ -I %llvm_src_root/include -I %llvm_obj_root/include -L %clang-include-dir/../lib/swift/macosx
// RUN: %target-build-swift -c %S/Inputs/struct-extra-data-fields.swift -emit-library -emit-module -module-name ExtraDataFieldsNoTrailingFlags -target %module-target-future -Xfrontend -disable-generic-metadata-prespecialization -emit-module-path %t/ExtraDataFieldsNoTrailingFlags.swiftmodule -o %t/%target-library-name(ExtraDataFieldsNoTrailingFlags)
// RUN: %target-build-swift -c %S/Inputs/struct-extra-data-fields.swift -emit-library -emit-module -module-name ExtraDataFieldsTrailingFlags -target %module-target-future -Xfrontend -prespecialize-generic-metadata -emit-module-path %t/ExtraDataFieldsTrailingFlags.swiftmodule -o %t/%target-library-name(ExtraDataFieldsTrailingFlags)
// RUN: %target-build-swift -v %mcp_opt %s %t/extraDataFields.o -import-objc-header %S/Inputs/extraDataFields.h -Xfrontend -disable-generic-metadata-prespecialization -target %module-target-future -lc++ -L %clang-include-dir/../lib/swift/macosx -sdk %sdk -o %t/main -I %t -L %t -lExtraDataFieldsTrailingFlags -lExtraDataFieldsNoTrailingFlags -module-name main
// RUN: %target-codesign %t/main
// RUN: %target-run %t/main | %FileCheck %s
// REQUIRES: OS=macosx
// REQUIRES: executable_test
// UNSUPPORTED: use_os_stdlib
// UNSUPPORTED: swift_test_mode_optimize
// UNSUPPORTED: swift_test_mode_optimize_size
func ptr<T>(to ty: T.Type) -> UnsafeMutableRawPointer {
UnsafeMutableRawPointer(mutating: unsafePointerToMetadata(of: ty))!
}
func unsafePointerToMetadata<T>(of ty: T.Type) -> UnsafePointer<T.Type> {
unsafeBitCast(ty, to: UnsafePointer<T.Type>.self)
}
import ExtraDataFieldsNoTrailingFlags
let one = completeMetadata(
ptr(
to: ExtraDataFieldsNoTrailingFlags.FixedFieldOffsets<Void>.self
)
)
// CHECK: nil
print(
trailingFlagsForStructMetadata(
one
)
)
guard let oneOffsets = fieldOffsetsForStructMetadata(one) else {
fatalError("no field offsets")
}
// CHECK-NEXT: 0
print(oneOffsets.advanced(by: 0).pointee)
// CHECK-NEXT: 8
print(oneOffsets.advanced(by: 1).pointee)
let two = completeMetadata(
ptr(
to: ExtraDataFieldsNoTrailingFlags.DynamicFieldOffsets<Int32>.self
)
)
// CHECK-NEXT: nil
print(
trailingFlagsForStructMetadata(
two
)
)
guard let twoOffsets = fieldOffsetsForStructMetadata(two) else {
fatalError("no field offsets")
}
// CHECK-NEXT: 0
print(twoOffsets.advanced(by: 0).pointee)
// CHECK-NEXT: 4
print(twoOffsets.advanced(by: 1).pointee)
import ExtraDataFieldsTrailingFlags
let three = completeMetadata(
ptr(
to: ExtraDataFieldsTrailingFlags.FixedFieldOffsets<Void>.self
)
)
// CHECK-NEXT: 0
print(
trailingFlagsForStructMetadata(
three
)!.pointee
)
guard let threeOffsets = fieldOffsetsForStructMetadata(three) else {
fatalError("no field offsets")
}
// CHECK-NEXT: 0
print(threeOffsets.advanced(by: 0).pointee)
// CHECK-NEXT: 8
print(threeOffsets.advanced(by: 1).pointee)
let four = completeMetadata(
ptr(
to: ExtraDataFieldsTrailingFlags.DynamicFieldOffsets<Int32>.self
)
)
// CHECK-NEXT: 0
print(
trailingFlagsForStructMetadata(
four
)!.pointee
)
guard let fourOffsets = fieldOffsetsForStructMetadata(four) else {
fatalError("no field offsets")
}
// CHECK-NEXT: 0
print(fourOffsets.advanced(by: 0).pointee)
// CHECK-NEXT: 4
print(fourOffsets.advanced(by: 1).pointee)
| apache-2.0 | 078709281741253642fd57e2f51f22a2 | 29.008403 | 359 | 0.754691 | 3.525173 | false | false | false | false |
Electrode-iOS/ELState | ELState/Subscriber.swift | 1 | 976 | //
// Subscriber.swift
// ELState
//
// Created by Brandon Sneed on 3/27/16.
// Copyright © 2016 Electrode-iOS. All rights reserved.
//
import Foundation
public protocol BaseSubscriber: AnyObject {
func _newState(state: State, store: Store)
}
public protocol Subscriber: BaseSubscriber, Equatable, Hashable {
associatedtype StateType
func newState(state: StateType, store: Store)
}
public extension Subscriber {
func _newState(state: State, store: Store) {
newState(state as! StateType, store: store)
}
}
public extension BaseSubscriber {
var hashValue: Int {
return 0
}
}
// MARK: Equatable
/*public func ==<T: BaseSubscriber>(lhs: T, rhs: T) -> Bool {
return lhs.hashValue == rhs.hashValue
}*/
/*public func !=<T: Subscriber>(lhs: T, rhs: T) -> Bool {
return lhs.hashValue != rhs.hashValue
}*/
/*public func !=<T: BaseSubscriber>(lhs: T, rhs: T) -> Bool {
return lhs.hashValue != rhs.hashValue
}*/
| mit | 1780035a4c3a0ac2b69313b6601b906a | 20.195652 | 65 | 0.659487 | 3.764479 | false | false | false | false |
YaQiongLu/LYQdyzb | LYQdyzb/LYQdyzb/Classes/Main/View/PageContentView.swift | 1 | 6543 | //
// PageContentView.swift
// LYQdyzb
//
// Created by 芦亚琼 on 2017/6/29.
// Copyright © 2017年 芦亚琼. All rights reserved.
//
import UIKit
protocol PageContentViewDelegate : class {
func pageContentView(contentView : PageContentView, progress : CGFloat, sourceIndex : Int, targetIndex : Int)
}
fileprivate let ContentCellID = "ContentCellID"
class PageContentView: UIView {
//MARK:- 定义属性
fileprivate var childVcs : [UIViewController]
fileprivate weak var parentViewController : UIViewController?//weak防止循环引用
fileprivate var startOffsetX : CGFloat = 0;//记录属性
fileprivate var isForbidScrollDelegate : Bool = false
weak var delegate : PageContentViewDelegate?
//MARk: - 懒加载属性
//[weak self]在闭包中防止循环引用
fileprivate lazy var collectionView : UICollectionView = {[weak self] in
//1.创建layout 流水布局
let layout = UICollectionViewFlowLayout()
layout.itemSize = (self?.bounds.size)!
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
//2.创建UICollectionView
let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
collectionView.showsHorizontalScrollIndicator = false //水平滚动指示器
collectionView.isPagingEnabled = true //分页
collectionView.bounces = false //反弹效果
//3.遵循collectionView协议
collectionView.dataSource = self
collectionView.delegate = self as! UICollectionViewDelegate
//4.注册cell
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: ContentCellID)
return collectionView
}()
//MARK:- 自定义构造函数
init(frame: CGRect, childVcs: [UIViewController], parentViewController: UIViewController?){
self.childVcs = childVcs
self.parentViewController = parentViewController
super.init(frame: frame)
//设置UI
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//MARK: - 设置UI界面
extension PageContentView{
fileprivate func setupUI(){
//1.将所有子控制器添加到父控制器中
for childVc in childVcs {
parentViewController?.addChildViewController(childVc)
}
//2.添加UICollectionView,用于在Cell中存放控制器的View
addSubview(collectionView)
collectionView.frame = bounds
}
}
//MARK: -遵循UICollectionViewDataSource
extension PageContentView : UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return childVcs.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//1.创建cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier:ContentCellID, for: indexPath)
//2.0 防止cell循环引用,先把contentView的subviews移除,避免添加多次
for view in cell.contentView.subviews {
view.removeFromSuperview()
}
//2.1 给cell设置内容
let childVC = childVcs[indexPath.item]
childVC.view.frame = cell.contentView.bounds
cell.contentView.addSubview(childVC.view)
// frame: 该view在父view坐标系统中的位置和大小。(参照点是,父亲的坐标系统)
// bounds:该view在本地坐标系统中的位置和大小。(参照点是,本地坐标系统,就相当于ViewB自己的坐标系统,以0,0点为起点)
//3.返回cell
return cell
}
}
//MARK: -遵循UICollectionViewDelegate
extension PageContentView : UICollectionViewDelegate{
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
isForbidScrollDelegate = false
startOffsetX = scrollView.contentOffset.x
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
//0.判断是否是点击事件
if isForbidScrollDelegate { return }
//1.定义获取需要的数据
var progress : CGFloat = 0
var sourceIndex : Int = 0
var targetIndex : Int = 0
//2.判断是左滑还是右滑
let currentOffsetX = scrollView.contentOffset.x
let scrollViewW = scrollView.bounds.width
if currentOffsetX > startOffsetX {//左滑
//1.计算progress
progress = currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW)
//2.计算sourceIndex
sourceIndex = Int(currentOffsetX / scrollViewW)
//3.计算targetIndex
targetIndex = sourceIndex + 1
if targetIndex >= childVcs.count {
targetIndex = childVcs.count - 1
}
//4.如果完全滑过去
if currentOffsetX - startOffsetX == scrollViewW {
progress = 1
targetIndex = sourceIndex
}
}else{//右滑
//1.计算progress
progress = 1 - (currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW))
//3.计算targetIndex
targetIndex = Int(currentOffsetX / scrollViewW)
//2.计算sourceIndex
sourceIndex = targetIndex + 1
if sourceIndex >= childVcs.count {
sourceIndex = childVcs.count - 1
}
}
//3.用代理将progress、sourceIndex、targetIndex传给titleView
delegate?.pageContentView(contentView: self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
// print(progress,sourceIndex,targetIndex)
}
}
//MARK:- 设置对外暴露的方法
extension PageContentView{
func setCurrentIndex(currentIndex : Int) {
isForbidScrollDelegate = true
//随着title的点击,滚动到对应页面
let offsetX = CGFloat(currentIndex) * collectionView.frame.size.width
collectionView.setContentOffset(CGPoint(x:offsetX, y:0), animated: false)
}
}
| mit | 24eb0de6e4a23251f71fe0fdee614abd | 29.387755 | 124 | 0.629449 | 5.454212 | false | false | false | false |
IT-Department-Projects/POP-II | iOS App/notesNearby_iOS_finalUITests/notesNearby_iOS_final/ViewController.swift | 2 | 4437 | import UIKit
import CoreLocation
import Firebase
import FirebaseDatabase
import FirebaseStorage
import CoreLocation
import SVProgressHUD
class ViewController: UIViewController, ARDataSource
{
var activityIndicator:UIActivityIndicatorView=UIActivityIndicatorView()
@IBOutlet var viewLoad: UIView!
@IBOutlet var button: UIButton!
var posts = [Firebasepull]()
override func viewDidLoad()
{
super.viewDidLoad()
SVProgressHUD.show(withStatus: "Loading")
UIApplication.shared.beginIgnoringInteractionEvents()
DispatchQueue.global(qos:.background).async {
do{
let databaseRef = FIRDatabase.database().reference()
databaseRef.child("posts").queryOrderedByKey().observe(.childAdded, with: {(snapshot) in
print(snapshot)
if let dictionary = snapshot.value as? [String:AnyObject]{
let title1 = dictionary["title"] as? String
let note = dictionary["note"] as? String
let latitude = dictionary["latitude"] as? Double
let longitude = dictionary["longitude"] as? Double
let image_url=dictionary["image_url"] as? String
let key=dictionary["key"] as? String
self.posts.insert(Firebasepull(title1:title1,note:note,latitude:latitude,longitude:longitude,image_url:image_url,key:key), at: 0)
}
}, withCancel: nil)
print("*********")
}
catch{
print("error")
}
}
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(5), execute: {
SVProgressHUD.dismiss()
UIApplication.shared.endIgnoringInteractionEvents()
})
}
/// Creates random annotations around predefined center point and presents ARViewController modally
func showARViewController()
{
// Check if device has hardware needed for augmented reality
let result = ARViewController.createCaptureSession()
if result.error != nil
{
let message = result.error?.userInfo["description"] as? String
let alertView = UIAlertView(title: "Error", message: message, delegate: nil, cancelButtonTitle: "Close")
alertView.show()
return
}
let dummyAnnotations = self.getDummyAnnotations()
// Present ARViewController
let arViewController = ARViewController()
arViewController.dataSource = self
arViewController.maxVisibleAnnotations = 100
arViewController.headingSmoothingFactor = 0.05
arViewController.setAnnotations(dummyAnnotations)
self.present(arViewController, animated: true, completion: nil)
}
/// This method is called by ARViewController, make sure to set dataSource property.
func ar(_ arViewController: ARViewController, viewForAnnotation: ARAnnotation) -> ARAnnotationView
{
// Annotation views should be lightweight views, try to avoid xibs and autolayout all together.
let annotationView = TestAnnotationView()
annotationView.frame = CGRect(x: 0,y: 0,width: 150,height: 50)
return annotationView;
}
fileprivate func getDummyAnnotations() -> Array<ARAnnotation>
{
UIApplication.shared.ignoreSnapshotOnNextApplicationLaunch()
var annotations: [ARAnnotation] = []
var i:Int = 0
while(i < self.posts.count){
let annotation = ARAnnotation()
annotation.location=CLLocation(latitude: self.posts[i].latitude, longitude: self.posts[i].longitude)
annotation.title = self.posts[i].title1
annotation.note=self.posts[i].note
annotation.image_url=self.posts[i].image_url
annotations.append(annotation)
i=i+1
}
SVProgressHUD.dismiss()
UIApplication.shared.endIgnoringInteractionEvents()
return annotations
}
@IBAction func buttonTap(_ sender: AnyObject)
{
showARViewController()
}
}
| mit | 1437f8efc5b5a59f59053cb6f835c81a | 34.782258 | 153 | 0.592968 | 5.754864 | false | false | false | false |
actorapp/actor-platform | actor-sdk/sdk-core-ios/ActorSDK/Sources/Utils/AATools.swift | 3 | 3256 | //
// Copyright (c) 2014-2016 Actor LLC. <https://actor.im>
//
import Foundation
import zipzap
class AATools {
class func copyFileCommand(_ from: String, to: String) -> ACCommand {
return CopyCommand(from: from, to: to)
}
class func zipDirectoryCommand(_ from: String, to: String) -> ACCommand {
return ZipCommand(dir: from, to: to)
}
class func isValidEmail(_ testStr:String) -> Bool {
let emailRegEx = "^[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailTest.evaluate(with: testStr)
}
}
private class ZipCommand: BackgroundCommand {
fileprivate let dir: String
fileprivate let to: String
init(dir: String, to: String) {
self.dir = dir
self.to = to
}
fileprivate override func backgroundTask() throws {
let rootPath = URL(fileURLWithPath: dir).lastPathComponent
let zip = try ZZArchive(url: URL(fileURLWithPath: to), options: [ZZOpenOptionsCreateIfMissingKey: true])
let subs = try FileManager.default.subpathsOfDirectory(atPath: dir)
var entries = [ZZArchiveEntry]()
for p in subs {
// Full path of object
let fullPath = "\(dir)/\(p)"
let destPath = "\(rootPath)/\(p)"
// Check path type: directory or file?
var isDir : ObjCBool = false
if FileManager.default.fileExists(atPath: fullPath, isDirectory: &isDir) {
if !isDir.boolValue {
// If file write file
entries.append(ZZArchiveEntry(fileName: destPath, compress: false, dataBlock: { (error) -> Data! in
// TODO: Error handling?
return (try! Data(contentsOf: URL(fileURLWithPath: fullPath)))
}))
} else {
// Create directory
// Uncommenting this line causes unpack errors
// Also zip format doesn't have file paths
// entries.append(ZZArchiveEntry(directoryName: destPath))
}
}
}
// Write entries
try zip.updateEntries(entries)
}
}
private class CopyCommand: BackgroundCommand {
let from: String
let to: String
init(from: String, to: String) {
self.from = from
self.to = to
}
fileprivate override func backgroundTask() throws {
try FileManager.default.copyItem(atPath: from, toPath: to)
}
}
class BackgroundCommand: NSObject, ACCommand {
func start(with callback: ACCommandCallback!) {
DispatchQueue.global(priority: DispatchQueue.GlobalQueuePriority.default).async { () -> Void in
do {
try self.backgroundTask()
callback.onResult(nil)
} catch {
callback.onError(nil)
}
}
}
func backgroundTask() throws {
}
}
| agpl-3.0 | 69db7d53a6d34e622e66b644d8f28f96 | 28.6 | 119 | 0.530713 | 5.001536 | false | false | false | false |
DrGo/LearningSwift | PLAYGROUNDS/APPLE/Balloons.playground/section-11.swift | 2 | 517 | let fireBalloon: (SKSpriteNode, SKNode) -> Void = { balloon, cannon in
let impulseMagnitude: CGFloat = 70.0
let xComponent = cos(cannon.zRotation) * impulseMagnitude
let yComponent = sin(cannon.zRotation) * impulseMagnitude
let impulseVector = CGVector(dx: xComponent, dy: yComponent)
balloon.physicsBody!.applyImpulse(impulseVector)
}
func fireCannon(cannon: SKNode) {
let balloon = createRandomBalloon()
displayBalloon(balloon, cannon)
fireBalloon(balloon, cannon)
}
| gpl-3.0 | ec0473e834401a19e060808a75796a24 | 31.3125 | 70 | 0.717602 | 4.136 | false | false | false | false |
aipeople/PokeIV | Pods/PGoApi/PGoApi/Classes/PGoApiRequest.swift | 1 | 31081 | //
// PgoApi.swift
// pgomap
//
// Based on https://github.com/tejado/pgoapi/blob/master/pgoapi/pgoapi.py
//
// Created by Luke Sapan on 7/20/16.
// Copyright © 2016 Coadstal. All rights reserved.
//
import Foundation
import ProtocolBuffers
public struct PGoApiMethod {
let id: Pogoprotos.Networking.Requests.RequestType
let message: GeneratedMessage
let parser: NSData -> GeneratedMessage
}
public struct PGoApiResponse {
public let response: GeneratedMessage
public let subresponses: [GeneratedMessage]
}
public struct PGoLocation {
var lat:Double = 0
var long:Double = 0
var alt:Double? = nil
}
public class PGoApiRequest {
public var Location = PGoLocation()
private var auth: PGoAuth?
public var methodList: [PGoApiMethod] = []
public init(auth: PGoAuth? = nil) {
if (auth != nil) {
self.auth = auth
}
}
public func makeRequest(intent: PGoApiIntent, delegate: PGoApiDelegate?) {
// analogous to call in pgoapi.py
if methodList.count == 0 {
print("makeRequest() called without any methods in methodList.")
return
}
if self.auth != nil {
if !self.auth!.loggedIn {
print("makeRequest() called without being logged in.")
return
}
} else {
print("makeRequest() called without initializing auth.")
return
}
let request = PGoRpcApi(subrequests: methodList, intent: intent, auth: self.auth!, api: self, delegate: delegate)
request.request()
methodList.removeAll()
}
public func setLocation(latitude: Double, longitude: Double, altitude: Double? = nil) {
Location.lat = latitude
Location.long = longitude
if altitude != nil {
Location.alt = altitude!
}
}
public func simulateAppStart() {
getPlayer()
getHatchedEggs()
getInventory()
checkAwardedBadges()
downloadSettings()
}
public func updatePlayer() {
let messageBuilder = Pogoprotos.Networking.Requests.Messages.PlayerUpdateMessage.Builder()
messageBuilder.latitude = Location.lat
messageBuilder.longitude = Location.long
methodList.append(PGoApiMethod(id: .PlayerUpdate, message: try! messageBuilder.build(), parser: { data in
return try! Pogoprotos.Networking.Responses.PlayerUpdateResponse.parseFromData(data)
}))
}
public func getPlayer() {
let messageBuilder = Pogoprotos.Networking.Requests.Messages.GetPlayerMessage.Builder()
methodList.append(PGoApiMethod(id: .GetPlayer, message: try! messageBuilder.build(), parser: { data in
return try! Pogoprotos.Networking.Responses.GetPlayerResponse.parseFromData(data)
}))
}
public func getInventory(lastTimestampMs: Int64? = nil) {
let messageBuilder = Pogoprotos.Networking.Requests.Messages.GetInventoryMessage.Builder()
if lastTimestampMs != nil {
messageBuilder.lastTimestampMs = lastTimestampMs!
}
methodList.append(PGoApiMethod(id: .GetInventory, message: try! messageBuilder.build(), parser: { data in
return try! Pogoprotos.Networking.Responses.GetInventoryResponse.parseFromData(data)
}))
}
public func downloadSettings() {
let messageBuilder = Pogoprotos.Networking.Requests.Messages.DownloadSettingsMessage.Builder()
messageBuilder.hash = PGoSetting.SettingsHash
methodList.append(PGoApiMethod(id: .DownloadSettings, message: try! messageBuilder.build(), parser: { data in
return try! Pogoprotos.Networking.Responses.DownloadSettingsResponse.parseFromData(data)
}))
}
public func downloadItemTemplates() {
let messageBuilder = Pogoprotos.Networking.Requests.Messages.DownloadItemTemplatesMessage.Builder()
methodList.append(PGoApiMethod(id: .DownloadItemTemplates, message: try! messageBuilder.build(), parser: { data in
return try! Pogoprotos.Networking.Responses.DownloadItemTemplatesResponse.parseFromData(data)
}))
}
public func downloadRemoteConfigVersion(deviceModel: String, deviceManufacturer: String, locale: String, appVersion: UInt32) {
let messageBuilder = Pogoprotos.Networking.Requests.Messages.DownloadRemoteConfigVersionMessage.Builder()
messageBuilder.platform = .Ios
messageBuilder.deviceModel = deviceModel
messageBuilder.deviceManufacturer = deviceManufacturer
messageBuilder.locale = locale
messageBuilder.appVersion = appVersion
methodList.append(PGoApiMethod(id: .DownloadRemoteConfigVersion, message: try! messageBuilder.build(), parser: { data in
return try! Pogoprotos.Networking.Responses.DownloadRemoteConfigVersionResponse.parseFromData(data)
}))
}
public func fortSearch(fortId: String, fortLatitude: Double, fortLongitude: Double) {
let messageBuilder = Pogoprotos.Networking.Requests.Messages.FortSearchMessage.Builder()
messageBuilder.fortId = fortId
messageBuilder.fortLatitude = fortLatitude
messageBuilder.fortLongitude = fortLongitude
messageBuilder.playerLatitude = Location.lat
messageBuilder.playerLongitude = Location.long
methodList.append(PGoApiMethod(id: .FortSearch, message: try! messageBuilder.build(), parser: { data in
return try! Pogoprotos.Networking.Responses.FortSearchResponse.parseFromData(data)
}))
}
public func encounterPokemon(encounterId: UInt64, spawnPointId: String) {
let messageBuilder = Pogoprotos.Networking.Requests.Messages.EncounterMessage.Builder()
messageBuilder.encounterId = encounterId
messageBuilder.spawnPointId = spawnPointId
messageBuilder.playerLatitude = Location.lat
messageBuilder.playerLongitude = Location.long
methodList.append(PGoApiMethod(id: .Encounter, message: try! messageBuilder.build(), parser: { data in
return try! Pogoprotos.Networking.Responses.EncounterResponse.parseFromData(data)
}))
}
public func catchPokemon(encounterId: UInt64, spawnPointId: String, pokeball: Pogoprotos.Inventory.Item.ItemId, hitPokemon: Bool, normalizedReticleSize: Double, normalizedHitPosition: Double, spinModifier: Double) {
let messageBuilder = Pogoprotos.Networking.Requests.Messages.CatchPokemonMessage.Builder()
messageBuilder.encounterId = encounterId
messageBuilder.spawnPointId = spawnPointId
messageBuilder.pokeball = pokeball
messageBuilder.hitPokemon = hitPokemon
messageBuilder.normalizedReticleSize = normalizedReticleSize
messageBuilder.normalizedHitPosition = normalizedHitPosition
messageBuilder.spinModifier = spinModifier
methodList.append(PGoApiMethod(id: .CatchPokemon, message: try! messageBuilder.build(), parser: { data in
return try! Pogoprotos.Networking.Responses.CatchPokemonResponse.parseFromData(data)
}))
}
public func fortDetails(fortId: String, fortLatitude: Double, fortLongitude: Double) {
let messageBuilder = Pogoprotos.Networking.Requests.Messages.FortDetailsMessage.Builder()
messageBuilder.fortId = fortId
messageBuilder.latitude = fortLatitude
messageBuilder.longitude = fortLongitude
methodList.append(PGoApiMethod(id: .FortDetails, message: try! messageBuilder.build(), parser: { data in
return try! Pogoprotos.Networking.Responses.FortDetailsResponse.parseFromData(data)
}))
}
public func generateS2Cells(lat: Double, long: Double) -> Array<UInt64> {
let cell = S2CellId(p: S2LatLon(latDegrees: lat, lonDegrees: long).toPoint())
var cells: [UInt64] = []
var currentCell = cell
for _ in 0..<10 {
currentCell = currentCell.prev()
cells.insert(currentCell.id, atIndex: 0)
}
cells.append(cell.id)
currentCell = cell
for _ in 0..<10 {
currentCell = currentCell.next()
cells.append(currentCell.id)
}
return cells
}
public func getMapObjects(cellIds: Array<UInt64>? = nil, sinceTimestampMs: Array<Int64>? = nil) {
let messageBuilder = Pogoprotos.Networking.Requests.Messages.GetMapObjectsMessage.Builder()
messageBuilder.latitude = Location.lat
messageBuilder.longitude = Location.long
if sinceTimestampMs != nil {
messageBuilder.sinceTimestampMs = sinceTimestampMs!
} else {
var timeStamps: Array<Int64> = []
if cellIds != nil {
for _ in cellIds! {
timeStamps.append(0)
}
messageBuilder.sinceTimestampMs = timeStamps
} else {
messageBuilder.sinceTimestampMs = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
}
}
if cellIds != nil {
messageBuilder.cellId = cellIds!
} else {
let cells = generateS2Cells(Location.lat, long: Location.long)
messageBuilder.cellId = cells
}
methodList.append(PGoApiMethod(id: .GetMapObjects, message: try! messageBuilder.build(), parser: { data in
return try! Pogoprotos.Networking.Responses.GetMapObjectsResponse.parseFromData(data)
}))
}
public func fortDeployPokemon(fortId: String, pokemonId:UInt64) {
let messageBuilder = Pogoprotos.Networking.Requests.Messages.FortDeployPokemonMessage.Builder()
messageBuilder.fortId = fortId
messageBuilder.pokemonId = pokemonId
messageBuilder.playerLatitude = Location.lat
messageBuilder.playerLongitude = Location.long
methodList.append(PGoApiMethod(id: .FortDeployPokemon, message: try! messageBuilder.build(), parser: { data in
return try! Pogoprotos.Networking.Responses.FortDeployPokemonResponse.parseFromData(data)
}))
}
public func fortRecallPokemon(fortId: String, pokemonId:UInt64) {
let messageBuilder = Pogoprotos.Networking.Requests.Messages.FortRecallPokemonMessage.Builder()
messageBuilder.fortId = fortId
messageBuilder.pokemonId = pokemonId
messageBuilder.playerLatitude = Location.lat
messageBuilder.playerLongitude = Location.long
methodList.append(PGoApiMethod(id: .FortRecallPokemon, message: try! messageBuilder.build(), parser: { data in
return try! Pogoprotos.Networking.Responses.FortRecallPokemonResponse.parseFromData(data)
}))
}
public func releasePokemon(pokemonId:UInt64) {
let messageBuilder = Pogoprotos.Networking.Requests.Messages.ReleasePokemonMessage.Builder()
messageBuilder.pokemonId = pokemonId
methodList.append(PGoApiMethod(id: .ReleasePokemon, message: try! messageBuilder.build(), parser: { data in
return try! Pogoprotos.Networking.Responses.ReleasePokemonResponse.parseFromData(data)
}))
}
public func useItemPotion(itemId: Pogoprotos.Inventory.Item.ItemId, pokemonId:UInt64) {
let messageBuilder = Pogoprotos.Networking.Requests.Messages.UseItemPotionMessage.Builder()
messageBuilder.itemId = itemId
messageBuilder.pokemonId = pokemonId
methodList.append(PGoApiMethod(id: .UseItemPotion, message: try! messageBuilder.build(), parser: { data in
return try! Pogoprotos.Networking.Responses.UseItemPotionResponse.parseFromData(data)
}))
}
public func useItemCapture(itemId: Pogoprotos.Inventory.Item.ItemId, encounterId:UInt64, spawnPointId: String) {
let messageBuilder = Pogoprotos.Networking.Requests.Messages.UseItemCaptureMessage.Builder()
messageBuilder.itemId = itemId
messageBuilder.encounterId = encounterId
messageBuilder.spawnPointId = spawnPointId
methodList.append(PGoApiMethod(id: .UseItemCapture, message: try! messageBuilder.build(), parser: { data in
return try! Pogoprotos.Networking.Responses.UseItemCaptureResponse.parseFromData(data)
}))
}
public func useItemRevive(itemId: Pogoprotos.Inventory.Item.ItemId, pokemonId: UInt64) {
let messageBuilder = Pogoprotos.Networking.Requests.Messages.UseItemReviveMessage.Builder()
messageBuilder.itemId = itemId
messageBuilder.pokemonId = pokemonId
methodList.append(PGoApiMethod(id: .UseItemRevive, message: try! messageBuilder.build(), parser: { data in
return try! Pogoprotos.Networking.Responses.UseItemReviveResponse.parseFromData(data)
}))
}
public func getPlayerProfile(playerName: String) {
let messageBuilder = Pogoprotos.Networking.Requests.Messages.GetPlayerProfileMessage.Builder()
messageBuilder.playerName = playerName
methodList.append(PGoApiMethod(id: .GetPlayerProfile, message: try! messageBuilder.build(), parser: { data in
return try! Pogoprotos.Networking.Responses.GetPlayerProfileResponse.parseFromData(data)
}))
}
public func evolvePokemon(pokemonId: UInt64) {
let messageBuilder = Pogoprotos.Networking.Requests.Messages.EvolvePokemonMessage.Builder()
messageBuilder.pokemonId = pokemonId
methodList.append(PGoApiMethod(id: .EvolvePokemon, message: try! messageBuilder.build(), parser: { data in
return try! Pogoprotos.Networking.Responses.EvolvePokemonResponse.parseFromData(data)
}))
}
public func getHatchedEggs() {
let messageBuilder = Pogoprotos.Networking.Requests.Messages.GetHatchedEggsMessage.Builder()
methodList.append(PGoApiMethod(id: .GetHatchedEggs, message: try! messageBuilder.build(), parser: { data in
return try! Pogoprotos.Networking.Responses.GetHatchedEggsResponse.parseFromData(data)
}))
}
public func encounterTutorialComplete(pokemonId: Pogoprotos.Enums.PokemonId) {
let messageBuilder = Pogoprotos.Networking.Requests.Messages.EncounterTutorialCompleteMessage.Builder()
messageBuilder.pokemonId = pokemonId
methodList.append(PGoApiMethod(id: .EncounterTutorialComplete, message: try! messageBuilder.build(), parser: { data in
return try! Pogoprotos.Networking.Responses.EncounterTutorialCompleteResponse.parseFromData(data)
}))
}
public func levelUpRewards(level:Int32) {
let messageBuilder = Pogoprotos.Networking.Requests.Messages.LevelUpRewardsMessage.Builder()
messageBuilder.level = level
methodList.append(PGoApiMethod(id: .LevelUpRewards, message: try! messageBuilder.build(), parser: { data in
return try! Pogoprotos.Networking.Responses.LevelUpRewardsResponse.parseFromData(data)
}))
}
public func checkAwardedBadges() {
let messageBuilder = Pogoprotos.Networking.Requests.Messages.CheckAwardedBadgesMessage.Builder()
methodList.append(PGoApiMethod(id: .CheckAwardedBadges, message: try! messageBuilder.build(), parser: { data in
return try! Pogoprotos.Networking.Responses.CheckAwardedBadgesResponse.parseFromData(data)
}))
}
public func useItemGym(itemId: Pogoprotos.Inventory.Item.ItemId, gymId: String) {
let messageBuilder = Pogoprotos.Networking.Requests.Messages.UseItemGymMessage.Builder()
messageBuilder.itemId = itemId
messageBuilder.gymId = gymId
messageBuilder.playerLatitude = Location.lat
messageBuilder.playerLongitude = Location.long
methodList.append(PGoApiMethod(id: .UseItemGym, message: try! messageBuilder.build(), parser: { data in
return try! Pogoprotos.Networking.Responses.UseItemGymResponse.parseFromData(data)
}))
}
public func getGymDetails(gymId: String, gymLatitude: Double, gymLongitude: Double) {
let messageBuilder = Pogoprotos.Networking.Requests.Messages.GetGymDetailsMessage.Builder()
messageBuilder.gymId = gymId
messageBuilder.playerLatitude = Location.lat
messageBuilder.playerLongitude = Location.long
messageBuilder.gymLatitude = gymLatitude
messageBuilder.gymLongitude = gymLongitude
methodList.append(PGoApiMethod(id: .GetGymDetails, message: try! messageBuilder.build(), parser: { data in
return try! Pogoprotos.Networking.Responses.GetGymDetailsResponse.parseFromData(data)
}))
}
public func startGymBattle(gymId: String, attackingPokemonIds: Array<UInt64>, defendingPokemonId: UInt64) {
let messageBuilder = Pogoprotos.Networking.Requests.Messages.StartGymBattleMessage.Builder()
messageBuilder.gymId = gymId
messageBuilder.attackingPokemonIds = attackingPokemonIds
messageBuilder.defendingPokemonId = defendingPokemonId
methodList.append(PGoApiMethod(id: .StartGymBattle, message: try! messageBuilder.build(), parser: { data in
return try! Pogoprotos.Networking.Responses.StartGymBattleResponse.parseFromData(data)
}))
}
public func attackGym(gymId: String, battleId: String, attackActions: Array<Pogoprotos.Data.Battle.BattleAction>, lastRetrievedAction: Pogoprotos.Data.Battle.BattleAction) {
let messageBuilder = Pogoprotos.Networking.Requests.Messages.AttackGymMessage.Builder()
messageBuilder.gymId = gymId
messageBuilder.battleId = battleId
messageBuilder.attackActions = attackActions
messageBuilder.lastRetrievedActions = lastRetrievedAction
messageBuilder.playerLongitude = Location.lat
messageBuilder.playerLatitude = Location.long
methodList.append(PGoApiMethod(id: .AttackGym, message: try! messageBuilder.build(), parser: { data in
return try! Pogoprotos.Networking.Responses.AttackGymResponse.parseFromData(data)
}))
}
public func recycleInventoryItem(itemId: Pogoprotos.Inventory.Item.ItemId, itemCount: Int32) {
let messageBuilder = Pogoprotos.Networking.Requests.Messages.RecycleInventoryItemMessage.Builder()
messageBuilder.itemId = itemId
messageBuilder.count = itemCount
methodList.append(PGoApiMethod(id: .RecycleInventoryItem, message: try! messageBuilder.build(), parser: { data in
return try! Pogoprotos.Networking.Responses.RecycleInventoryItemResponse.parseFromData(data)
}))
}
public func collectDailyBonus() {
let messageBuilder = Pogoprotos.Networking.Requests.Messages.CollectDailyBonusMessage.Builder()
methodList.append(PGoApiMethod(id: .CollectDailyBonus, message: try! messageBuilder.build(), parser: { data in
return try! Pogoprotos.Networking.Responses.CollectDailyBonusResponse.parseFromData(data)
}))
}
public func useItemXPBoost(itemId: Pogoprotos.Inventory.Item.ItemId) {
let messageBuilder = Pogoprotos.Networking.Requests.Messages.UseItemXpBoostMessage.Builder()
messageBuilder.itemId = itemId
methodList.append(PGoApiMethod(id: .UseItemXpBoost, message: try! messageBuilder.build(), parser: { data in
return try! Pogoprotos.Networking.Responses.UseItemXpBoostResponse.parseFromData(data)
}))
}
public func useItemEggIncubator(itemId: String, pokemonId: UInt64) {
let messageBuilder = Pogoprotos.Networking.Requests.Messages.UseItemEggIncubatorMessage.Builder()
messageBuilder.itemId = itemId
messageBuilder.pokemonId = pokemonId
methodList.append(PGoApiMethod(id: .UseItemEggIncubator, message: try! messageBuilder.build(), parser: { data in
return try! Pogoprotos.Networking.Responses.UseItemEggIncubatorResponse.parseFromData(data)
}))
}
public func useIncense(itemId: Pogoprotos.Inventory.Item.ItemId) {
let messageBuilder = Pogoprotos.Networking.Requests.Messages.UseIncenseMessage.Builder()
messageBuilder.incenseType = itemId
methodList.append(PGoApiMethod(id: .UseIncense, message: try! messageBuilder.build(), parser: { data in
return try! Pogoprotos.Networking.Responses.UseIncenseResponse.parseFromData(data)
}))
}
public func getIncensePokemon() {
let messageBuilder = Pogoprotos.Networking.Requests.Messages.GetIncensePokemonMessage.Builder()
messageBuilder.playerLatitude = Location.lat
messageBuilder.playerLongitude = Location.long
methodList.append(PGoApiMethod(id: .GetIncensePokemon, message: try! messageBuilder.build(), parser: { data in
return try! Pogoprotos.Networking.Responses.GetIncensePokemonResponse.parseFromData(data)
}))
}
public func incenseEncounter(encounterId: UInt64, encounterLocation: String) {
let messageBuilder = Pogoprotos.Networking.Requests.Messages.IncenseEncounterMessage.Builder()
messageBuilder.encounterId = encounterId
messageBuilder.encounterLocation = encounterLocation
methodList.append(PGoApiMethod(id: .IncenseEncounter, message: try! messageBuilder.build(), parser: { data in
return try! Pogoprotos.Networking.Responses.IncenseEncounterResponse.parseFromData(data)
}))
}
public func addFortModifier(itemId: Pogoprotos.Inventory.Item.ItemId, fortId: String) {
let messageBuilder = Pogoprotos.Networking.Requests.Messages.AddFortModifierMessage.Builder()
messageBuilder.modifierType = itemId
messageBuilder.fortId = fortId
messageBuilder.playerLatitude = Location.lat
messageBuilder.playerLongitude = Location.long
methodList.append(PGoApiMethod(id: .AddFortModifier, message: try! messageBuilder.build(), parser: { data in
return try! Pogoprotos.Networking.Responses.AddFortModifierResponse.parseFromData(data)
}))
}
public func diskEncounter(encounterId: UInt64, fortId: String) {
let messageBuilder = Pogoprotos.Networking.Requests.Messages.DiskEncounterMessage.Builder()
messageBuilder.encounterId = encounterId
messageBuilder.fortId = fortId
messageBuilder.playerLatitude = Location.lat
messageBuilder.playerLongitude = Location.long
methodList.append(PGoApiMethod(id: .DiskEncounter, message: try! messageBuilder.build(), parser: { data in
return try! Pogoprotos.Networking.Responses.DiskEncounterResponse.parseFromData(data)
}))
}
public func collectDailyDefenderBonus(encounterId: UInt64, fortId: String) {
let messageBuilder = Pogoprotos.Networking.Requests.Messages.CollectDailyDefenderBonusMessage.Builder()
methodList.append(PGoApiMethod(id: .CollectDailyDefenderBonus, message: try! messageBuilder.build(), parser: { data in
return try! Pogoprotos.Networking.Responses.CollectDailyDefenderBonusResponse.parseFromData(data)
}))
}
public func upgradePokemon(pokemonId: UInt64) {
let messageBuilder = Pogoprotos.Networking.Requests.Messages.UpgradePokemonMessage.Builder()
messageBuilder.pokemonId = pokemonId
methodList.append(PGoApiMethod(id: .UpgradePokemon, message: try! messageBuilder.build(), parser: { data in
return try! Pogoprotos.Networking.Responses.UpgradePokemonResponse.parseFromData(data)
}))
}
public func setFavoritePokemon(pokemonId: Int64, isFavorite: Bool) {
let messageBuilder = Pogoprotos.Networking.Requests.Messages.SetFavoritePokemonMessage.Builder()
messageBuilder.pokemonId = pokemonId
messageBuilder.isFavorite = isFavorite
methodList.append(PGoApiMethod(id: .SetFavoritePokemon, message: try! messageBuilder.build(), parser: { data in
return try! Pogoprotos.Networking.Responses.SetFavoritePokemonResponse.parseFromData(data)
}))
}
public func nicknamePokemon(pokemonId: UInt64, nickname: String) {
let messageBuilder = Pogoprotos.Networking.Requests.Messages.NicknamePokemonMessage.Builder()
messageBuilder.pokemonId = pokemonId
messageBuilder.nickname = nickname
methodList.append(PGoApiMethod(id: .NicknamePokemon, message: try! messageBuilder.build(), parser: { data in
return try! Pogoprotos.Networking.Responses.NicknamePokemonResponse.parseFromData(data)
}))
}
public func equipBadge(badgeType: Pogoprotos.Enums.BadgeType) {
let messageBuilder = Pogoprotos.Networking.Requests.Messages.EquipBadgeMessage.Builder()
messageBuilder.badgeType = badgeType
methodList.append(PGoApiMethod(id: .EquipBadge, message: try! messageBuilder.build(), parser: { data in
return try! Pogoprotos.Networking.Responses.EquipBadgeResponse.parseFromData(data)
}))
}
public func setContactSettings(sendMarketingEmails: Bool, sendPushNotifications: Bool) {
let messageBuilder = Pogoprotos.Networking.Requests.Messages.SetContactSettingsMessage.Builder()
let contactSettings = Pogoprotos.Data.Player.ContactSettings.Builder()
contactSettings.sendMarketingEmails = sendMarketingEmails
contactSettings.sendPushNotifications = sendPushNotifications
try! messageBuilder.contactSettings = contactSettings.build()
methodList.append(PGoApiMethod(id: .SetContactSettings, message: try! messageBuilder.build(), parser: { data in
return try! Pogoprotos.Networking.Responses.SetContactSettingsResponse.parseFromData(data)
}))
}
public func getAssetDigest(deviceModel: String, deviceManufacturer: String, locale: String, appVersion: UInt32) {
let messageBuilder = Pogoprotos.Networking.Requests.Messages.GetAssetDigestMessage.Builder()
messageBuilder.platform = .Ios
messageBuilder.deviceModel = deviceModel
messageBuilder.deviceManufacturer = deviceManufacturer
messageBuilder.locale = locale
messageBuilder.appVersion = appVersion
methodList.append(PGoApiMethod(id: .GetAssetDigest, message: try! messageBuilder.build(), parser: { data in
return try! Pogoprotos.Networking.Responses.GetAssetDigestResponse.parseFromData(data)
}))
}
public func getDownloadURLs(assetId: Array<String>) {
let messageBuilder = Pogoprotos.Networking.Requests.Messages.GetDownloadUrlsMessage.Builder()
messageBuilder.assetId = assetId
methodList.append(PGoApiMethod(id: .GetDownloadUrls, message: try! messageBuilder.build(), parser: { data in
return try! Pogoprotos.Networking.Responses.GetDownloadUrlsResponse.parseFromData(data)
}))
}
public func getSuggestedCodenames() {
let messageBuilder = Pogoprotos.Networking.Requests.Messages.GetSuggestedCodenamesMessage.Builder()
methodList.append(PGoApiMethod(id: .GetSuggestedCodenames, message: try! messageBuilder.build(), parser: { data in
return try! Pogoprotos.Networking.Responses.GetSuggestedCodenamesResponse.parseFromData(data)
}))
}
public func checkCodenameAvailable(codename: String) {
let messageBuilder = Pogoprotos.Networking.Requests.Messages.CheckCodenameAvailableMessage.Builder()
messageBuilder.codename = codename
methodList.append(PGoApiMethod(id: .CheckCodenameAvailable, message: try! messageBuilder.build(), parser: { data in
return try! Pogoprotos.Networking.Responses.CheckCodenameAvailableResponse.parseFromData(data)
}))
}
public func claimCodename(codename: String) {
let messageBuilder = Pogoprotos.Networking.Requests.Messages.ClaimCodenameMessage.Builder()
messageBuilder.codename = codename
methodList.append(PGoApiMethod(id: .ClaimCodename, message: try! messageBuilder.build(), parser: { data in
return try! Pogoprotos.Networking.Responses.ClaimCodenameResponse.parseFromData(data)
}))
}
public func setAvatar(skin: Int32, hair: Int32, shirt: Int32, pants: Int32, hat: Int32, shoes: Int32, gender: Pogoprotos.Enums.Gender, eyes: Int32, backpack: Int32) {
let messageBuilder = Pogoprotos.Networking.Requests.Messages.SetAvatarMessage.Builder()
let playerAvatar = Pogoprotos.Data.Player.PlayerAvatar.Builder()
playerAvatar.backpack = backpack
playerAvatar.skin = skin
playerAvatar.hair = hair
playerAvatar.shirt = shirt
playerAvatar.pants = pants
playerAvatar.hat = hat
playerAvatar.gender = gender
playerAvatar.eyes = eyes
try! messageBuilder.playerAvatar = playerAvatar.build()
methodList.append(PGoApiMethod(id: .SetAvatar, message: try! messageBuilder.build(), parser: { data in
return try! Pogoprotos.Networking.Responses.SetAvatarResponse.parseFromData(data)
}))
}
public func setPlayerTeam(teamColor: Pogoprotos.Enums.TeamColor) {
let messageBuilder = Pogoprotos.Networking.Requests.Messages.SetPlayerTeamMessage.Builder()
messageBuilder.team = teamColor
methodList.append(PGoApiMethod(id: .SetPlayerTeam, message: try! messageBuilder.build(), parser: { data in
return try! Pogoprotos.Networking.Responses.SetPlayerTeamResponse.parseFromData(data)
}))
}
public func markTutorialComplete(tutorialState: Array<Pogoprotos.Enums.TutorialState>, sendMarketingEmails: Bool, sendPushNotifications: Bool) {
let messageBuilder = Pogoprotos.Networking.Requests.Messages.MarkTutorialCompleteMessage.Builder()
messageBuilder.tutorialsCompleted = tutorialState
messageBuilder.sendMarketingEmails = sendMarketingEmails
messageBuilder.sendPushNotifications = sendPushNotifications
methodList.append(PGoApiMethod(id: .MarkTutorialComplete, message: try! messageBuilder.build(), parser: { data in
return try! Pogoprotos.Networking.Responses.MarkTutorialCompleteResponse.parseFromData(data)
}))
}
public func echo() {
let messageBuilder = Pogoprotos.Networking.Requests.Messages.EchoMessage.Builder()
methodList.append(PGoApiMethod(id: .Echo, message: try! messageBuilder.build(), parser: { data in
return try! Pogoprotos.Networking.Responses.EchoResponse.parseFromData(data)
}))
}
public func sfidaActionLog() {
let messageBuilder = Pogoprotos.Networking.Requests.Messages.SfidaActionLogMessage.Builder()
methodList.append(PGoApiMethod(id: .SfidaActionLog, message: try! messageBuilder.build(), parser: { data in
return try! Pogoprotos.Networking.Responses.SfidaActionLogResponse.parseFromData(data)
}))
}
}
| gpl-3.0 | b8e8e29c2b3840fef39e1427a3d1cc94 | 49.618893 | 219 | 0.707368 | 5.138889 | false | false | false | false |
JTWang4778/LearningSwiftDemos | 02-集合类型/001-Array/ViewController.swift | 1 | 3409 | //
// ViewController.swift
// 001-Array
//
// Created by 王锦涛 on 2017/4/16.
// Copyright © 2017年 JTWang. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// 1,数组的创建
// creatArray()
// 2,访问和修改数组
// readAndWriteArr()
//3, 插入和删除元素
// insertAndDelete()
// 4,数组的遍历
enumerateArr()
}
func enumerateArr() {
let arr = ["Eggs","Milk","Beef"]
//1, 直接 遍历数组元素
for item in arr {
print(item)
}
// 2,需要索引的时候。 如果我们同时需要每个数据项的值和索引值,可以使用enumerate()方法来进行数组遍历。enumerate()返回一个由每一个数据项索引值和数据值组成的元组
for (index,obj) in arr.enumerated() {
print("arr[\(index)] = \(obj)")
}
// 2,另外一种遍历方式
for index in 0..<arr.count {
print("arr[\(index)] = \(arr[index])")
}
}
//3, 插入和删除元素
func insertAndDelete() {
var arr = ["Eggs","Milk","Beef"]
arr.insert("插入元素", at: 0)
print(arr) // 注意 插入的位置是在索引之前
// 删除元素
arr.remove(at: 1)
print(arr)
// 删除最后一个元素 和 删除第一个元素 都提供了相应的方法 这样就不能再访问数组的count了
arr.removeLast()
print(arr)
}
// 2,访问和修改数组
func readAndWriteArr() {
var shoppingList = ["Eggs","Milk","Beef"]
if shoppingList.isEmpty {
print("数组为空")
}else{
print("数组长度为 = \(shoppingList.count)")
}
shoppingList.append("红烧肉")
// 可以像OC一样 用下标索引 访问数组中的元素(读取和修改)
print(shoppingList[0])
// 修改
shoppingList[0] = "修改"
print(shoppingList)
// 注意 用下标去读写数组元素的时候 一定要注意下标的范围 从0 到 count - 1 不然会报错
// 错误写法
// print(shoppingList[shoppingList.count])
}
// 1,数组的创建
func creatArray() {
// 创建空的数组
var arr:[Int] = [Int]()
print(arr)
print(arr.count)
arr.append(3)
print(arr)
// 创建带有默认值的数组
let arr2:[Int] = [Int](repeatElement(4, count: 6))
print(arr2)
let arr3 = [Double](repeatElement(10.1, count: 3))
print(arr3)
// 如果两个数组的类型一样 可以直接使用 + 合并成一个数组
let arr4 = arr + arr2
print(arr4)
// 利用字面量创建数组
var strArr:[String] = ["Eggs","Milk"] // 因为类型推断 所以可以不用声明数组的类型 可以推断出来
strArr.append("Beef")
print(strArr)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | fc69a1d859755dd3bf8a32aa7b8ddefa | 21.87395 | 101 | 0.496326 | 3.764869 | false | false | false | false |
dclelland/AudioKit | AudioKit/Common/Instruments/AKFMSynth.swift | 1 | 4895 | //
// AKFMSynth.swift
// AudioKit
//
// Created by Jeff Cooper, revision history on Github.
// Copyright © 2016 AudioKit. All rights reserved.
//
import Foundation
import AVFoundation
/// A wrapper for AKFMOscillator to make it playable as a polyphonic instrument.
public class AKFMSynth: AKPolyphonicInstrument {
/// This multiplied by the baseFrequency gives the carrier frequency.
public var carrierMultiplier: Double = 1.0 {
didSet {
for voice in voices {
let fmVoice = voice as! AKFMOscillatorVoice
fmVoice.oscillator.carrierMultiplier = carrierMultiplier
}
}
}
/// This multiplied by the baseFrequency gives the modulating frequency.
public var modulatingMultiplier: Double = 1 {
didSet {
for voice in voices {
let fmVoice = voice as! AKFMOscillatorVoice
fmVoice.oscillator.modulatingMultiplier = modulatingMultiplier
}
}
}
/// This multiplied by the modulating frequency gives the modulation amplitude.
public var modulationIndex: Double = 1 {
didSet {
for voice in voices {
let fmVoice = voice as! AKFMOscillatorVoice
fmVoice.oscillator.modulationIndex = modulationIndex
}
}
}
/// Attack time
public var attackDuration: Double = 0.1 {
didSet {
for voice in voices {
let fmVoice = voice as! AKFMOscillatorVoice
fmVoice.adsr.attackDuration = attackDuration
}
}
}
/// Decay time
public var decayDuration: Double = 0.1 {
didSet {
for voice in voices {
let fmVoice = voice as! AKFMOscillatorVoice
fmVoice.adsr.decayDuration = decayDuration
}
}
}
/// Sustain Level
public var sustainLevel: Double = 0.66 {
didSet {
for voice in voices {
let fmVoice = voice as! AKFMOscillatorVoice
fmVoice.adsr.sustainLevel = sustainLevel
}
}
}
/// Release time
public var releaseDuration: Double = 0.5 {
didSet {
for voice in voices {
let fmVoice = voice as! AKFMOscillatorVoice
fmVoice.adsr.releaseDuration = releaseDuration
}
}
}
/// Instantiate the FM Oscillator Instrument
///
/// - parameter voiceCount: Maximum number of voices that will be required
///
public init(voiceCount: Int) {
super.init(voice: AKFMOscillatorVoice(), voiceCount: voiceCount)
for voice in voices {
let fmVoice = voice as! AKFMOscillatorVoice
fmVoice.oscillator.modulatingMultiplier = 4 //just some arbitrary default values
fmVoice.oscillator.modulationIndex = 10
}
}
/// Start a given voice playing a note.
///
/// - parameter voice: Voice to start
/// - parameter note: MIDI Note Number to start
/// - parameter velocity: MIDI Velocity (0-127) to trigger the note at
///
override internal func playVoice(voice: AKVoice, note: Int, velocity: Int) {
let fmVoice = voice as! AKFMOscillatorVoice
fmVoice.oscillator.baseFrequency = note.midiNoteToFrequency()
fmVoice.oscillator.amplitude = Double(velocity) / 127.0
fmVoice.start()
}
/// Stop a given voice playing a note.
///
/// - parameter voice: Voice to stop
/// - parameter note: MIDI Note Number to stop
///
override internal func stopVoice(voice: AKVoice, note: Int) {
let fmVoice = voice as! AKFMOscillatorVoice
fmVoice.stop()
}
}
internal class AKFMOscillatorVoice: AKVoice {
var oscillator: AKFMOscillator
var adsr: AKAmplitudeEnvelope
/// Instantiate the FM Oscillator Voice
override init() {
oscillator = AKFMOscillator()
adsr = AKAmplitudeEnvelope(oscillator,
attackDuration: 0.2,
decayDuration: 0.2,
sustainLevel: 0.8,
releaseDuration: 1.0)
super.init()
avAudioNode = adsr.avAudioNode
}
/// Function create an identical new node for use in creating polyphonic instruments
override func duplicate() -> AKVoice {
let copy = AKFMOscillatorVoice()
return copy
}
/// Tells whether the node is processing (ie. started, playing, or active)
override var isStarted: Bool {
return oscillator.isPlaying
}
/// Function to start, play, or activate the node, all do the same thing
override func start() {
oscillator.start()
adsr.start()
}
/// Function to stop or bypass the node, both are equivalent
override func stop() {
adsr.stop()
}
}
| mit | bee8776e8552cbeabfe9396456badf63 | 30.574194 | 92 | 0.600327 | 5.296537 | false | false | false | false |
jamesjmtaylor/weg-ios | Pods/Mockingjay/Sources/Mockingjay/XCTest.swift | 2 | 1726 | //
// XCTest.swift
// Mockingjay
//
// Created by Kyle Fuller on 28/02/2015.
// Copyright (c) 2015 Cocode. All rights reserved.
//
import ObjectiveC
import XCTest
let swizzleTearDown: Void = {
let tearDown = class_getInstanceMethod(XCTest.self, #selector(XCTest.tearDown))
let mockingjayTearDown = class_getInstanceMethod(XCTest.self, #selector(XCTest.mockingjayTearDown))
method_exchangeImplementations(tearDown!, mockingjayTearDown!)
}()
var AssociatedMockingjayRemoveStubOnTearDownHandle: UInt8 = 0
extension XCTest {
// MARK: Stubbing
/// Whether Mockingjay should remove stubs on teardown
public var mockingjayRemoveStubOnTearDown: Bool {
get {
let associatedResult = objc_getAssociatedObject(self, &AssociatedMockingjayRemoveStubOnTearDownHandle) as? Bool
return associatedResult ?? true
}
set {
objc_setAssociatedObject(self, &AssociatedMockingjayRemoveStubOnTearDownHandle, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
@discardableResult public func stub(_ matcher: @escaping Matcher, delay: TimeInterval? = nil, _ builder: @escaping Builder) -> Stub {
if mockingjayRemoveStubOnTearDown {
XCTest.mockingjaySwizzleTearDown()
}
return MockingjayProtocol.addStub(matcher: matcher, delay: delay, builder: builder)
}
public func removeStub(_ stub:Stub) {
MockingjayProtocol.removeStub(stub)
}
public func removeAllStubs() {
MockingjayProtocol.removeAllStubs()
}
// MARK: Teardown
public class func mockingjaySwizzleTearDown() {
_ = swizzleTearDown
}
@objc func mockingjayTearDown() {
mockingjayTearDown()
if mockingjayRemoveStubOnTearDown {
MockingjayProtocol.removeAllStubs()
}
}
}
| mit | c1c43ca8d483d8e8706a965c23afe7f0 | 26.396825 | 135 | 0.738123 | 4.690217 | false | true | false | false |
ianrahman/HackerRankChallenges | Swift/Data Structures/Arrays/algorithmic-crush.swift | 1 | 671 | import Foundation
// declare initial values
let params = readLine()!.components(separatedBy: " ").map{ Int($0)! }
let n = params[0]
let m = params[1]
var list = [Int]()
for _ in 0...n {
list.append(0)
}
// perform each operation
for _ in 0..<m {
// parse operation
let operation = readLine()!.components(separatedBy: " ").map{ Int($0)! }
let a = operation[0]
let b = operation[1]
let k = operation[2]
// mark beginning of incremented range
list[a - 1] += k
// mark end of incremented range
list[b] -= k
}
// sum changes to determine max
var temp = 0
var max = 0
list.map({temp += $0; if temp > max {max = temp}})
print(max)
| mit | 7ecf5db0c17f6002367dc749e4b425e5 | 19.333333 | 76 | 0.605067 | 3.289216 | false | false | false | false |
wikimedia/wikipedia-ios | Wikipedia/Code/Article as a Living Document/ArticleAsLivingDocViewController.swift | 1 | 24755 | import UIKit
import WMF
protocol ArticleAsLivingDocViewControllerDelegate: AnyObject {
var articleAsLivingDocViewModel: ArticleAsLivingDocViewModel? { get }
var articleURL: URL { get }
var isFetchingAdditionalPages: Bool { get }
func fetchNextPage(nextRvStartId: UInt, theme: Theme)
func showEditHistory()
func handleLink(with href: String)
func livingDocViewWillAppear()
func livingDocViewWillPush()
}
protocol ArticleDetailsShowing: AnyObject {
func goToHistory()
func goToDiff(revisionId: UInt, parentId: UInt, diffType: DiffContainerViewModel.DiffType)
func showTalkPageWithSectionName(_ sectionName: String?)
func thankButtonTapped(for revisionID: Int, isUserAnonymous: Bool, livingDocLoggingValues: ArticleAsLivingDocLoggingValues)
}
class ArticleAsLivingDocViewController: ColumnarCollectionViewController {
private let articleTitle: String?
private var headerView: ArticleAsLivingDocHeaderView?
private let headerText = WMFLocalizedString("aaald-header-text", value: "Recent Changes", comment: "Header text of article as a living document view.")
private let editMetrics: [NSNumber]?
private weak var delegate: ArticleAsLivingDocViewControllerDelegate?
private lazy var dataSource: UICollectionViewDiffableDataSource<ArticleAsLivingDocViewModel.SectionHeader, ArticleAsLivingDocViewModel.TypedEvent> = createDataSource()
private var initialIndexPath: IndexPath?
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) not supported")
}
required init?(articleTitle: String?, editMetrics: [NSNumber]?, theme: Theme, locale: Locale = Locale.current, delegate: ArticleAsLivingDocViewControllerDelegate, scrollToInitialIndexPath initialIndexPath: IndexPath?) {
guard delegate.articleAsLivingDocViewModel != nil else {
return nil
}
self.articleTitle = articleTitle
self.editMetrics = editMetrics
super.init()
self.theme = theme
self.delegate = delegate
self.initialIndexPath = initialIndexPath
footerButtonTitle = CommonStrings.viewFullHistoryText
}
override func viewDidLoad() {
super.viewDidLoad()
layoutManager.register(ArticleAsLivingDocLargeEventCollectionViewCell.self, forCellWithReuseIdentifier: ArticleAsLivingDocLargeEventCollectionViewCell.identifier, addPlaceholder: true)
layoutManager.register(ArticleAsLivingDocSmallEventCollectionViewCell.self, forCellWithReuseIdentifier: ArticleAsLivingDocSmallEventCollectionViewCell.identifier, addPlaceholder: true)
layoutManager.register(ArticleAsLivingDocSectionHeaderView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: ArticleAsLivingDocSectionHeaderView.identifier, addPlaceholder: true)
layoutManager.register(ActivityIndicatorCollectionViewFooter.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: ActivityIndicatorCollectionViewFooter.identifier, addPlaceholder: false)
self.title = headerText
setupNavigationBar()
if let viewModel = delegate?.articleAsLivingDocViewModel {
addInitialSections(sections: viewModel.sections)
}
self.navigationController?.presentationController?.delegate = self
}
override func viewWillAppear(_ animated: Bool) {
// for some reason the initial calls to metrics(with size: CGSize...) (triggered from viewDidLoad) have an incorrect view size passed in.
// this retriggers that method with the correct size, so that we have correct layout margins on load
if isFirstAppearance {
collectionView.reloadData()
}
super.viewWillAppear(animated)
delegate?.livingDocViewWillAppear()
}
private func createDataSource() -> UICollectionViewDiffableDataSource<ArticleAsLivingDocViewModel.SectionHeader, ArticleAsLivingDocViewModel.TypedEvent> {
let dataSource = UICollectionViewDiffableDataSource<ArticleAsLivingDocViewModel.SectionHeader, ArticleAsLivingDocViewModel.TypedEvent>(collectionView: collectionView) { (collectionView: UICollectionView, indexPath: IndexPath, event: ArticleAsLivingDocViewModel.TypedEvent) -> UICollectionViewCell? in
let theme = self.theme
let cell: CollectionViewCell
switch event {
case .large(let largeEvent):
guard let largeEventCell = collectionView.dequeueReusableCell(withReuseIdentifier: ArticleAsLivingDocLargeEventCollectionViewCell.identifier, for: indexPath) as? ArticleAsLivingDocLargeEventCollectionViewCell else {
return nil
}
largeEventCell.configure(with: largeEvent, theme: theme, extendTimelineAboveDot: indexPath.item != 0)
largeEventCell.delegate = self
largeEventCell.articleDelegate = self
cell = largeEventCell
case .small(let smallEvent):
guard let smallEventCell = collectionView.dequeueReusableCell(withReuseIdentifier: ArticleAsLivingDocSmallEventCollectionViewCell.identifier, for: indexPath) as? ArticleAsLivingDocSmallEventCollectionViewCell else {
return nil
}
smallEventCell.configure(viewModel: smallEvent, theme: theme)
smallEventCell.delegate = self
cell = smallEventCell
}
if let layout = collectionView.collectionViewLayout as? ColumnarCollectionViewLayout {
cell.layoutMargins = layout.itemLayoutMargins
}
return cell
}
dataSource.supplementaryViewProvider = { collectionView, kind, indexPath in
guard kind == UICollectionView.elementKindSectionHeader || kind == UICollectionView.elementKindSectionFooter else {
return UICollectionReusableView()
}
let theme = self.theme
if kind == UICollectionView.elementKindSectionHeader {
let section = self.dataSource.snapshot()
.sectionIdentifiers[indexPath.section]
guard let sectionHeaderView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: ArticleAsLivingDocSectionHeaderView.identifier, for: indexPath) as? ArticleAsLivingDocSectionHeaderView else {
return UICollectionReusableView()
}
sectionHeaderView.layoutMargins = self.layout.itemLayoutMargins
sectionHeaderView.configure(viewModel: section, theme: theme)
return sectionHeaderView
} else if kind == UICollectionView.elementKindSectionFooter {
if self.delegate?.isFetchingAdditionalPages == true,
let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: ActivityIndicatorCollectionViewFooter.identifier, for: indexPath) as? ActivityIndicatorCollectionViewFooter {
footer.apply(theme: theme)
return footer
}
guard let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: CollectionViewFooter.identifier, for: indexPath) as? CollectionViewFooter else {
return UICollectionReusableView()
}
self.configure(footer: footer, forSectionAt: indexPath.section, layoutOnly: false)
return footer
}
return UICollectionReusableView()
}
return dataSource
}
private func updateLoggingPositionsForItemsInSections(_ sections: [ArticleAsLivingDocViewModel.SectionHeader]) {
var currentPosition: Int = 0
for section in sections {
for item in section.typedEvents {
switch item {
case .large(let largeEvent):
if largeEvent.loggingPosition == 0 {
largeEvent.loggingPosition = currentPosition
}
case .small(let smallEvent):
if smallEvent.loggingPosition == 0 {
smallEvent.loggingPosition = currentPosition
}
}
currentPosition = currentPosition + 1
}
}
}
func addInitialSections(sections: [ArticleAsLivingDocViewModel.SectionHeader]) {
var snapshot = NSDiffableDataSourceSnapshot<ArticleAsLivingDocViewModel.SectionHeader, ArticleAsLivingDocViewModel.TypedEvent>()
snapshot.appendSections(sections)
for section in sections {
snapshot.appendItems(section.typedEvents, toSection: section)
}
updateLoggingPositionsForItemsInSections(snapshot.sectionIdentifiers)
dataSource.apply(snapshot, animatingDifferences: true) {
self.scrollToInitialIndexPathIfNeeded()
}
}
func scrollToInitialIndexPathIfNeeded() {
guard let initialIndexPath = initialIndexPath else {
return
}
collectionView.scrollToItem(at: initialIndexPath, at: .top, animated: true)
}
func appendSections(_ sections: [ArticleAsLivingDocViewModel.SectionHeader]) {
guard let dayMonthNumberYearDateFormatter = DateFormatter.wmf_monthNameDayOfMonthNumberYear(), let isoDateFormatter = DateFormatter.wmf_iso8601() else {
return
}
var currentSnapshot = dataSource.snapshot()
var existingSections: [ArticleAsLivingDocViewModel.SectionHeader] = []
for currentSection in currentSnapshot.sectionIdentifiers {
for proposedSection in sections {
if currentSection == proposedSection {
if
let lastCurrentEvent = currentSection.typedEvents.last, lastCurrentEvent.isSmall,
let firstProposedEvent = proposedSection.typedEvents.first, firstProposedEvent.isSmall {
// Collapse sequential small events if appending to the same section
let smallChanges = lastCurrentEvent.smallChanges + firstProposedEvent.smallChanges
let collapsedSmallEvent = ArticleAsLivingDocViewModel.TypedEvent.small(.init(smallChanges: smallChanges))
let proposedSectionCollapsed = proposedSection
let currentSectionCollapsed = currentSection
proposedSectionCollapsed.typedEvents.removeFirst()
currentSectionCollapsed.typedEvents.removeLast()
currentSnapshot.deleteItems([lastCurrentEvent])
currentSnapshot.appendItems([collapsedSmallEvent], toSection: currentSection)
currentSnapshot.appendItems(proposedSectionCollapsed.typedEvents, toSection: currentSection)
existingSections.append(proposedSectionCollapsed)
} else {
currentSnapshot.appendItems(proposedSection.typedEvents, toSection: currentSection)
existingSections.append(proposedSection)
}
}
}
}
// Collapse first proposed section into last current section if both only contain small events
if
let lastCurrentSection = currentSnapshot.sectionIdentifiers.last, lastCurrentSection.containsOnlySmallEvents,
let firstProposedSection = sections.first, firstProposedSection.containsOnlySmallEvents {
let smallChanges = lastCurrentSection.typedEvents.flatMap { $0.smallChanges } + firstProposedSection.typedEvents.flatMap { $0.smallChanges }
let collapsedSmallEvent = ArticleAsLivingDocViewModel.Event.Small(smallChanges: smallChanges)
let smallTypedEvent = ArticleAsLivingDocViewModel.TypedEvent.small(collapsedSmallEvent)
let smallChangeDates = smallChanges.compactMap { isoDateFormatter.date(from: $0.timestampString) }
var dateRange: DateInterval?
if let minDate = smallChangeDates.min(), let maxDate = smallChangeDates.max() {
dateRange = DateInterval(start: minDate, end: maxDate)
}
let collapsedSection = ArticleAsLivingDocViewModel.SectionHeader(timestamp: lastCurrentSection.timestamp, typedEvents: [smallTypedEvent], subtitleDateFormatter: dayMonthNumberYearDateFormatter, dateRange: dateRange)
currentSnapshot.deleteItems(lastCurrentSection.typedEvents)
currentSnapshot.insertSections([collapsedSection], afterSection: lastCurrentSection)
currentSnapshot.deleteSections([lastCurrentSection])
currentSnapshot.appendItems(collapsedSection.typedEvents, toSection: collapsedSection)
existingSections.append(lastCurrentSection)
existingSections.append(firstProposedSection)
}
// Appending remaining new sections to the snapshot
for section in sections {
if !existingSections.contains(section) {
currentSnapshot.appendSections([section])
currentSnapshot.appendItems(section.typedEvents, toSection: section)
}
}
updateLoggingPositionsForItemsInSections(currentSnapshot.sectionIdentifiers)
dataSource.apply(currentSnapshot, animatingDifferences: true)
}
private func setupNavigationBar() {
navigationItem.rightBarButtonItem = UIBarButtonItem(title: WMFLocalizedString("close-button", value: "Close", comment: "Close button used in navigation bar that closes out a presented modal screen."), style: .done, target: self, action: #selector(closeButtonPressed))
navigationMode = .forceBar
if let headerView = ArticleAsLivingDocHeaderView.wmf_viewFromClassNib() {
self.headerView = headerView
configureHeaderView(headerView)
navigationBar.isBarHidingEnabled = false
navigationBar.isUnderBarViewHidingEnabled = true
navigationBar.isUnderBarFadingEnabled = false
navigationBar.addUnderNavigationBarView(headerView)
navigationBar.needsUnderBarHack = true
navigationBar.underBarViewPercentHiddenForShowingTitle = 0.6
navigationBar.title = headerText
navigationBar.setNeedsLayout()
navigationBar.layoutIfNeeded()
updateScrollViewInsets()
}
}
@objc private func closeButtonPressed() {
ArticleAsLivingDocFunnel.shared.logModalCloseButtonTapped()
dismiss(animated: true, completion: nil)
}
override func metrics(with size: CGSize, readableWidth: CGFloat, layoutMargins: UIEdgeInsets) -> ColumnarCollectionViewLayoutMetrics {
return ColumnarCollectionViewLayoutMetrics.tableViewMetrics(with: size, readableWidth: readableWidth, layoutMargins: layoutMargins)
}
private func configureHeaderView(_ headerView: ArticleAsLivingDocHeaderView) {
guard let articleAsLivingDocViewModel = delegate?.articleAsLivingDocViewModel else {
return
}
let headerText = self.headerText.uppercased(with: NSLocale.current)
headerView.configure(headerText: headerText, titleText: articleTitle, summaryText: articleAsLivingDocViewModel.summaryText, editMetrics: editMetrics, theme: theme)
headerView.apply(theme: theme)
headerView.viewFullHistoryButton.addTarget(self, action: #selector(tappedViewFullHistoryButtonInHeader), for: .touchUpInside)
}
override func apply(theme: Theme) {
guard isViewLoaded else {
return
}
super.apply(theme: theme)
navigationItem.rightBarButtonItem?.tintColor = theme.colors.link
navigationController?.navigationBar.barTintColor = theme.colors.cardButtonBackground
headerView?.apply(theme: theme)
}
@objc func tappedViewFullHistoryButtonInFooter() {
ArticleAsLivingDocFunnel.shared.logModalViewFullHistoryBottomButtonTapped()
tappedViewFullHistoryButton()
}
@objc func tappedViewFullHistoryButtonInHeader() {
ArticleAsLivingDocFunnel.shared.logModalViewFullHistoryTopButtonTapped()
tappedViewFullHistoryButton()
}
private func tappedViewFullHistoryButton() {
self.goToHistory()
}
// MARK: - CollectionView functions
override func collectionView(_ collectionView: UICollectionView, estimatedHeightForHeaderInSection section: Int, forColumnWidth columnWidth: CGFloat) -> ColumnarCollectionViewLayoutHeightEstimate {
var estimate = ColumnarCollectionViewLayoutHeightEstimate(precalculated: false, height: 70)
let section = self.dataSource.snapshot()
.sectionIdentifiers[section]
guard let sectionHeaderView = layoutManager.placeholder(forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: ArticleAsLivingDocSectionHeaderView.identifier) as? ArticleAsLivingDocSectionHeaderView else {
return estimate
}
sectionHeaderView.configure(viewModel: section, theme: theme)
estimate.height = sectionHeaderView.sizeThatFits(CGSize(width: columnWidth, height: UIView.noIntrinsicMetric), apply: false).height
estimate.precalculated = true
return estimate
}
override func collectionView(_ collectionView: UICollectionView, estimatedHeightForItemAt indexPath: IndexPath, forColumnWidth columnWidth: CGFloat) -> ColumnarCollectionViewLayoutHeightEstimate {
var estimate = ColumnarCollectionViewLayoutHeightEstimate(precalculated: false, height: 350)
guard let event = dataSource.itemIdentifier(for: indexPath) else {
return estimate
}
let cell: CollectionViewCell
switch event {
case .large(let largeEvent):
guard let largeEventCell = layoutManager.placeholder(forCellWithReuseIdentifier: ArticleAsLivingDocLargeEventCollectionViewCell.identifier) as? ArticleAsLivingDocLargeEventCollectionViewCell else {
return estimate
}
largeEventCell.configure(with: largeEvent, theme: theme)
cell = largeEventCell
case .small(let smallEvent):
guard let smallEventCell = layoutManager.placeholder(forCellWithReuseIdentifier: ArticleAsLivingDocSmallEventCollectionViewCell.identifier) as? ArticleAsLivingDocSmallEventCollectionViewCell else {
return estimate
}
smallEventCell.configure(viewModel: smallEvent, theme: theme)
cell = smallEventCell
}
cell.layoutMargins = layout.itemLayoutMargins
estimate.height = cell.sizeThatFits(CGSize(width: columnWidth, height: UIView.noIntrinsicMetric), apply: false).height
estimate.precalculated = true
return estimate
}
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
guard let articleAsLivingDocViewModel = delegate?.articleAsLivingDocViewModel else {
return
}
let numSections = dataSource.numberOfSections(in: collectionView)
let numEvents = dataSource.collectionView(collectionView, numberOfItemsInSection: indexPath.section)
if indexPath.section == numSections - 1 &&
indexPath.item == numEvents - 1 {
guard let nextRvStartId = articleAsLivingDocViewModel.nextRvStartId,
nextRvStartId != 0 else {
return
}
delegate?.fetchNextPage(nextRvStartId: nextRvStartId, theme: theme)
}
}
@objc func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool {
return false
}
@objc func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
return false
}
override func collectionViewFooterButtonWasPressed(_ collectionViewFooter: CollectionViewFooter) {
tappedViewFullHistoryButtonInFooter()
}
}
// MARK: - ArticleAsLivingDocHorizontallyScrollingCellDelegate
extension ArticleAsLivingDocViewController: ArticleAsLivingDocHorizontallyScrollingCellDelegate, InternalLinkPreviewing {
func tappedLink(_ url: URL) {
guard let fullURL = delegate?.articleURL.resolvingRelativeWikiHref(url.absoluteString) else {
return
}
switch Configuration.current.router.destination(for: fullURL) {
case .article(let articleURL): showInternalLink(url: articleURL)
default: navigate(to: fullURL)
}
}
}
extension ArticleAsLivingDocViewController: ArticleDetailsShowing {
func showTalkPageWithSectionName(_ sectionName: String?) {
var maybeTalkPageURL = delegate?.articleURL.articleTalkPage
if let convertedSectionName = sectionName?.asTalkPageFragment,
let talkPageURL = maybeTalkPageURL {
maybeTalkPageURL = URL(string: talkPageURL.absoluteString + "#" + convertedSectionName)
}
guard let talkPageURL = maybeTalkPageURL else {
showGenericError()
return
}
navigate(to: talkPageURL)
}
func goToDiff(revisionId: UInt, parentId: UInt, diffType: DiffContainerViewModel.DiffType) {
guard let title = delegate?.articleURL.wmf_title,
let siteURL = delegate?.articleURL.wmf_site else {
return
}
let diffContainerVC = DiffContainerViewController(siteURL: siteURL, theme: theme, fromRevisionID: Int(parentId), toRevisionID: Int(revisionId), type: diffType, articleTitle: title, needsSetNavDelegate: true)
delegate?.livingDocViewWillPush()
push(diffContainerVC)
}
func goToHistory() {
guard let articleURL = delegate?.articleURL, let title = articleURL.wmf_title else {
showGenericError()
return
}
let historyVC = PageHistoryViewController(pageTitle: title, pageURL: articleURL)
historyVC.apply(theme: theme)
delegate?.livingDocViewWillPush()
push(historyVC)
}
func thankButtonTapped(for revisionID: Int, isUserAnonymous: Bool, livingDocLoggingValues: ArticleAsLivingDocLoggingValues) {
self.tappedThank(for: revisionID, isUserAnonymous: isUserAnonymous, livingDocLoggingValues: livingDocLoggingValues)
}
}
extension ArticleAsLivingDocViewController: ThanksGiving {
var url: URL? {
return self.delegate?.articleURL.wmf_site
}
var bottomSpacing: CGFloat? {
return 0
}
func didLogIn() {
self.apply(theme: theme)
}
func wereThanksSent(for revisionID: Int) -> Bool {
let currentSnapshot = dataSource.snapshot()
for section in currentSnapshot.sectionIdentifiers {
for event in section.typedEvents {
switch event {
case .large(let largeEvent):
if largeEvent.revId == revisionID {
return largeEvent.wereThanksSent
}
default: continue
}
}
}
return false
}
func thanksWereSent(for revisionID: Int) {
var currentSnapshot = dataSource.snapshot()
for section in currentSnapshot.sectionIdentifiers {
for event in section.typedEvents {
switch event {
case .large(let largeEvent):
if largeEvent.revId == revisionID {
largeEvent.wereThanksSent = true
currentSnapshot.reloadSections([section])
break
}
default: continue
}
}
}
dataSource.apply(currentSnapshot, animatingDifferences: true)
}
}
extension ArticleAsLivingDocViewController: UIAdaptivePresentationControllerDelegate {
func presentationControllerDidDismiss(_ presentationController: UIPresentationController) {
ArticleAsLivingDocFunnel.shared.logModalSwipedToDismiss()
}
}
| mit | fad208adfecda78642baafecc4a601f3 | 44.673432 | 308 | 0.682246 | 6.606619 | false | false | false | false |
superk589/DereGuide | DereGuide/Card/View/CGSSIconView.swift | 2 | 1331 | //
// CGSSIconView.swift
// DereGuide
//
// Created by zzk on 16/8/14.
// Copyright © 2016 zzk. All rights reserved.
//
import UIKit
import ZKCornerRadiusView
protocol CGSSIconViewDelegate: class {
func iconClick(_ iv: CGSSIconView)
}
class CGSSIconView: UIImageView {
var tap: UITapGestureRecognizer?
var action: Selector?
weak var target: AnyObject?
weak var delegate: CGSSIconViewDelegate?
convenience init() {
self.init(frame: CGRect.init(x: 0, y: 0, width: 48, height: 48))
}
override init(frame: CGRect) {
super.init(frame: frame)
prepare()
}
func prepare() {
isUserInteractionEnabled = true
tap = UITapGestureRecognizer(target: self, action: #selector(onClick))
addGestureRecognizer(tap!)
}
func setAction(_ target: AnyObject, action: Selector) {
self.action = action
self.target = target
}
@objc func onClick() {
delegate?.iconClick(self)
if action != nil {
_ = self.target?.perform(action!, with: self)
}
}
override var intrinsicContentSize: CGSize {
return CGSize(width: 48, height: 48)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
prepare()
}
}
| mit | a8ea4c528fb35e77b55828f3e6490dbc | 21.931034 | 78 | 0.604511 | 4.262821 | false | false | false | false |
niklassaers/PackStream-Swift | Tests/PackStreamTests/Random.swift | 1 | 3967 | import Foundation
// source: https://gist.github.com/jstn/f9d5437316879c9c448a
let wordSize = __WORDSIZE // needed to suprress warnings
public func arc4random <T: ExpressibleByIntegerLiteral> (_ type: T.Type) -> T {
#if os(Linux)
let size = UInt64(MemoryLayout<T>.size)
return UInt64(random()) % size as! T
#else
var r: T = 0
arc4random_buf(&r, Int(MemoryLayout<T>.size))
return r
#endif
}
public extension UInt {
static func random(_ lower: UInt = min, upper: UInt = max) -> UInt {
switch (wordSize) {
case 32: return UInt(UInt32.random(UInt32(lower), upper: UInt32(upper)))
case 64: return UInt(UInt64.random(UInt64(lower), upper: UInt64(upper)))
default: return lower
}
}
}
public extension Int {
static func random(_ lower: Int = min, upper: Int = max) -> Int {
#if os(Linux)
return (random() % (upper)) + lower
#else
switch (wordSize) {
case 32: return Int(Int32.random(Int32(lower), upper: Int32(upper)))
case 64: return Int(Int64.random(Int64(lower), upper: Int64(upper)))
default: return lower
}
#endif
}
}
public extension Int8 {
static func random(_ lower: Int8 = min, upper: Int8 = max) -> Int8 {
#if os(Linux)
return (random() % (upper)) + lower
#else
let r = arc4random_uniform(UInt32(Int64(upper) - Int64(lower)))
return Int8(Int64(r) + Int64(lower))
#endif
}
}
public extension Int16 {
static func random(_ lower: Int16 = min, upper: Int16 = max) -> Int16 {
#if os(Linux)
return (random() % (upper)) + lower
#else
let r = arc4random_uniform(UInt32(Int64(upper) - Int64(lower)))
return Int16(Int64(r) + Int64(lower))
#endif
}
}
public extension UInt32 {
static func random(_ lower: UInt32 = min, upper: UInt32 = max) -> UInt32 {
#if os(Linux)
return (random() % (upper)) + lower
#else
return arc4random_uniform(upper - lower) + lower
#endif
}
}
public extension Int32 {
static func random(_ lower: Int32 = min, upper: Int32 = max) -> Int32 {
#if os(Linux)
return (random() % (upper)) + lower
#else
let r = arc4random_uniform(UInt32(Int64(upper) - Int64(lower)))
return Int32(Int64(r) + Int64(lower))
#endif
}
}
public extension UInt64 {
static func random(_ lower: UInt64 = min, upper: UInt64 = max) -> UInt64 {
var m: UInt64
let u = upper - lower
var r = arc4random(UInt64.self)
if u > UInt64(Int64.max) {
m = 1 + ~u
} else {
m = ((max - (u * 2)) + 1) % u
}
while r < m {
r = arc4random(UInt64.self)
}
return (r % u) + lower
}
}
public extension Int64 {
static func random(_ lower: Int64 = min, upper: Int64 = max) -> Int64 {
#if swift(>=4.0)
let (s, overflow) = upper.subtractingReportingOverflow(lower)
#elseif swift(>=3.0)
let (s, overflow) = Int64.subtractWithOverflow(upper, lower)
#endif
let u = overflow ? UInt64.max - UInt64(~s) : UInt64(s)
let r = UInt64.random(upper: u)
if r > UInt64(Int64.max) {
return Int64(r - (UInt64(~lower) + 1))
} else {
return Int64(r) + lower
}
}
}
public extension Float {
static func random(_ lower: Float = 0.0, upper: Float = 1.0) -> Float {
let r = Float(arc4random(UInt32.self)) / Float(UInt32.max)
return (r * (upper - lower)) + lower
}
}
public extension Double {
static func random(_ lower: Double = 0.0, upper: Double = 1.0) -> Double {
let r = Double(arc4random(UInt64.self)) / Double(UInt64.max)
return (r * (upper - lower)) + lower
}
}
| bsd-3-clause | cf2aa109f681118fb78264fa070b077c | 28.169118 | 80 | 0.549029 | 3.461606 | false | false | false | false |
raumfeld/RFSVG | RFSVG/DirectoryWatcher.swift | 1 | 2444 | //
// DirectoryWatcher.swift
// RFSVG
//
// Created by Dunja Lalic on 28/01/2017.
// Copyright © 2017 Lautsprecher Teufel GmbH. All rights reserved.
//
import Foundation
protocol DirectoryWatcherDelegate: class {
func directoryDidChange(_ directoryWatcher: DirectoryWatcher)
}
class DirectoryWatcher {
// MARK: Properties
/// A delegate responsible for responding to `DirectoryWatcher` updates
private weak var delegate: DirectoryWatcherDelegate?
/// A file descriptor for the monitored directory
private var monitoredDirectoryFileDescriptor: CInt = -1
/// A dispatch queue used for sending file changes in the directory
private let directoryWatcherQueue = DispatchQueue(label: "com.raumfeld.SVGCache.directoryWatcher", attributes: DispatchQueue.Attributes.concurrent)
/// A dispatch source to monitor a file descriptor
private var directoryWatcherSource: DispatchSourceFileSystemObject?
/// URL for the directory to be monitored
private var URL: URL
// MARK: Lifecycle
/// Initializer.
///
/// - Parameters:
/// - URL: URL for the directory to be monitored
/// - delegate: A delegate responsible for responding to `DirectoryWatcher` updates
init(URL: URL, delegate: DirectoryWatcherDelegate) {
self.URL = URL
self.delegate = delegate
}
// MARK: Monitoring
/// Starts monitoring
func startMonitoring() {
if directoryWatcherSource == nil && monitoredDirectoryFileDescriptor == -1 {
monitoredDirectoryFileDescriptor = open(URL.path, O_EVTONLY)
directoryWatcherSource = DispatchSource.makeFileSystemObjectSource(fileDescriptor: monitoredDirectoryFileDescriptor, eventMask: [.write], queue: directoryWatcherQueue)
directoryWatcherSource?.setEventHandler {
self.delegate?.directoryDidChange(self)
return
}
directoryWatcherSource?.setCancelHandler {
close(self.monitoredDirectoryFileDescriptor)
self.monitoredDirectoryFileDescriptor = -1
self.directoryWatcherSource = nil
}
directoryWatcherSource?.resume()
}
}
/// Stops monitoring
func stopMonitoring() {
directoryWatcherSource?.cancel()
}
}
| mit | 0aabf2b509233734041da2a28a1bd3f4 | 32.930556 | 179 | 0.651658 | 5.721311 | false | false | false | false |
natmark/SlideStock | SlideStock/ViewModels/StockViewModel.swift | 1 | 2362 | //
// StockViewModel.swift
// SlideStock
//
// Created by AtsuyaSato on 2017/05/03.
// Copyright © 2017年 Atsuya Sato. All rights reserved.
//
import UIKit
import RxSwift
import RealmSwift
class StockViewModel: NSObject {
fileprivate let cellIdentifier = "slideCell"
let searchController = UISearchController(searchResultsController: nil)
let slides = Variable<[Slide]>([])
let searchResults = Variable<[Slide]>([])
override init() {
super.init()
}
func reloadData() {
let realm = try! Realm()
let results = realm.objects(Slide.self)
print(results)
self.slides.value = Array(results)
}
func removeAt(index: Int) {
let realm = try! Realm()
if searchController.isActive {
try? realm.write {
realm.delete(searchResults.value[index])
}
searchResults.value.remove(at: index)
} else {
try? realm.write {
realm.delete(slides.value[index])
}
slides.value.remove(at: index)
}
}
func indexOf(index: Int) -> Slide {
if searchController.isActive {
return searchResults.value[index]
} else {
return slides.value[index]
}
}
}
extension StockViewModel : UITableViewDataSource {
// MARK: - TableView
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searchController.isActive {
return searchResults.value.count
} else {
return slides.value.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: self.cellIdentifier, for: indexPath) as! SlideCell
if searchController.isActive {
cell.configureCell(slide: searchResults.value[indexPath.row])
} else {
cell.configureCell(slide: slides.value[indexPath.row])
}
return cell
}
}
extension StockViewModel: UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
self.searchResults.value = self.slides.value.filter {
$0.title.lowercased().contains(searchController.searchBar.text!.lowercased())
}
}
}
| mit | 2cb56ef40c0cced3f990d65bc558da63 | 30.039474 | 115 | 0.624417 | 4.814286 | false | false | false | false |
ozgurersil/EngageyaIOSSDK | EngageyaIOSSDK/Classes/EngageyaCreativesView.swift | 1 | 11120 | //
// CreativesView.swift
// Pods
//
// Created by ozgur ersil on 25/07/2017.
//
//
import UIKit
import Foundation
func getDataFromUrl(_ url:String, completion: @escaping ((_ data: Data?) -> Void)) {
URLSession.shared.dataTask(with: URL(string: url)!, completionHandler: { (data, response, error) in
if let newData = data {
completion(NSData(data: newData) as Data)
}
else{
print("creative did not loaded")
}
}) .resume()
}
public class EngageyaCreativesView: NSObject, UITableViewDelegate , UITableViewDataSource , UICollectionViewDelegate , UICollectionViewDataSource {
public var tableView:UITableView?
public var cView:UICollectionView?
public var items = [EngageyaBox]()
public var imageCache = Dictionary<String, UIImage>()
public var eventManager:EventManager = EventManager()
var titleLabel:UILabel = {
let descLabel = UILabel(frame: CGRect(x:Int(5), y: 0, width: Int(UIScreen.main.bounds.width) , height: 40))
descLabel.textAlignment = .left
descLabel.lineBreakMode = .byWordWrapping
descLabel.font = UIFont.boldSystemFont(ofSize: 18.0)
descLabel.numberOfLines = 1
descLabel.textColor = UIColor(hex: 0x202020)
return descLabel
}()
public override init(){
super.init()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
public func getEventManager()->EventManager{
return self.eventManager
}
// get widget data
public func getWidgetData(url:String, compliation:@escaping (_ widget:EngageyaWidget)->()){
let url = JSONRequestHandler.createURL(url: url)
JSONRequestHandler.getWidgetJSONResponse(url: url) { (bool, widget) in
if !bool{
print("error with JSON url - please check your id collection")
return
}
compliation(widget)
}
}
// get collectionView
public func createCollectionView(url:String ,options:[String:Any]?,compliation:@escaping (_ widget:UIView)->()){
NotificationCenter.default.addObserver(self, selector: #selector(self.rotated), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
let url = JSONRequestHandler.createURL(url: url)
JSONRequestHandler.getWidgetJSONResponse(url: url) { (bool, widget) in
if !bool{
print("error with JSON url - please check your id collection")
return
}
// set optionals if exist
if let definedOptions = options {
OptionalsCheck.checkOptionals(idCollection: definedOptions, type: .collectionView)
}
// set data arrayˆ
self.items = widget.boxes!
let holderView:UIView = UIView(frame: UIScreen.main.bounds)
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 5, left: 5, bottom: 0 , right: 5)
var calculateHeight = 0
if (OptionalParams.direction == .horizontal){
layout.itemSize = CGSize(width: (200) , height: CGFloat(OptionalParams.tileHeight))
layout.scrollDirection = .horizontal
calculateHeight = Int(OptionalParams.tileHeight)
}
else{
layout.itemSize = CGSize(width: (UIScreen.main.bounds.width/CGFloat(OptionalParams.tileRowCount) - CGFloat(OptionalParams.tilePadding)) , height: CGFloat(OptionalParams.tileHeight))
if let heightDefined = OptionalParams.widgetHeight {
calculateHeight = heightDefined
}
else{
calculateHeight = Int(Double(self.items.count / OptionalParams.tileRowCount) * Double(OptionalParams.tileHeight) + Double(self.items.count / OptionalParams.tileRowCount))
}
}
let rect = CGRect(x: 0, y: 40, width: UIScreen.main.bounds.width, height: CGFloat(calculateHeight+10))
self.cView = UICollectionView(frame: rect, collectionViewLayout: layout)
self.cView?.register(EngageyaCollectionViewCell.self, forCellWithReuseIdentifier: "goCell")
self.cView?.dataSource = self
self.cView?.delegate = self
self.cView?.backgroundColor = UIColor.white
holderView.addSubview(self.titleLabel)
holderView.addSubview(self.cView!)
DispatchQueue.main.async {
self.titleLabel.text = widget.widgetTitle!
compliation(holderView)
}
}
}
// get tableView
public func createListView(url:String, options:[String:Any]?,compliation:@escaping (_ widget:UIView)->()){
let url = JSONRequestHandler.createURL(url: url)
JSONRequestHandler.getWidgetJSONResponse(url: url) { (bool, widget) in
if !bool{
print("error with JSON url - please check your id collection")
return
}
// set optionals if exist
if let definedOptions = options {
OptionalsCheck.checkOptionals(idCollection: definedOptions, type: .tableView)
}
// set data array
self.items = widget.boxes!
// create tableView and its holder
let holderView:UIView = UIView(frame: UIScreen.main.bounds)
var rect = CGRect(x: 0.0, y: 40.0, width: Double(OptionalParams.cellWidth), height: Double(self.items.count) * OptionalParams.tileHeight)
if let widgetHeight = OptionalParams.widgetHeight {
rect = CGRect(x: 0.0, y: 40.0, width: Double(OptionalParams.cellWidth), height: Double(widgetHeight))
}
self.tableView = UITableView(frame: rect, style: .plain)
self.tableView?.register(EngageyaTableViewCell.self, forCellReuseIdentifier: "box")
self.tableView?.separatorStyle = .none
self.tableView?.delegate = self
self.tableView?.dataSource = self
self.tableView?.alwaysBounceVertical = false
holderView.addSubview(self.titleLabel)
holderView.addSubview(self.tableView!)
DispatchQueue.main.async {
self.titleLabel.text = widget.widgetTitle
compliation(holderView)
}
}
}
// Detect orientation changes
func rotated() {
}
// CollectionView Overrides
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.items.count
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let tile = self.items[indexPath.row]
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "goCell", for: indexPath) as! EngageyaCollectionViewCell
cell.tag = (indexPath as NSIndexPath).row
if let title = tile.title{
cell.titleLabelMutual?.text = String(htmlEncodedString:title)
}
cell.titleLabelMutual?.frame.size.width = CGFloat(cell.frame.width) - 10
cell.titleLabelMutual?.sizeToFit()
cell.titleLabelMutual?.frame.origin.y = CGFloat(OptionalParams.imageHeight) + CGFloat(OptionalParams.titlePaddingTop)
cell.advertiserNameLabel?.frame.origin.y = (cell.titleLabelMutual?.frame.height)! + CGFloat(OptionalParams.imageHeight) + 3
if let displayName = tile.displayName {
cell.advertiserNameLabel?.text = String(htmlEncodedString:displayName)
}
else{
cell.advertiserNameLabel?.text = ""
}
if let imageURL = (tile.thumbnail_path) {
getDataFromUrl("https:"+imageURL) { data in
DispatchQueue.main.async {
if(cell.tag == (indexPath as NSIndexPath).row){
let image = UIImage(data: data!)
cell.homeImageView?.image = image
}
}
}
}
return cell
}
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
self.eventManager.trigger(eventName: "tapped", information: items[indexPath.row])
}
public func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
//TableView Overrides
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return CGFloat(OptionalParams.tileHeight)
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.eventManager.trigger(eventName: "tapped", information: items[indexPath.row])
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let box = self.items[indexPath.row]
let cell = self.tableView?.dequeueReusableCell(withIdentifier: "box", for: indexPath) as! EngageyaTableViewCell
cell.tag = (indexPath as NSIndexPath).row
cell.titleLabelMutual.text = String(htmlEncodedString: box.title)
if let displayName = box.displayName {
cell.advertiserNameLabel.text = String(htmlEncodedString:displayName)
}
let padding = Int(OptionalParams.imagePaddingLeft) + Int(OptionalParams.imageWidth) + Int(OptionalParams.titlePaddingLeft)
cell.titleLabelMutual.frame.size.width = CGFloat(OptionalParams.cellWidth) - CGFloat(padding)
cell.titleLabelMutual.sizeToFit()
cell.advertiserNameLabel.frame.origin.x = cell.titleLabelMutual.frame.origin.x
cell.advertiserNameLabel.frame.origin.y = cell.titleLabelMutual.frame.height + cell.titleLabelMutual.frame.origin.y + 3
let thumbnailURL = "https:\(box.thumbnail_path!)"
getDataFromUrl(thumbnailURL) { data in
DispatchQueue.main.async {
if(cell.tag == (indexPath as NSIndexPath).row) {
let image = UIImage(data: data!)
self.imageCache[String(box.thumbnail_path)] = image
cell.homeImageView.image = image
}
}
}
return cell
}
}
| mit | c99f35a2a3f365359fb96c85836f2782 | 40.488806 | 197 | 0.600863 | 5.358554 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.