repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
711k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
DiegoSan1895/Smartisan-Notes
|
refs/heads/master
|
Smartisan-Notes/Constants.swift
|
mit
|
1
|
//
// Configs.swift
// Smartisan-Notes
//
// Created by DiegoSan on 3/4/16.
// Copyright © 2016 DiegoSan. All rights reserved.
//
import UIKit
let isNotFirstOpenSmartisanNotes = "isNotFirstOpenSmartisanNotes"
let ueAgreeOrNot = "userAgreeToJoinUEPlan"
let NSBundleURL = NSBundle.mainBundle().bundleURL
struct AppID {
static let notesID = 867934588
static let clockID = 828812911
static let syncID = 880078620
static let calenderID = 944154964
}
struct AppURL {
static let clockURL = NSURL(string: "smartisanclock://")!
static let syncURL = NSURL(string: "smartisansync://")!
static let calenderURL = NSURL(string: "smartisancalendar://")!
static let smartisanWeb = NSURL(string: "https://store.smartisan.com")!
}
struct AppItunsURL {
let baseURLString = "http://itunes.apple.com/us/app/id"
static let calenderURL = NSURL(string: "http://itunes.apple.com/us/app/id\(AppID.calenderID)")!
static let syncURL = NSURL(string: "http://itunes.apple.com/us/app/id\(AppID.syncID)")!
static let clockURL = NSURL(string: "http://itunes.apple.com/us/app/id\(AppID.clockID)")!
static let notesURL = NSURL(string: "http://itunes.apple.com/us/app/id\(AppID.notesID)")!
}
struct AppShareURL {
static let notesURL = NSURL(string: "https://itunes.apple.com/us/app/smartisan-notes/id867934588?ls=1&mt=8")!
}
struct iPhoneInfo{
static let iOS_Version = UIDevice.currentDevice().systemVersion
static let deviceName = NSString.deviceName() as String
}
struct AppInfo{
static let App_Version = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String
}
struct Configs {
struct Weibo {
static let appID = "1682079354"
static let appKey = "94c42dacce2401ad73e5080ccd743052"
static let redirectURL = "http://www.limon.top"
}
struct Wechat {
static let appID = "wx4868b35061f87885"
static let appKey = "64020361b8ec4c99936c0e3999a9f249"
}
struct QQ {
static let appID = "1104881792"
}
struct Pocket {
static let appID = "48363-344532f670a052acff492a25"
static let redirectURL = "pocketapp48363:authorizationFinished" // pocketapp + $prefix + :authorizationFinished
}
struct Alipay {
static let appID = "2016012101112529"
}
}
|
106a1f612919be5defa706c60098cd68
| 29.25641 | 119 | 0.690971 | false | false | false | false |
MaartenBrijker/project
|
refs/heads/back
|
project/External/AudioKit-master/AudioKit/Common/MIDI/AKMIDI+ReceivingMIDI.swift
|
apache-2.0
|
1
|
//
// AKMIDI+ReceivingMIDI.swift
// AudioKit For OSX
//
// Created by Aurelius Prochazka on 4/30/16.
// Copyright © 2016 AudioKit. All rights reserved.
//
extension AKMIDI {
/// Array of input names
public var inputNames: [String] {
var nameArray = [String]()
let sourceCount = MIDIGetNumberOfSources()
for i in 0 ..< sourceCount {
let source = MIDIGetSource(i)
var inputName: Unmanaged<CFString>?
inputName = nil
MIDIObjectGetStringProperty(source, kMIDIPropertyName, &inputName)
let inputNameStr = (inputName?.takeRetainedValue())! as String
nameArray.append(inputNameStr)
}
return nameArray
}
/// Add a listener to the listeners
public func addListener(listener: AKMIDIListener) {
listeners.append(listener)
}
/// Open a MIDI Input port
///
/// - parameter namedInput: String containing the name of the MIDI Input
///
public func openInput(namedInput: String = "") {
var result = noErr
let sourceCount = MIDIGetNumberOfSources()
for i in 0 ..< sourceCount {
let src = MIDIGetSource(i)
var tempName: Unmanaged<CFString>? = nil
MIDIObjectGetStringProperty(src, kMIDIPropertyName, &tempName)
let inputNameStr = (tempName?.takeRetainedValue())! as String
if namedInput.isEmpty || namedInput == inputNameStr {
inputPorts.append(MIDIPortRef())
var port = inputPorts.last!
result = MIDIInputPortCreateWithBlock(
client, inputPortName, &port, MyMIDIReadBlock)
if result != noErr {
print("Error creating midiInPort : \(result)")
}
MIDIPortConnectSource(port, src, nil)
}
}
}
internal func handleMidiMessage(event: AKMIDIEvent) {
for listener in listeners {
let type = event.status
switch type {
case AKMIDIStatus.ControllerChange:
listener.receivedMIDIController(Int(event.internalData[1]),
value: Int(event.internalData[2]),
channel: Int(event.channel))
case AKMIDIStatus.ChannelAftertouch:
listener.receivedMIDIAfterTouch(Int(event.internalData[1]),
channel: Int(event.channel))
case AKMIDIStatus.NoteOn:
listener.receivedMIDINoteOn(Int(event.internalData[1]),
velocity: Int(event.internalData[2]),
channel: Int(event.channel))
case AKMIDIStatus.NoteOff:
listener.receivedMIDINoteOff(Int(event.internalData[1]),
velocity: Int(event.internalData[2]),
channel: Int(event.channel))
case AKMIDIStatus.PitchWheel:
listener.receivedMIDIPitchWheel(Int(event.data),
channel: Int(event.channel))
case AKMIDIStatus.PolyphonicAftertouch:
listener.receivedMIDIAftertouchOnNote(Int(event.internalData[1]),
pressure: Int(event.internalData[2]),
channel: Int(event.channel))
case AKMIDIStatus.ProgramChange:
listener.receivedMIDIProgramChange(Int(event.internalData[1]),
channel: Int(event.channel))
case AKMIDIStatus.SystemCommand:
listener.receivedMIDISystemCommand(event.internalData)
}
}
}
internal func MyMIDINotifyBlock(midiNotification: UnsafePointer<MIDINotification>) {
_ = midiNotification.memory
//do something with notification - change _ above to let varname
//print("MIDI Notify, messageId= \(notification.messageID.rawValue)")
}
internal func MyMIDIReadBlock(
packetList: UnsafePointer<MIDIPacketList>,
srcConnRefCon: UnsafeMutablePointer<Void>) -> Void {
/*
//can't yet figure out how to access the port passed via srcConnRefCon
//maybe having this port is not that necessary though...
let midiPortPointer = UnsafeMutablePointer<MIDIPortRef>(srcConnRefCon)
let midiPort = midiPortPointer.memory
*/
for packet in packetList.memory {
// a coremidi packet may contain multiple midi events
for event in packet {
handleMidiMessage(event)
}
}
}
}
|
c3b87202f4e74efe53a66d360dc70f84
| 40.216667 | 91 | 0.548231 | false | false | false | false |
LoveZYForever/HXWeiboPhotoPicker
|
refs/heads/master
|
Pods/HXPHPicker/Sources/HXPHPicker/Editor/Controller/Photo/PhotoEditorViewController+Animation.swift
|
mit
|
1
|
//
// PhotoEditorViewController+Animation.swift
// HXPHPicker
//
// Created by Slience on 2021/7/14.
//
import UIKit
extension PhotoEditorViewController {
func showChartletView() {
UIView.animate(withDuration: 0.25) {
self.setChartletViewFrame()
}
}
func hiddenChartletView() {
UIView.animate(withDuration: 0.25) {
self.setChartletViewFrame()
}
}
func showFilterView() {
UIView.animate(withDuration: 0.25) {
self.setFilterViewFrame()
}
}
func hiddenFilterView() {
UIView.animate(withDuration: 0.25) {
self.setFilterViewFrame()
}
}
func showBrushColorView() {
brushColorView.isHidden = false
UIView.animate(withDuration: 0.25) {
self.brushColorView.alpha = 1
}
}
func hiddenBrushColorView() {
if brushColorView.isHidden {
return
}
UIView.animate(withDuration: 0.25) {
self.brushColorView.alpha = 0
} completion: { (_) in
guard let option = self.currentToolOption,
option.type == .graffiti else {
return
}
self.brushColorView.isHidden = true
}
}
func showMosaicToolView() {
mosaicToolView.isHidden = false
UIView.animate(withDuration: 0.25) {
self.mosaicToolView.alpha = 1
}
}
func hiddenMosaicToolView() {
if mosaicToolView.isHidden {
return
}
UIView.animate(withDuration: 0.25) {
self.mosaicToolView.alpha = 0
} completion: { (_) in
guard let option = self.currentToolOption,
option.type == .mosaic else {
return
}
self.mosaicToolView.isHidden = true
}
}
func croppingAction() {
if state == .cropping {
cropConfirmView.isHidden = false
cropToolView.isHidden = false
hidenTopView()
}else {
if let option = currentToolOption {
if option.type == .graffiti {
imageView.drawEnabled = true
}else if option.type == .mosaic {
imageView.mosaicEnabled = true
}
}
showTopView()
}
UIView.animate(withDuration: 0.25) {
self.cropConfirmView.alpha = self.state == .cropping ? 1 : 0
self.cropToolView.alpha = self.state == .cropping ? 1 : 0
} completion: { (isFinished) in
if self.state != .cropping {
self.cropConfirmView.isHidden = true
self.cropToolView.isHidden = true
}
}
}
func showTopView() {
topViewIsHidden = false
toolView.isHidden = false
topView.isHidden = false
if let option = currentToolOption {
if option.type == .graffiti {
brushColorView.isHidden = false
}else if option.type == .mosaic {
mosaicToolView.isHidden = false
}
}else {
imageView.stickerEnabled = true
}
UIView.animate(withDuration: 0.25) {
self.toolView.alpha = 1
self.topView.alpha = 1
self.topMaskLayer.isHidden = false
if let option = self.currentToolOption {
if option.type == .graffiti {
self.brushColorView.alpha = 1
}else if option.type == .mosaic {
self.mosaicToolView.alpha = 1
}
}
}
}
func hidenTopView() {
topViewIsHidden = true
UIView.animate(withDuration: 0.25) {
self.toolView.alpha = 0
self.topView.alpha = 0
self.topMaskLayer.isHidden = true
if let option = self.currentToolOption {
if option.type == .graffiti {
self.brushColorView.alpha = 0
}else if option.type == .mosaic {
self.mosaicToolView.alpha = 0
}
}
} completion: { (isFinished) in
if self.topViewIsHidden {
self.toolView.isHidden = true
self.topView.isHidden = true
self.brushColorView.isHidden = true
self.mosaicToolView.isHidden = true
}
}
}
}
|
91ca0375669ab209de5eeff809e9563c
| 29.214765 | 72 | 0.51355 | false | false | false | false |
mathewsheets/SwiftLearningAssignments
|
refs/heads/master
|
Todo_Assignment_2.playground/Contents.swift
|
mit
|
1
|
/*:
* callout(Assignment): Based on Sessions 1-7 (specifically Collection Types, Functions, Closures, Enumerations), create a playground that will manage your todos.
**You will need to:**
- Print all your Todos (small description)
- Print a single Todo (large description)
- Add a Todo
- Update a Todo
- Delete a Todo
**Constraints:**
- Model a Todo
- Create functions to:
- Get all your Todos
- Get a single Todo passing an id as an argument
- Add a Todo
- Update a Todo
- Delete a Todo
*/
import Foundation
func printTodos(todos: [Todo]) {
each(todos: todos) { (todo, index) -> Void in
print("\t\(todo.0): \(todo.1) = \(todo.4)")
}
}
initData()
print("Print all your Todos (small description)")
printTodos(todos: todos)
print("\nPrint a single Todo (large description)")
var study = getTodo(id: "1")!
print("\t\(description(todo: study))\n")
print("Add a Todo")
let sweep = createTodo(title: "Sweep", subtitle: "The stairs need a cleaning", description: "Sweep the stairs and then the bedrooms")
addTodo(todo: sweep)
printTodos(todos: todos)
print("\nUpdate a Todo")
updateTodo(todo: (study.0, study.1, study.2, study.3, Status.Completed))
study = getTodo(id: "1")!
print("\t\(description(todo: study))")
print("\nDelete a Todo")
let weed = deleteTodo(id: "0")!
print("\t\(description(todo: weed))\n")
print("Updated list of Todos")
printTodos(todos: todos)
print("\nDisplay only non completed todos")
let nonComplete = filter(todos: todos) { $0.4 != .Completed }
printTodos(todos: nonComplete ?? [])
|
6112c1b4e6af1bfd9ae0bbbda6c8b151
| 26.086207 | 162 | 0.677276 | false | false | false | false |
t4thswm/Course
|
refs/heads/master
|
Course/CourseMainViewController.swift
|
gpl-3.0
|
1
|
//
// CourseMainViewController.swift
// Course
//
// Created by Cedric on 2016/12/8.
// Copyright © 2016年 Archie Yu. All rights reserved.
//
import UIKit
import CourseModel
class CourseMainViewController: UIViewController, UIPageViewControllerDelegate, UIPageViewControllerDataSource, UIPickerViewDataSource, UIPickerViewDelegate {
var coursePageVC: UIPageViewController!
var dayControllers: [DisplayCoursesViewController] = []
var nextWeekday = 0
var selectingWeek = false
var editView: UIView!
var labelView: UILabel!
var pickerView: UIPickerView!
let offset: CGFloat = -18
@IBOutlet weak var titleButton: UIButton!
@IBOutlet weak var weekdayPageControl: UIPageControl!
override func viewDidLoad() {
super.viewDidLoad()
self.automaticallyAdjustsScrollViewInsets = false
resumeWeek()
load(from: courseDataFilePath())
for vc in self.childViewControllers {
if vc is UIPageViewController {
coursePageVC = vc as! UIPageViewController
}
}
coursePageVC.delegate = self
coursePageVC.dataSource = self
weekdayPageControl.numberOfPages = weekdayNum
for i in 0..<7 {
dayControllers.append(
storyboard?.instantiateViewController(withIdentifier: "DayCourse") as!
DisplayCoursesViewController)
dayControllers[i].weekday = i
}
titleButton.titleLabel?.font = .boldSystemFont(ofSize: 17)
let width = UIScreen.main.bounds.width
var frame = CGRect(x: 0, y: -224, width: width, height: 224)
editView = UIView(frame: frame)
editView.backgroundColor = UIColor(white: 0.05, alpha: 1)
self.view.addSubview(editView)
frame = CGRect(x: offset, y: -100, width: width, height: 40)
labelView = UILabel(frame: frame)
labelView.text = "当前为第\t\t\t星期"
labelView.textColor = .white
labelView.textAlignment = .center
self.view.addSubview(labelView)
frame = CGRect(x: 0, y: -162, width: width, height: 162)
pickerView = UIPickerView(frame: frame)
pickerView.dataSource = self
pickerView.delegate = self
self.view.addSubview(pickerView)
}
override func viewWillAppear(_ animated: Bool) {
if needReload {
weekdayPageControl.numberOfPages = weekdayNum
var weekday = (Calendar.current.dateComponents([.weekday], from: Date()).weekday! + 5) % 7
if weekday >= weekdayNum { weekday = 0 }
weekdayPageControl.currentPage = weekday
coursePageVC.setViewControllers(
[dayControllers[weekday]], direction: .forward, animated: false, completion: nil)
needReload = false
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
let nextWeekday = (weekdayPageControl.currentPage + 1) % weekdayNum
return dayControllers[nextWeekday]
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
let nextWeekday = (weekdayPageControl.currentPage + weekdayNum - 1) % weekdayNum
return dayControllers[nextWeekday]
}
func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) {
if let displayController = pendingViewControllers[0] as? DisplayCoursesViewController {
nextWeekday = displayController.weekday
}
}
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
if completed {
weekdayPageControl.currentPage = nextWeekday
}
}
@IBAction func changeWeek(_ sender: UIButton) {
let width = UIScreen.main.bounds.width
if selectingWeek {
titleButton.setTitle("课程", for: .normal)
titleButton.titleLabel?.font = .boldSystemFont(ofSize: 17)
let frame = CGRect(x: 0, y: -224, width: width, height: 224)
let labelFrame = CGRect(x: offset, y: -100, width: width, height: 40)
let pickerFrame = CGRect(x: 0, y: -162, width: width, height: 162)
UIView.animate(withDuration: 0.5, animations: {() -> Void in
self.editView.frame = frame
self.labelView.frame = labelFrame
self.pickerView.frame = pickerFrame
})
courseWeek = pickerView.selectedRow(inComponent: 0) + 1
relevantWeek = Calendar.current.dateComponents([.weekOfYear], from: Date()).weekOfYear!
let userDefault = UserDefaults(suiteName: "group.studio.sloth.Course")
userDefault?.set(courseWeek, forKey: "CourseWeek")
userDefault?.set(relevantWeek, forKey: "RelevantWeek")
userDefault?.synchronize()
for controller in dayControllers {
for i in 0..<lessonList.count {
lessonList[i].removeAll()
}
for course in courseList {
for lesson in course.lessons {
if lesson.firstWeek <= courseWeek && lesson.lastWeek >= courseWeek && (lesson.alternate == 3 || (lesson.alternate % 2) == (courseWeek % 2)) {
lessonList[lesson.weekday].append(lesson)
}
}
}
for i in 0..<lessonList.count {
lessonList[i].sort() { $0.firstClass < $1.firstClass }
}
(controller.view as! UITableView).reloadData()
}
} else {
resumeWeek()
pickerView.selectRow(courseWeek - 1, inComponent: 0, animated: false)
titleButton.setTitle("确认", for: .normal)
titleButton.titleLabel?.font = .boldSystemFont(ofSize: 21)
let frame = CGRect(x: 0, y: 0, width: width, height: 224)
let labelFrame = CGRect(x: offset, y: 124, width: width, height: 40)
let pickerFrame = CGRect(x: 0, y: 64, width: width, height: 162)
UIView.animate(withDuration: 0.5, animations: {() -> Void in
self.editView.frame = frame
self.labelView.frame = labelFrame
self.pickerView.frame = pickerFrame
})
}
selectingWeek = !selectingWeek
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return weekNum
}
func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
return 40
}
func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
let label = UILabel()
label.text = "\(row + 1)"
label.textColor = .white
label.font = UIFont.systemFont(ofSize: 28)
label.textAlignment = .center
return label
}
}
|
3363c5c0d6a5fce628a134de05df63bb
| 37.929648 | 190 | 0.606428 | false | false | false | false |
mownier/photostream
|
refs/heads/master
|
Photostream/Modules/Liked Post/Presenter/LikedPostPresenter.swift
|
mit
|
1
|
//
// LikedPostPresenter.swift
// Photostream
//
// Created by Mounir Ybanez on 19/01/2017.
// Copyright © 2017 Mounir Ybanez. All rights reserved.
//
protocol LikedPostPresenterInterface: BaseModulePresenter, BaseModuleInteractable {
var userId: String! { set get }
var posts: [LikedPostData] { set get }
var limit: UInt { set get }
func indexOf(post id: String) -> Int?
func appendPosts(_ data: [LikedPostData])
}
class LikedPostPresenter: LikedPostPresenterInterface {
typealias ModuleInteractor = LikedPostInteractorInput
typealias ModuleView = LikedPostScene
typealias ModuleWireframe = LikedPostWireframeInterface
weak var view: ModuleView!
var interactor: ModuleInteractor!
var wireframe: ModuleWireframe!
var userId: String!
var posts = [LikedPostData]()
var limit: UInt = 10
func indexOf(post id: String) -> Int? {
return posts.index { item -> Bool in
return item.id == id
}
}
func appendPosts(_ data: [LikedPostData]) {
let filtered = data.filter { post in
return indexOf(post: post.id) == nil
}
posts.append(contentsOf: filtered)
}
}
extension LikedPostPresenter: LikedPostModuleInterface {
var postCount: Int {
return posts.count
}
func exit() {
var property = WireframeExitProperty()
property.controller = view.controller
wireframe.exit(with: property)
}
func viewDidLoad() {
view.isLoadingViewHidden = false
interactor.fetchNew(userId: userId, limit: limit)
}
func refresh() {
view.isEmptyViewHidden = true
view.isRefreshingViewHidden = false
interactor.fetchNew(userId: userId, limit: limit)
}
func loadMore() {
interactor.fetchNext(userId: userId, limit: limit)
}
func unlikePost(at index: Int) {
guard var post = post(at: index), post.isLiked else {
view.reload(at: index)
return
}
post.isLiked = false
post.likes -= 1
posts[index] = post
view.reload(at: index)
interactor.unlikePost(id: post.id)
}
func likePost(at index: Int) {
guard var post = post(at: index), !post.isLiked else {
view.reload(at: index)
return
}
post.isLiked = true
post.likes += 1
posts[index] = post
view.reload(at: index)
interactor.likePost(id: post.id)
}
func toggleLike(at index: Int) {
guard let post = post(at: index) else {
view.reload(at: index)
return
}
if post.isLiked {
unlikePost(at: index)
} else {
likePost(at: index)
}
}
func post(at index: Int) -> LikedPostData? {
guard posts.isValid(index) else {
return nil
}
return posts[index]
}
}
extension LikedPostPresenter: LikedPostInteractorOutput {
func didRefresh(data: [LikedPostData]) {
view.isLoadingViewHidden = true
view.isRefreshingViewHidden = true
posts.removeAll()
appendPosts(data)
if postCount == 0 {
view.isEmptyViewHidden = false
}
view.didRefresh(error: nil)
view.reload()
}
func didLoadMore(data: [LikedPostData]) {
view.didLoadMore(error: nil)
guard data.count > 0 else {
return
}
appendPosts(data)
view.reload()
}
func didRefresh(error: PostServiceError) {
view.isLoadingViewHidden = true
view.isRefreshingViewHidden = true
view.didRefresh(error: error.message)
}
func didLoadMore(error: PostServiceError) {
view.didLoadMore(error: error.message)
}
func didLike(error: PostServiceError?, postId: String) {
view.didLike(error: error?.message)
guard let index = indexOf(post: postId),
var post = post(at: index),
error != nil else {
return
}
post.isLiked = false
if post.likes > 0 {
post.likes -= 1
}
posts[index] = post
view.reload(at: index)
}
func didUnlike(error: PostServiceError?, postId: String) {
view.didUnlike(error: error?.message)
guard let index = indexOf(post: postId),
var post = post(at: index),
error != nil else {
return
}
post.isLiked = true
post.likes += 1
posts[index] = post
view.reload(at: index)
}
}
|
e668d844b7379a76664c723fe93be493
| 23.262376 | 83 | 0.550704 | false | false | false | false |
ReactiveKit/ReactiveGitter
|
refs/heads/master
|
Views/View Controllers/Authentication.swift
|
mit
|
1
|
//
// AuthenticationViewController.swift
// ReactiveGitter
//
// Created by Srdan Rasic on 15/01/2017.
// Copyright © 2017 ReactiveKit. All rights reserved.
//
import UIKit
extension ViewController {
public class Authentication: UIViewController {
public private(set) lazy var titleLabel = UILabel().setup {
$0.text = "Reactive Gitter"
$0.font = .preferredFont(forTextStyle: .title1)
}
public private(set) lazy var loginButton = UIButton(type: .system).setup {
$0.setTitle("Log in", for: .normal)
}
public init() {
super.init(nibName: nil, bundle: nil)
view.backgroundColor = .white
view.addSubview(titleLabel)
titleLabel.center(in: view)
view.addSubview(loginButton)
loginButton.center(in: view, offset: .init(x: 0, y: 60))
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
}
|
40aff54d99866ab2bc3adf67ad980d0b
| 23.179487 | 78 | 0.658537 | false | false | false | false |
izotx/iTenWired-Swift
|
refs/heads/master
|
Conference App/SocialMediaCell.swift
|
bsd-2-clause
|
1
|
// Copyright (c) 2016, Izotx
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of Izotx nor the names of its contributors may be used to
// endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
// SocialMediaCell.swift
// Conference App
//
// Created by Felipe on 5/17/16.
import UIKit
import UIKit
class SocialMediaCell: UITableViewCell {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var logo: UIImageView!
func setName(name:String){
self.nameLabel.text = name
}
func setlogo(logo:String){
let image = UIImage(named: logo)
self.logo.image = image
}
func build(socialItem: SocialItem){
self.UIConfig()
self.setName(socialItem.name)
self.setlogo(socialItem.logo)
}
internal func UIConfig(){
self.backgroundColor = ItenWiredStyle.background.color.mainColor
self.nameLabel.textColor = ItenWiredStyle.text.color.mainColor
}
}
|
32801b5b2f6576840d95b16717d59e88
| 36.68254 | 82 | 0.711757 | false | false | false | false |
leizh007/HiPDA
|
refs/heads/master
|
HiPDA/HiPDA/Sections/Message/MessageNavigationBarTitleView.swift
|
mit
|
1
|
//
// MessageNavigationBarTitleView.swift
// HiPDA
//
// Created by leizh007 on 2017/6/27.
// Copyright © 2017年 HiPDA. All rights reserved.
//
import UIKit
protocol MesssageNavigationBarTitleViewDelegate: class {
func itemDidSelect(_ index: Int)
}
class MessageNavigationBarTitleView: UIView {
@IBOutlet private var messagesCountLabels: [UILabel]!
@IBOutlet private var messageLabels: [UILabel]!
weak var delegate: MesssageNavigationBarTitleViewDelegate?
private var lastSelectedIndex = 0
var model: UnReadMessagesCountModel! {
didSet {
messagesCountLabels[0].text = "\(model.threadMessagesCount)"
messagesCountLabels[1].text = "\(model.privateMessagesCount)"
messagesCountLabels[2].text = "\(model.friendMessagesCount)"
messagesCountLabels[0].isHidden = model.threadMessagesCount == 0
messagesCountLabels[1].isHidden = model.privateMessagesCount == 0
messagesCountLabels[2].isHidden = model.friendMessagesCount == 0
}
}
@IBAction private func messagesContainerViewDidTapped(_ sender: UITapGestureRecognizer) {
let tag = sender.view?.tag ?? 0
select(index: tag)
if lastSelectedIndex != tag {
lastSelectedIndex = tag
delegate?.itemDidSelect(tag)
} else {
NotificationCenter.default.post(name: .MessageViewControllerTabRepeatedSelected, object: nil)
}
}
func configureApperance(with offset: CGFloat) {
var lowerIndex = Int(floor(offset))
if lowerIndex < 0 {
lowerIndex = 0
}
var upperIndex = Int(ceil(offset))
if upperIndex >= messagesCountLabels.count {
upperIndex = messagesCountLabels.count - 1
}
let lowerFactor = 1 - (offset - CGFloat(lowerIndex))
let upperFactor = 1 - (CGFloat(upperIndex) - offset)
for (index, factor) in zip([lowerIndex, upperIndex], [lowerFactor, upperFactor]) {
messageLabels[index].textColor = UIColor(red: (101.0 - 72 * factor) / 255.0,
green: (119.0 + 43 * factor) / 255.0,
blue: (134.0 + 108 * factor) / 255.0,
alpha: 1.0)
messageLabels[index].transform = CGAffineTransform(scaleX: 1.0 - 2.0 * (1 - factor) / 17.0,
y: 1.0 - 2.0 * (1 - factor) / 17.0)
}
lastSelectedIndex = Int(round(offset))
}
func select(index: Int) {
guard index >= 0 && index < messageLabels.count else { return }
UIView.animate(withDuration: C.UI.animationDuration) {
for i in 0..<self.messageLabels.count {
let label = self.messageLabels[i]
if i == index {
label.transform = .identity
label.textColor = #colorLiteral(red: 0.1137254902, green: 0.6352941176, blue: 0.9490196078, alpha: 1)
} else {
label.transform = CGAffineTransform(scaleX: 15.0 / 17.0, y: 15.0 / 17.0)
label.textColor = #colorLiteral(red: 0.3960784314, green: 0.4666666667, blue: 0.5254901961, alpha: 1)
}
}
}
}
}
|
bbf6fd3013671a35254c2422c6a962e7
| 41.4375 | 121 | 0.569367 | false | false | false | false |
vchuo/Photoasis
|
refs/heads/master
|
Photoasis/Classes/Views/Views/ImageViewer/POImageViewerLinkedImageView.swift
|
mit
|
1
|
//
// POImageViewerLinkedImageView.swift
// イメージビューアとリンクしているイメージビュー。
// このクラスを使用するには、UIImageViewを使う場所はPOImageViewerLinkedImageViewを入れるだけ。
// イメージビューアを開くに必要なボタンなどは自動で生成する。
//
// 使用上の注意:
// ・POImageViewerLinkedImageViewのポジションとサイズを設定する時に、必ず
// 用意しているupdateOriginとupdateSizeのファンクションを使う。このビューに
// 関連するオーバーレイボタンのポジションとサイズの調整も必要から。
//
// Created by Vernon Chuo Chian Khye on 2017/02/26.
// Copyright © 2017 Vernon Chuo Chian Khye. All rights reserved.
//
import UIKit
import RxSwift
import ChuoUtil
class POImageViewerLinkedImageView: UIImageView {
// MARK: - Public Properties
// イメージビューアーモードを有効するか
var imageViewerModeEnabled: Bool = true
// 著者名
private var _photoAuthorName = ""
var photoAuthorName: String {
get { return _photoAuthorName }
set(newValue) { _photoAuthorName = newValue }
}
// オーバーレイボタン
var overlayButtonAction: (() -> Void)? // オーバーレイボタンに関連するアクション
var overlayButtonPressBeganEventCallback: (() -> Void)? // オーバーレイボタンプレス開始時のコールバック
var overlayButtonPressEndedEventCallback: (() -> Void)? // オーバーレイボタンプレス終わる時のコールバック
var overlayButtonShouldDisplayFadeEffectWhenPressed: Bool { // オーバーレイボタンが押された時にフェード効果を表示するか
get { return overlayButton.shouldDisplayFadeEffectWhenPressed }
set(display) { overlayButton.shouldDisplayFadeEffectWhenPressed = display }
}
// MARK: - Views
private var topView = UIView()
private var parentView: UIView?
private let overlayButton = CUOverlayButtonView() // イメージビューアを開くにはオーバーレイボタンを押す
private let imageViewerScrollView = UIScrollView() // 画像を拡大するためのスクロールビュー
private let imageView = UIImageView() // 拡大・パニング用イメージビュー
private let transitionImageView = UIImageView()
private let backButtonContainerView = UIView()
private let backButtonImageView = UIImageView()
private let backButtonOverlayButton = CUOverlayButtonView()
private let shareButtonImageView = UIImageView()
private let shareButtonOverlayButton = CUOverlayButtonView()
private var authorNameView = POImageViewerAuthorNameView()
// MARK: - Private Properties
private let disposeBag = DisposeBag()
// ステート関連
private var imageViewerIsDisplaying: Bool = false
private var executingImageViewerTransitionAnimation: Bool = false
private var buttonsDisplaying: Bool = true
// アニメーション関連
private var panGestureStartCoordinate: CGPoint = CGPointZero
private var executingSwipeToHideAnimation: Bool = false
// レイアウト関連
private var imageCenterAtMinimumZoom: CGPoint = CGPointZero
// ジェスチャ認識
private var pan = UIPanGestureRecognizer()
private var singleTap = UITapGestureRecognizer()
private var doubleTap = UITapGestureRecognizer()
// MARK: - Init
init() {
super.init(frame: CGRectZero)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(frame: CGRectZero)
setup()
}
// MARK: - Public Functions
/**
ビュー起源の更新。
- parameter originX: 起源のx座標
- parameter originY: 起源のy座標
*/
func updateOrigin(originX: CGFloat? = nil, originY: CGFloat? = nil) {
if parentView == nil {
guard let superview = self.superview else { return }
superview.addSubview(overlayButton)
self.parentView = superview
}
if let originX = originX {
self.frame.origin.x = originX
overlayButton.frame.origin.x = originX
}
if let originY = originY {
self.frame.origin.y = originY
overlayButton.frame.origin.y = originY
}
}
/**
ビューの更新。
- parameter origin: 起源
- parameter size: サイズ
*/
func updateSize(width: CGFloat? = nil, height: CGFloat? = nil) {
if parentView == nil {
guard let superview = self.superview else { return }
superview.addSubview(overlayButton)
self.parentView = superview
}
if let width = width {
self.bounds.size.width = width
overlayButton.bounds.size.width = width
}
if let height = height {
self.bounds.size.height = height
overlayButton.bounds.size.height = height
}
}
/**
イメージビューを表示。
*/
func display() {
self.hidden = false
self.overlayButton.hidden = false
}
/**
イメージビューを隠す。
*/
func hide() {
self.hidden = true
self.overlayButton.hidden = true
}
/**
イメージビューアを表示。
*/
func displayImageViewer() {
guard let image = self.image else { return }
if imageViewerIsDisplaying { return }
guard let view = POUtilities.getTopViewController()?.view else { return }
guard let parentView = parentView else { return }
executingImageViewerTransitionAnimation = true
topView = view
imageViewerIsDisplaying = true
UIApplication.sharedApplication().setStatusBarHidden(true, withAnimation: .Slide)
let aspectRatio = image.size.width / image.size.height,
maxWidth = POConstants.MainScreenSize.width,
maxHeight = POConstants.MainScreenSize.height,
desiredHeight = maxWidth / aspectRatio,
size = (desiredHeight <= maxHeight) ? CGSizeMake(maxWidth, desiredHeight)
: CGSizeMake(maxHeight * aspectRatio, maxHeight)
imageViewerScrollView.zoomScale = 1
imageViewerScrollView.minimumZoomScale = POConstants.ImageViewerScrollViewMinimumZoomLevel
imageViewerScrollView.maximumZoomScale = POConstants.ImageViewerScrollViewMaximumZoomLevel
imageViewerScrollView.bounds.size = topView.bounds.size
imageViewerScrollView.center = CUHelper.centerPointOf(topView)
imageView.layer.cornerRadius = 0
imageView.transform = CGAffineTransformIdentity
imageView.bounds.size = size
imageView.center = CUHelper.centerPointOf(imageViewerScrollView)
imageView.image = image
imageViewerScrollView.contentSize = size
// 借りのイメージビュー
let startBounds = parentView.convertRect(self.bounds, toView: topView),
startScale = startBounds.width / imageView.bounds.size.width,
startOrigin = parentView.convertPoint(self.frame.origin, toView: topView),
startCenter = CGPointMake(startOrigin.x + (startBounds.width / 2), startOrigin.y + (startBounds.height / 2))
transitionImageView.bounds.size = imageView.bounds.size
transitionImageView.center = startCenter
transitionImageView.layer.cornerRadius = POConstants.HomeTableViewCellPhotoCornerRadius
transitionImageView.transform = CGAffineTransformMakeScale(startScale, startScale)
transitionImageView.image = image
// 最初ズームレベルのイメージセンターを先に計算して保存
imageCenterAtMinimumZoom = centerPointNeededToCenterImageViewInImageViewerScrollView()
// 著者名ビュー
authorNameView.updateAuthorName(_photoAuthorName)
// ボタン
backButtonContainerView.transform = POConstants.ImageViewerButtonHiddenScaleTransform
shareButtonImageView.transform = POConstants.ImageViewerButtonHiddenScaleTransform
// サブビューの追加
imageViewerScrollView.addSubview(imageView)
topView.addSubview(imageViewerScrollView)
topView.addSubview(transitionImageView)
topView.addSubview(authorNameView)
topView.addSubview(shareButtonImageView)
topView.addSubview(shareButtonOverlayButton)
topView.addSubview(backButtonContainerView)
topView.addSubview(backButtonOverlayButton)
// アニメーション前の準備
transitionImageView.alpha = 0.0
imageView.hidden = true
imageViewerScrollView.backgroundColor = UIColor.fromHexa(0xFFFFFF, alpha: 0.0)
// 表示アニメーション
CUHelper.animateKeyframes(
POConstants.ImageViewerDisplayAnimationDuration,
animations: {
UIView.addKeyframeWithRelativeStartTime(0.0, relativeDuration: 0.4) {
self.alpha = 0.0
self.transitionImageView.alpha = 1.0
}
UIView.addKeyframeWithRelativeStartTime(0.0, relativeDuration: 0.9) {
self.imageViewerScrollView.backgroundColor = UIColor.fromHexa(0xFFFFFF, alpha: POConstants.ImageViewerScrollViewBackgroundMaxAlpha)
self.transitionImageView.transform = CGAffineTransformMakeScale(1, 1)
self.transitionImageView.layer.cornerRadius = 0
self.transitionImageView.center = CUHelper.centerPointOf(self.imageViewerScrollView)
}
}
) { _ in
// 確認とクリーンアップ
if self.transitionImageView.center == CUHelper.centerPointOf(self.imageViewerScrollView) {
self.executeCleanupForImageViewerDisplaySequence(); return
}
CUHelper.animate(
POConstants.ImageViewerDisplayAnimationDuration,
animations: { self.transitionImageView.center = CUHelper.centerPointOf(self.imageViewerScrollView) }
) { _ in self.executeCleanupForImageViewerDisplaySequence() }
}
}
// MARK: - Gesture Related Functions
/**
パンジェスチャがあるときの処理。
- parameter sender: パンジェスチャ
*/
func panGesture(sender: UIPanGestureRecognizer) {
if executingImageViewerTransitionAnimation { return }
let currentCoordinate = sender.locationInView(imageViewerScrollView)
if sender.state == .Began {
updateViewForPanGestureStart(currentCoordinate); return
}
if sender.state == .Ended {
updateViewForPanGestureEnd(sender, currentCoordinate: currentCoordinate); return
}
if executingSwipeToHideAnimation { self.updateViewForPanGestureChange(currentCoordinate) }
}
/**
シングルタップジェスチャがあるときの処理。
- parameter sender: シングルタップジェスチャ
*/
func singleTapGesture(sender: UITapGestureRecognizer) {
if executingImageViewerTransitionAnimation { return }
if imageViewerScrollView.zoomScale == POConstants.ImageViewerScrollViewMinimumZoomLevel {
if buttonsDisplaying {
hideButtons()
} else {
displayButtons()
}
} else {
if !imageView.bounds.contains(sender.locationInView(imageView)) {
CUHelper.animate(
POConstants.ImageViewerDoubleTapZoomAnimationDuration,
animations: {
self.imageViewerScrollView.zoomScale = POConstants.ImageViewerScrollViewMinimumZoomLevel
self.imageView.center = self.centerPointNeededToCenterImageViewInImageViewerScrollView()
}
)
}
}
}
/**
ダブルタップジェスチャがあるときの処理。
- parameter sender: ダブルタップジェスチャ
*/
func doubleTapGesture(sender: UITapGestureRecognizer) {
if executingImageViewerTransitionAnimation { return }
if imageView.bounds.contains(sender.locationInView(imageView)) {
if imageViewerScrollView.zoomScale == 1 {
updateViewForDoubleTapGestureZoomIn(sender)
} else {
updateViewForDoubleTapGestureZoomOut()
}
}
}
// MARK: - Private Functions
/**
セットアップ。
*/
private func setup() {
imageViewerScrollView.delegate = self
imageViewerScrollView.bouncesZoom = false
imageView.contentMode = .ScaleAspectFit
imageView.clipsToBounds = true
transitionImageView.contentMode = .ScaleAspectFit
transitionImageView.clipsToBounds = true
setupOverlayButton()
setupBackButton()
setupShareButton()
setupGestureRecognizers()
}
/**
戻るボタンのセットアップ。
*/
private func setupBackButton() {
// コンテナビュー
backButtonContainerView.bounds.size = POConstants.ImageViewerButtonSize
backButtonContainerView.center = CGPointMake(
backButtonContainerView.bounds.width * (4 / 5),
POConstants.MainScreenSize.height - backButtonContainerView.bounds.height * (5 / 4)
)
backButtonContainerView.backgroundColor = POColors.ImageViewerBackButtonBackgroundColor
backButtonContainerView.layer.cornerRadius = POConstants.ImageViewerButtonSize.width / 2
backButtonContainerView.clipsToBounds = true
// 戻る矢印アイコン
if let icon = UIImage(named: "back") {
backButtonImageView.image = icon.imageWithRenderingMode(.AlwaysTemplate)
backButtonImageView.tintColor = UIColor.whiteColor()
}
backButtonImageView.bounds.size = POConstants.ImageViewerBackButtonImageViewSize
backButtonImageView.center = CUHelper.centerPointOf(backButtonContainerView)
backButtonContainerView.addSubview(backButtonImageView)
// オーバーレイボタン
backButtonOverlayButton.bounds.size = POConstants.ImageViewerButtonSize
backButtonOverlayButton.center = backButtonContainerView.center
backButtonOverlayButton.layer.cornerRadius = POConstants.ImageViewerButtonSize.width / 2
backButtonOverlayButton.clipsToBounds = true
backButtonOverlayButton.buttonAction = { self.hideImageViewer() }
}
/**
シェアボタンのセットアップ。
*/
private func setupShareButton() {
// イメージビュー
shareButtonImageView.image = UIImage(named: "share")
shareButtonImageView.bounds.size = POConstants.ImageViewerButtonSize
shareButtonImageView.center = CGPointMake(
POConstants.MainScreenSize.width - backButtonContainerView.center.x,
backButtonContainerView.center.y
)
shareButtonImageView.alpha = POConstants.ImageViewerShareButtonAlpha
// オーバーレイボタン
shareButtonOverlayButton.bounds.size = CGSizeMake(
POConstants.ImageViewerButtonSize.width - POConstants.ImageViewerShareButtonOverlayButtonSizeAdjustment,
POConstants.ImageViewerButtonSize.height - POConstants.ImageViewerShareButtonOverlayButtonSizeAdjustment
)
shareButtonOverlayButton.center = shareButtonImageView.center
shareButtonOverlayButton.layer.cornerRadius = POConstants.ImageViewerButtonSize.width / 2
shareButtonOverlayButton.buttonAction = {
if let topViewController = POUtilities.getTopViewController() {
var activityItems: [AnyObject] = [POStrings.ShareMessage]
if let image = self.image {
activityItems.append(image)
}
let activityVC = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
activityVC.completionWithItemsHandler = {(activityType, completed:Bool, returnedItems:[AnyObject]?, error: NSError?) in
if completed {
if let activityType = activityType {
if activityType == UIActivityTypeSaveToCameraRoll {
// フォトがカメラロールに保存した情報を伝えるビュー
let photoSavedToCameraRollToastView = POImageViewerPhotoSavedToCameraRollToastView()
photoSavedToCameraRollToastView.center = CUHelper.centerPointOf(self.topView)
self.topView.addSubview(photoSavedToCameraRollToastView)
photoSavedToCameraRollToastView.display()
}
}
}
}
topViewController.presentViewController(activityVC, animated: true, completion: nil)
}
}
}
/**
オーバーレイボタンのセットアップ。
*/
private func setupOverlayButton() {
overlayButton.layer.anchorPoint = CGPointZero
overlayButton.buttonAction = {
if self.imageViewerModeEnabled { self.displayImageViewer() }
if let action = self.overlayButtonAction { action() }
}
overlayButton.buttonPressBeganEventCallback = {
if let callback = self.overlayButtonPressBeganEventCallback { callback() }
}
overlayButton.buttonPressEndedEventCallback = {
if let callback = self.overlayButtonPressEndedEventCallback { callback() }
}
}
/**
ジェスチャ認識のセットアップ。
*/
private func setupGestureRecognizers() {
// パンジェスチャ
pan = UIPanGestureRecognizer(target: self, action: #selector(POImageViewerLinkedImageView.panGesture(_:)))
pan.maximumNumberOfTouches = 1
pan.delegate = self
imageViewerScrollView.addGestureRecognizer(pan)
// シングルタップジェスチャ
singleTap = UITapGestureRecognizer(target: self, action: #selector(POImageViewerLinkedImageView.singleTapGesture(_:)))
singleTap.numberOfTapsRequired = 1
singleTap.numberOfTouchesRequired = 1
singleTap.delegate = self
imageViewerScrollView.addGestureRecognizer(singleTap)
// ダブルタップジェスチャ
doubleTap = UITapGestureRecognizer(target: self, action: #selector(POImageViewerLinkedImageView.doubleTapGesture(_:)))
doubleTap.numberOfTapsRequired = 2
doubleTap.numberOfTouchesRequired = 1
doubleTap.delegate = self
imageViewerScrollView.addGestureRecognizer(doubleTap)
}
/**
イメージビューアを隠す。
*/
private func hideImageViewer() {
guard let parentView = parentView else { return }
executingImageViewerTransitionAnimation = true
imageViewerIsDisplaying = false
hideButtons()
// アニメーションするためのイメージビュー
let newAspectRatio = self.bounds.width / self.bounds.height,
imageViewAspectRatio = imageView.bounds.width / imageView.bounds.height,
newSize = (imageViewAspectRatio <= 1)
? CGSizeMake(imageView.bounds.height * newAspectRatio, imageView.bounds.height)
: CGSizeMake(imageView.bounds.width, imageView.bounds.width / newAspectRatio)
transitionImageView.bounds.size = newSize
transitionImageView.image = imageView.image
transitionImageView.center = imageView.center
topView.addSubview(transitionImageView)
// アニメーション前の準備
imageView.hidden = true
// 隠すアニメーション
let newOrigin = parentView.convertPoint(self.frame.origin, toView: topView),
newBounds = parentView.convertRect(self.bounds, toView: topView),
newCenter = CGPointMake(newOrigin.x + (newBounds.width / 2), newOrigin.y + (newBounds.height / 2)),
newScale = newBounds.width / transitionImageView.bounds.width
CUHelper.animateKeyframes(
POConstants.ImageViewerHideAnimationDuration,
animations: {
UIView.addKeyframeWithRelativeStartTime(0.94, relativeDuration: 0.06) {
self.transitionImageView.alpha = 0.5
}
UIView.addKeyframeWithRelativeStartTime(0.92, relativeDuration: 0.08) {
self.alpha = 1.0
}
UIView.addKeyframeWithRelativeStartTime(0.0, relativeDuration: 1.0) {
self.imageViewerScrollView.backgroundColor = UIColor.fromHexa(0xFFFFFF, alpha: 0)
self.transitionImageView.transform = CGAffineTransformMakeScale(newScale, newScale)
self.transitionImageView.layer.cornerRadius = POConstants.HomeTableViewCellPhotoCornerRadius
self.transitionImageView.center = newCenter
}
}
) { _ in
CUHelper.animate(
POConstants.ImageViewerHideAnimationDuration / 20,
animations: { self.transitionImageView.alpha = 0.0 }
) { _ in
// 確認とクリーンアップ
if self.transitionImageView.center == newCenter {
self.executeCleanupForImageViewerHideSequence(); return
}
CUHelper.animate(
POConstants.ImageViewerHideAnimationDuration,
animations: { self.transitionImageView.center = newCenter }
) { _ in self.executeCleanupForImageViewerHideSequence() }
}
}
}
/**
パンジェスチャが開始したためビューの更新。
- parameter currentCoordinate: 現在のジェスチャ座標
*/
private func updateViewForPanGestureStart(currentCoordinate: CGPoint) {
panGestureStartCoordinate = currentCoordinate
executingSwipeToHideAnimation = imageViewerScrollView.zoomScale == 1
if executingSwipeToHideAnimation {
hideButtons()
imageViewerScrollView.maximumZoomScale = imageViewerScrollView.minimumZoomScale
} else {
imageViewerScrollView.maximumZoomScale = POConstants.ImageViewerScrollViewMaximumZoomLevel
}
}
/**
パンジェスチャが終了したためビューの更新。
- parameter sender: パンジェスチャ
- parameter currentCoordinate: 現在のジェスチャ座標
*/
private func updateViewForPanGestureEnd(sender: UIPanGestureRecognizer, currentCoordinate: CGPoint) {
if imageViewerScrollView.zoomScale > 1 { return }
let horizontalSquaredTerm = pow(Double(panGestureStartCoordinate.x - currentCoordinate.x), Double(2)),
verticalSquaredTerm = pow(Double(panGestureStartCoordinate.y - currentCoordinate.y), Double(2)),
distanceMoved = CGFloat(pow(Double(horizontalSquaredTerm + verticalSquaredTerm), Double(0.5))),
velocity = sender.velocityInView(imageViewerScrollView),
minimumVelocityAttained = abs(velocity.x) > POConstants.ImageViewerMinimumVelocitySwipeRequiredToHide
|| abs(velocity.y) > POConstants.ImageViewerMinimumVelocitySwipeRequiredToHide
if minimumVelocityAttained && (distanceMoved > POConstants.ImageViewerMinimumDistanceSwipeRequiredToHide) {
hideImageViewer()
} else if distanceMoved > POConstants.ImageViewerMinimumDistanceRequiredToHide {
hideImageViewer()
} else { // イメージビューアを隠すアニメーションがキャンセルされた場合
CUHelper.animate(
POConstants.ImageViewerHideAnimationCancelledAnimationDuration,
options: .CurveEaseOut,
animations: { self.imageViewerScrollView.backgroundColor = UIColor.fromHexa(0xFFFFFF, alpha: POConstants.ImageViewerScrollViewBackgroundMaxAlpha) }
)
CUHelper.animateWithSpringBehavior(
POConstants.ImageViewerHideAnimationCancelledAnimationDuration,
usingSpringWithDamping: 0.3,
initialSpringVelocity: 0.2,
animations: {
self.imageView.center = CUHelper.centerPointOf(self.imageViewerScrollView)
self.imageView.layer.cornerRadius = 0
}
) { _ in
self.imageViewerScrollView.maximumZoomScale = POConstants.ImageViewerScrollViewMaximumZoomLevel
self.displayButtons()
}
}
executingSwipeToHideAnimation = false
}
/**
パンジェスチャが変更したためビューの更新。
- parameter currentCoordinate: 現在のジェスチャ座標
*/
private func updateViewForPanGestureChange(currentCoordinate: CGPoint) {
let pulledHorizontalDistance = panGestureStartCoordinate.x - currentCoordinate.x,
pulledVerticalDistance = panGestureStartCoordinate.y - currentCoordinate.y,
horizontalSquaredTerm = pow(Double(pulledHorizontalDistance), Double(2)),
verticalSquaredTerm = pow(Double(pulledVerticalDistance), Double(2)),
distanceMoved = CGFloat(pow(Double(horizontalSquaredTerm + verticalSquaredTerm), Double(0.5))),
scrollViewAlpha = max(1 - (distanceMoved / POConstants.ImageViewerMinimumDistanceRequiredToHide), 0) * POConstants.ImageViewerScrollViewBackgroundMaxAlpha,
imageViewCornerRadius = max((distanceMoved / POConstants.ImageViewerMinimumDistanceRequiredToHide), 0) * POConstants.HomeTableViewCellPhotoCornerRadius
imageViewerScrollView.backgroundColor = UIColor.fromHexa(0xFFFFFF, alpha: scrollViewAlpha)
imageView.layer.cornerRadius = imageViewCornerRadius
imageView.center = CGPointMake(
imageViewerScrollView.bounds.width / 2 - pulledHorizontalDistance,
imageViewerScrollView.bounds.height / 2 - pulledVerticalDistance
)
}
/**
ダブルタップジェスチャズームインアニメーション。
- parameter sender: ダブルタップジェスチャ
*/
private func updateViewForDoubleTapGestureZoomIn(sender: UITapGestureRecognizer) {
let currentCoordinate = sender.locationInView(imageView),
thirdOfViewWidth = imageView.bounds.width / 3,
thirdOfViewHeight = imageView.bounds.height / 3,
imageViewWidthAtMaximumZoomLevel = imageView.bounds.width * POConstants.ImageViewerScrollViewMaximumZoomLevel,
imageViewHeightAtMaximumZoomLevel = imageView.bounds.height * POConstants.ImageViewerScrollViewMaximumZoomLevel,
middleSegmentContentOffsetX = max((imageViewWidthAtMaximumZoomLevel - imageViewerScrollView.bounds.width) / 2, 0),
rightSegmentContentOffsetX = max(imageViewWidthAtMaximumZoomLevel - imageViewerScrollView.bounds.width, 0),
middleSegmentContentOffsetY = max((imageViewHeightAtMaximumZoomLevel - imageViewerScrollView.bounds.height) / 2, 0),
bottomSegmentContentOffsetY = max(imageViewHeightAtMaximumZoomLevel - imageViewerScrollView.bounds.height, 0)
var newContentOffset = CGPointZero
if currentCoordinate.x <= thirdOfViewWidth && currentCoordinate.y <= thirdOfViewHeight
{ // top-left segment
newContentOffset = CGPointZero
} else if currentCoordinate.x > thirdOfViewWidth
&& currentCoordinate.x <= 2*thirdOfViewWidth
&& currentCoordinate.y <= thirdOfViewHeight
{ // top-middle segment
newContentOffset = CGPointMake(middleSegmentContentOffsetX, 0)
} else if currentCoordinate.x > 2 * thirdOfViewWidth
&& currentCoordinate.y <= thirdOfViewHeight
{ // top-right segment
newContentOffset = CGPointMake(rightSegmentContentOffsetX, 0)
} else if currentCoordinate.x <= thirdOfViewWidth
&& currentCoordinate.y > thirdOfViewHeight
&& currentCoordinate.y <= 2*thirdOfViewHeight
{ // middle-left segment
newContentOffset = CGPointMake(0, middleSegmentContentOffsetY)
} else if currentCoordinate.x > thirdOfViewWidth
&& currentCoordinate.x <= 2*thirdOfViewWidth
&& currentCoordinate.y > thirdOfViewHeight
&& currentCoordinate.y <= 2*thirdOfViewHeight
{ // middle-middle segment
newContentOffset = CGPointMake(middleSegmentContentOffsetX, middleSegmentContentOffsetY)
} else if currentCoordinate.x > 2*thirdOfViewWidth
&& currentCoordinate.y > thirdOfViewHeight
&& currentCoordinate.y < 2*thirdOfViewHeight
{ // middle-right segment
newContentOffset = CGPointMake(rightSegmentContentOffsetX, middleSegmentContentOffsetY)
} else if currentCoordinate.x <= thirdOfViewWidth
&& currentCoordinate.y > 2*thirdOfViewHeight
{ // bottom-left segment
newContentOffset = CGPointMake(0, bottomSegmentContentOffsetY)
} else if currentCoordinate.x > thirdOfViewWidth
&& currentCoordinate.x <= 2*thirdOfViewWidth
&& currentCoordinate.y > 2*thirdOfViewHeight
{ // bottom-middle segment
newContentOffset = CGPointMake(middleSegmentContentOffsetX, bottomSegmentContentOffsetY)
} else if currentCoordinate.x > 2*thirdOfViewWidth
&& currentCoordinate.y > 2*thirdOfViewHeight
{ // bottom-right segment
newContentOffset = CGPointMake(rightSegmentContentOffsetX, bottomSegmentContentOffsetY)
}
CUHelper.animate(
POConstants.ImageViewerDoubleTapZoomAnimationDuration,
options: .CurveEaseOut,
animations: {
self.imageViewerScrollView.zoomScale = POConstants.ImageViewerScrollViewMaximumZoomLevel
self.imageViewerScrollView.contentOffset = newContentOffset
}
) { _ in
if self.buttonsDisplaying {
self.hideButtons()
}
if !self.shareButtonImageView.hidden {
}
}
}
/**
ダブルタップジェスチャズームアウトアニメーション。
*/
private func updateViewForDoubleTapGestureZoomOut() {
let currentContentOffset = imageViewerScrollView.contentOffset
if imageViewerScrollView.contentOffset == CGPointZero {
imageViewerScrollView.contentOffset = CGPointMake(1, 1) // contentOffsetが(0,0)の場合にちゃんとセンターしないバグの
}
if currentContentOffset.x >= 0 && currentContentOffset.y >= 0 {
executeDoubleTapZoomOutAnimation()
} else {
let newContentOffset = CGPointMake(max(currentContentOffset.x, 1), max(currentContentOffset.y, 1))
UIView.animateWithDuration(0.1) { self.imageViewerScrollView.contentOffset = newContentOffset }
CUHelper.executeOnMainThreadAfter(0.1) { self.executeDoubleTapZoomOutAnimation() }
}
}
/**
ダブルタップのズームアウトアニメーション。
*/
private func executeDoubleTapZoomOutAnimation() {
let newCenter = centerPointNeededToCenterImageViewInImageViewerScrollView()
CUHelper.animate(
POConstants.ImageViewerDoubleTapZoomAnimationDuration,
options: .CurveEaseOut,
animations: {
self.imageView.center = newCenter
self.imageViewerScrollView.zoomScale = POConstants.ImageViewerScrollViewMinimumZoomLevel + 0.001
}
) { _ in
CUHelper.executeOnMainThreadAfter(0.1) {
self.imageViewerScrollView.zoomScale = POConstants.ImageViewerScrollViewMinimumZoomLevel
}
}
}
// MARK: - Helper Functions
/**
ビューのボタンを表示。
*/
private func displayButtons() {
buttonsDisplaying = true
backButtonContainerView.hidden = false
backButtonOverlayButton.hidden = false
shareButtonImageView.hidden = false
shareButtonOverlayButton.hidden = false
authorNameView.display()
CUHelper.animate(
POConstants.ImageViewerButtonAnimationDuration,
options: .CurveEaseOut,
animations: {
self.backButtonContainerView.transform = POConstants.ImageViewerButtonDefaultScaleTransform
self.shareButtonImageView.transform = POConstants.ImageViewerButtonDefaultScaleTransform
}
)
}
/**
ビューのボタンを隠す。
*/
private func hideButtons() {
buttonsDisplaying = false
backButtonOverlayButton.hidden = true
shareButtonOverlayButton.hidden = true
authorNameView.hide()
CUHelper.animate(
POConstants.ImageViewerButtonAnimationDuration,
options: .CurveEaseOut,
animations: {
self.backButtonContainerView.transform = POConstants.ImageViewerButtonHiddenScaleTransform
self.shareButtonImageView.transform = POConstants.ImageViewerButtonHiddenScaleTransform
}
) { _ in
self.backButtonContainerView.hidden = true
self.shareButtonImageView.hidden = true
}
}
/**
イメージビューアディスプレイする時のセンタリングアニメーションを実行。
- parameter completion: コールバック
*/
private func executeCenteringAnimationForImageViewerDisplaySequence(completion: (() -> Void)? = nil) {
CUHelper.animate(
POConstants.ImageViewerDisplayAnimationDuration,
animations: {
self.transitionImageView.center = CUHelper.centerPointOf(self.imageViewerScrollView)
}
) { _ in if let complete = completion { complete() } }
}
/**
イメージビューアディスプレイする時のクリーンアップを実行。
*/
private func executeCleanupForImageViewerDisplaySequence() {
displayHintsIfNecessary()
CUHelper.executeOnMainThreadAfter(POConstants.ImageViewerDisplaySequenceBackButtonAnimationDelay) {
if self.imageViewerIsDisplaying
&& self.imageViewerScrollView.zoomScale == POConstants.ImageViewerScrollViewMinimumZoomLevel
&& !self.executingSwipeToHideAnimation
{
self.displayButtons()
}
}
imageView.hidden = false
transitionImageView.removeFromSuperview()
executingImageViewerTransitionAnimation = false
}
/**
イメージビュー隠す時のクリーンアップを実行。
*/
private func executeCleanupForImageViewerHideSequence() {
imageViewerScrollView.removeFromSuperview()
transitionImageView.removeFromSuperview()
backButtonContainerView.removeFromSuperview()
backButtonOverlayButton.removeFromSuperview()
authorNameView.removeFromSuperview()
imageViewerScrollView.center = CUHelper.centerPointOf(self.imageViewerScrollView)
self.hidden = false
UIApplication.sharedApplication().setStatusBarHidden(false, withAnimation: .Slide)
executingImageViewerTransitionAnimation = false
}
/**
イメージビューを親スクロールビューにセンターするため必要なイメージビューのセンターポイントをゲット。
- returns: イメージビューを親スクロールビューにセンターするため必要なイメージビューのセンターポイント
*/
private func centerPointNeededToCenterImageViewInImageViewerScrollView() -> CGPoint {
let offsetX = max((imageViewerScrollView.bounds.size.width - imageViewerScrollView.contentSize.width) / 2, 0),
offsetY = max((imageViewerScrollView.bounds.size.height - imageViewerScrollView.contentSize.height) / 2, 0)
return CGPointMake(
offsetX + (imageViewerScrollView.contentSize.width / 2),
offsetY + (imageViewerScrollView.contentSize.height / 2)
)
}
/**
最初イメージビューアーを表示する時にヒントを表示する。
*/
private func displayHintsIfNecessary() {
if !NSUserDefaults.standardUserDefaults().boolForKey(POStrings.ImageViewerZoomHintShownUserDefaultsKey) {
let zoomHintToastView = POImageViewerZoomHintToastView()
zoomHintToastView.center = CUHelper.centerPointOf(topView)
topView.addSubview(zoomHintToastView)
zoomHintToastView.displayHint()
NSUserDefaults.standardUserDefaults().setBool(true, forKey: POStrings.ImageViewerZoomHintShownUserDefaultsKey)
} else if !NSUserDefaults.standardUserDefaults().boolForKey(POStrings.ImageViewerSwipeGestureHintShownUserDefaultsKey) {
let swipeToHideHintToastView = POImageViewerSwipeToHideHintToastView()
swipeToHideHintToastView.center = CUHelper.centerPointOf(topView)
topView.addSubview(swipeToHideHintToastView)
swipeToHideHintToastView.displayHint()
NSUserDefaults.standardUserDefaults().setBool(true, forKey: POStrings.ImageViewerSwipeGestureHintShownUserDefaultsKey)
}
}
}
extension POImageViewerLinkedImageView: UIGestureRecognizerDelegate {
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRequireFailureOfGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
if ((gestureRecognizer == singleTap && otherGestureRecognizer == doubleTap) ||
(gestureRecognizer == singleTap && otherGestureRecognizer == pan)) &&
(self.imageView.bounds.contains(gestureRecognizer.locationInView(imageView)) ||
self.imageView.bounds.contains(otherGestureRecognizer.locationInView(imageView))
)
{
return true
}
return false
}
}
extension POImageViewerLinkedImageView: UIScrollViewDelegate {
func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
return imageView
}
func scrollViewDidScroll(scrollView: UIScrollView) {
imageView.center = centerPointNeededToCenterImageViewInImageViewerScrollView()
}
func scrollViewDidZoom(scrollView: UIScrollView) {
if scrollView.zoomScale == POConstants.ImageViewerScrollViewMinimumZoomLevel {
displayButtons()
} else {
hideButtons()
}
}
func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
if scrollView.zoomScale == POConstants.ImageViewerScrollViewMinimumZoomLevel {
if !buttonsDisplaying {
displayButtons()
}
if imageView.center != imageCenterAtMinimumZoom {
UIView.animateWithDuration(POConstants.ImageViewerCenteringMisalignedImageAnimationDuration) {
self.imageView.center = self.imageCenterAtMinimumZoom
}
}
}
}
}
|
119673d6b91e618e9155e6d32f0799a3
| 42.137813 | 172 | 0.660172 | false | false | false | false |
VernonVan/SmartClass
|
refs/heads/master
|
SmartClass/Quiz/View/QuizListViewController.swift
|
mit
|
1
|
//
// QuizListViewController.swift
// SmartClass
//
// Created by Vernon on 16/9/14.
// Copyright © 2016年 Vernon. All rights reserved.
//
import UIKit
import RealmSwift
import DZNEmptyDataSet
class QuizListViewController: UIViewController
{
@IBOutlet weak var tableView: UITableView!
var fromDate: Date!
var toDate: Date!
var quizs: Results<Quiz>!
override func viewDidLoad()
{
super.viewDidLoad()
let realm = try! Realm()
quizs = realm.objects(Quiz.self).filter("date BETWEEN {%@, %@}", fromDate, toDate)
// try! realm.write {
// let quiz1 = Quiz(value: ["content": "第一题怎么做", "name": "卢建晖", "date": NSDate()])
// realm.add(quiz1)
// let quiz2 = Quiz(value: ["content": "为什么1+1=2", "name": "刘德华", "date": NSDate()])
// realm.add(quiz2)
// let quiz3 = Quiz(value: ["content": "为什么1+1=2", "name": "卢建晖", "date": NSDate(timeIntervalSince1970: 10000000)])
// realm.add(quiz3)
// }
tableView.dataSource = self
tableView.delegate = self
tableView.separatorStyle = .none
tableView.backgroundColor = UIColor(netHex: 0xeeeeee)
tableView.emptyDataSetSource = self
navigationItem.backBarButtonItem = UIBarButtonItem(title:"", style:.plain, target:nil, action:nil)
}
}
extension QuizListViewController: UITableViewDataSource, UITableViewDelegate
{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return quizs.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "QuizCell", for: indexPath) as! QuizCell
cell.configureWithQuiz(quizs[(indexPath as NSIndexPath).row])
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
return QuizCell.cellHeight
}
}
extension QuizListViewController: DZNEmptyDataSetSource
{
func image(forEmptyDataSet scrollView: UIScrollView!) -> UIImage!
{
return UIImage(named: "emptyQuiz")
}
func title(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString!
{
let text = NSLocalizedString("本节课暂无学生提问", comment: "")
let attributes = [NSFontAttributeName: UIFont.boldSystemFont(ofSize: 16.0),
NSForegroundColorAttributeName: UIColor.darkGray]
return NSAttributedString(string: text, attributes: attributes)
}
}
|
8d2f1b0d1bac727cbbdbc7a432edfecd
| 29.988235 | 126 | 0.642369 | false | false | false | false |
FolioReader/FolioReaderKit
|
refs/heads/master
|
Example/FolioReaderTests/FolioReaderTests.swift
|
bsd-3-clause
|
2
|
//
// FolioReaderTests.swift
// FolioReaderTests
//
// Created by Brandon Kobilansky on 1/25/16.
// Copyright © 2016 FolioReader. All rights reserved.
//
@testable import FolioReaderKit
import Quick
import Nimble
class FolioReaderTests: QuickSpec {
override func spec() {
context("epub parsing") {
var subject: FREpubParser!
var epubPath: String!
beforeEach {
guard let path = Bundle.main.path(forResource: "The Silver Chair", ofType: "epub") else {
fail("Could not read the epub file")
return
}
subject = FREpubParser()
epubPath = path
do {
let book = try subject.readEpub(epubPath: epubPath)
print(book.tableOfContents.first!.title)
} catch {
fail("Error: \(error.localizedDescription)")
}
}
it("flat table of contents") {
expect(subject.flatTOC.count).to(equal(17))
}
it("parses table of contents") {
expect(subject.book.tableOfContents.count).to(equal(17))
}
it("parses cover image") {
guard let coverImage = subject.book.coverImage, let fromFileImage = UIImage(contentsOfFile: coverImage.fullHref) else {
fail("Could not read the cover image")
return
}
do {
let parsedImage = try subject.parseCoverImage(epubPath)
let data1 = parsedImage.pngData()
let data2 = fromFileImage.pngData()
expect(data1).to(equal(data2))
} catch {
fail("Error: \(error.localizedDescription)")
}
}
it("parses book title") {
do {
let title = try subject.parseTitle(epubPath)
expect(title).to(equal("The Silver Chair"))
} catch {
fail("Error: \(error.localizedDescription)")
}
}
it("parses author name") {
do {
let name = try subject.parseAuthorName(epubPath)
expect(name).to(equal("C. S. Lewis"))
} catch {
fail("Error: \(error.localizedDescription)")
}
}
}
}
}
|
c112b5c82c31ee62ad92fa0419c45db3
| 30.625 | 135 | 0.477866 | false | false | false | false |
MaartenBrijker/project
|
refs/heads/back
|
AudioKit/iOS/AudioKit/AudioKit.playground/Pages/AutoPan Operation.xcplaygroundpage/Contents.swift
|
apache-2.0
|
2
|
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
//:
//: ---
//:
//: ## AutoPan Operation
//:
import XCPlayground
import AudioKit
//: This first section sets up parameter naming in such a way to make the operation code easier to read below.
enum AutoPanParameter: Int {
case Speed, Depth
}
struct AutoPan {
static var speed: AKOperation {
return AKOperation.parameters(AutoPanParameter.Speed.rawValue)
}
static var depth: AKOperation {
return AKOperation.parameters(AutoPanParameter.Depth.rawValue)
}
}
extension AKOperationEffect {
var speed: Double {
get { return self.parameters[AutoPanParameter.Speed.rawValue] }
set(newValue) { self.parameters[AutoPanParameter.Speed.rawValue] = newValue }
}
var depth: Double {
get { return self.parameters[AutoPanParameter.Depth.rawValue] }
set(newValue) { self.parameters[AutoPanParameter.Depth.rawValue] = newValue }
}
}
//: Here we'll use the struct and the extension to refer to the autopan parameters by name
let bundle = NSBundle.mainBundle()
let file = bundle.pathForResource("guitarloop", ofType: "wav")
var player = AKAudioPlayer(file!)
player.looping = true
let oscillator = AKOperation.sineWave(frequency: AutoPan.speed, amplitude: AutoPan.depth)
let panner = AKOperation.input.pan(oscillator)
let effect = AKOperationEffect(player, stereoOperation: panner)
effect.parameters = [10, 1]
AudioKit.output = effect
AudioKit.start()
let playgroundWidth = 500
class PlaygroundView: AKPlaygroundView {
var speedLabel: Label?
var depthLabel: Label?
override func setup() {
addTitle("AutoPan")
addLabel("Audio Playback")
addButton("Start", action: #selector(start))
addButton("Stop", action: #selector(stop))
speedLabel = addLabel("Speed: \(effect.speed)")
addSlider(#selector(setSpeed), value: effect.speed, minimum: 0.1, maximum: 25)
depthLabel = addLabel("Depth: \(effect.depth)")
addSlider(#selector(setDepth), value: effect.depth)
}
func start() {
player.play()
}
func stop() {
player.stop()
}
func setSpeed(slider: Slider) {
effect.speed = Double(slider.value)
speedLabel!.text = "Speed: \(String(format: "%0.3f", effect.speed))"
}
func setDepth(slider: Slider) {
effect.depth = Double(slider.value)
depthLabel!.text = "Depth: \(String(format: "%0.3f", effect.depth))"
}
}
let view = PlaygroundView(frame: CGRect(x: 0, y: 0, width: playgroundWidth, height: 650))
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
XCPlaygroundPage.currentPage.liveView = view
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
|
c4d260f143c2a258e7c6c828f98c9f68
| 28.819149 | 110 | 0.674634 | false | false | false | false |
silt-lang/silt
|
refs/heads/master
|
Sources/OuterCore/ParseGIR.swift
|
mit
|
1
|
/// ParseGIR.swift
///
/// Copyright 2017-2018, The Silt Language Project.
///
/// This project is released under the MIT license, a copy of which is
/// available in the repository.
import Lithosphere
import Crust
import Seismography
import Moho
import Mantle
public final class GIRParser {
struct ParserScope {
let name: String
}
let parser: Parser
var module: GIRModule
private var _activeScope: ParserScope?
fileprivate var continuationsByName: [Name: Continuation] = [:]
fileprivate var undefinedContinuation: [Continuation: TokenSyntax] = [:]
fileprivate var localValues: [String: Value] = [:]
fileprivate var forwardRefLocalValues: [String: TokenSyntax] = [:]
private let tc: TypeChecker<CheckPhaseState>
var currentScope: ParserScope {
guard let scope = self._activeScope else {
fatalError("Attempted to request current scope without pushing a scope.")
}
return scope
}
public init(_ parser: Parser) {
self.parser = parser
self.tc = TypeChecker<CheckPhaseState>(CheckPhaseState(), parser.engine)
self.module = GIRModule(parent: nil, tc: TypeConverter(self.tc))
}
@discardableResult
func withScope<T>(named name: String,
_ actions: () throws -> T) rethrows -> T {
let prevScope = self._activeScope
let prevLocals = localValues
let prevForwardRefLocals = forwardRefLocalValues
self._activeScope = ParserScope(name: name)
defer {
self._activeScope = prevScope
self.localValues = prevLocals
self.forwardRefLocalValues = prevForwardRefLocals
}
return try actions()
}
func namedContinuation(_ B: GIRBuilder, _ name: Name) -> Continuation {
// If there was no name specified for this block, just create a new one.
if name.description.isEmpty {
return B.buildContinuation(name: QualifiedName(name: name))
}
// If the block has never been named yet, just create it.
guard let cont = self.continuationsByName[name] else {
let cont = B.buildContinuation(name: QualifiedName(name: name))
self.continuationsByName[name] = cont
return cont
}
if undefinedContinuation.removeValue(forKey: cont) == nil {
// If we have a redefinition, return a new BB to avoid inserting
// instructions after the terminator.
fatalError("Redefinition of Basic Block")
}
return cont
}
func getReferencedContinuation(
_ B: GIRBuilder, _ syntax: TokenSyntax) -> Continuation {
assert(syntax.render.starts(with: "@"))
let noAtNode = syntax.withKind(
.identifier(String(syntax.render.dropFirst())))
let name = Name(name: noAtNode)
// If the block has already been created, use it.
guard let cont = self.continuationsByName[name] else {
// Otherwise, create it and remember that this is a forward reference so
// that we can diagnose use without definition problems.
let cont = B.buildContinuation(name: QualifiedName(name: name))
self.continuationsByName[name] = cont
self.undefinedContinuation[cont] = syntax
return cont
}
return cont
}
func getLocalValue(_ name: TokenSyntax) -> Value {
// Check to see if this is already defined.
guard let entry = self.localValues[name.render] else {
// Otherwise, this is a forward reference. Create a dummy node to
// represent it until we see a real definition.
self.forwardRefLocalValues[name.render] = name
let entry = NoOp()
self.localValues[name.render] = entry
return entry
}
return entry
}
func setLocalValue(_ value: Value, _ name: String) {
// If this value was already defined, it is either a redefinition, or a
// specification for a forward referenced value.
guard let entry = self.localValues[name] else {
// Otherwise, just store it in our map.
self.localValues[name] = value
return
}
guard self.forwardRefLocalValues.removeValue(forKey: name) != nil else {
fatalError("Redefinition of named value \(name) by \(value)")
}
// Forward references only live here if they have a single result.
entry.replaceAllUsesWith(value)
}
}
extension GIRParser {
public func parseTopLevelModule() -> GIRModule {
do {
_ = try self.parser.consume(.moduleKeyword)
let moduleId = try self.parser.parseQualifiedName().render
_ = try self.parser.consume(.whereKeyword)
let mod = GIRModule(name: moduleId,
parent: nil, tc: TypeConverter(self.tc))
self.module = mod
let builder = GIRBuilder(module: mod)
try self.parseDecls(builder)
assert(self.parser.currentToken?.tokenKind == .eof)
return mod
} catch _ {
return self.module
}
}
func parseDecls(_ B: GIRBuilder) throws {
while self.parser.peek() != .rightBrace && self.parser.peek() != .eof {
_ = try parseDecl(B)
}
}
func parseDecl(_ B: GIRBuilder) throws -> Bool {
guard
case let .identifier(identStr) = parser.peek(), identStr.starts(with: "@")
else {
throw self.parser.unexpectedToken()
}
let ident = try self.parser.parseIdentifierToken()
_ = try self.parser.consume(.colon)
_ = try self.parser.parseGIRTypeExpr()
_ = try self.parser.consume(.leftBrace)
return try self.withScope(named: ident.render) {
repeat {
guard try self.parseGIRBasicBlock(B) else {
return false
}
} while self.parser.peek() != .rightBrace && self.parser.peek() != .eof
_ = try self.parser.consume(.rightBrace)
return true
}
}
func parseGIRBasicBlock(_ B: GIRBuilder) throws -> Bool {
var ident = try self.parser.parseIdentifierToken()
if ident.render.hasSuffix(":") {
ident = ident.withKind(.identifier(String(ident.render.dropLast())))
}
let cont = self.namedContinuation(B, Name(name: ident))
// If there is a basic block argument list, process it.
if try self.parser.consumeIf(.leftParen) != nil {
repeat {
let name = try self.parser.parseIdentifierToken().render
_ = try self.parser.consume(.colon)
let typeRepr = try self.parser.parseGIRTypeExpr()
let arg = cont.appendParameter(type: GIRExprType(typeRepr))
self.setLocalValue(arg, name)
} while try self.parser.consumeIf(.semicolon) != nil
_ = try self.parser.consume(.rightParen)
_ = try self.parser.consume(.colon)
}
repeat {
guard try parseGIRInstruction(B, in: cont) else {
return true
}
} while isStartOfGIRPrimop()
return true
}
func isStartOfGIRPrimop() -> Bool {
guard case .identifier(_) = self.parser.peek() else {
return false
}
return true
}
// swiftlint:disable function_body_length
func parseGIRInstruction(
_ B: GIRBuilder, in cont: Continuation) throws -> Bool {
guard self.parser.peekToken()!.leadingTrivia.containsNewline else {
fatalError("Instruction must begin on a new line")
}
guard case .identifier(_) = self.parser.peek() else {
return false
}
let resultName = tryParseGIRValueName()
if resultName != nil {
_ = try self.parser.consume(.equals)
}
guard let opcode = parseGIRPrimOpcode() else {
return false
}
var resultValue: Value?
switch opcode {
case .dataExtract:
fatalError("unimplemented")
case .forceEffects:
fatalError("unimplemented")
case .tuple:
fatalError("unimplemented")
case .tupleElementAddress:
fatalError("unimplemented")
case .thicken:
fatalError("unimplemented")
case .noop:
fatalError("noop cannot be spelled")
case .alloca:
let typeRepr = try self.parser.parseGIRTypeExpr()
let type = GIRExprType(typeRepr)
resultValue = B.createAlloca(type)
case .allocBox:
let typeRepr = try self.parser.parseGIRTypeExpr()
let type = GIRExprType(typeRepr)
resultValue = B.createAllocBox(type)
case .apply:
guard let fnName = tryParseGIRValueToken() else {
return false
}
let fnVal = self.getLocalValue(fnName)
_ = try self.parser.consume(.leftParen)
var argNames = [TokenSyntax]()
if self.parser.peek() != .rightParen {
repeat {
guard let arg = self.tryParseGIRValueToken() else {
return false
}
argNames.append(arg)
} while try self.parser.consumeIf(.semicolon) != nil
}
_ = try self.parser.consume(.rightParen)
_ = try self.parser.consume(.colon)
_ = try self.parser.parseGIRTypeExpr()
var args = [Value]()
for argName in argNames {
let argVal = self.getLocalValue(argName)
args.append(argVal)
}
_ = B.createApply(cont, fnVal, args)
case .copyValue:
guard let valueName = tryParseGIRValueToken() else {
return false
}
_ = try self.parser.consumeIf(.colon)
_ = try self.parser.parseGIRTypeExpr()
resultValue = B.createCopyValue(self.getLocalValue(valueName))
case .copyAddress:
guard let valueName = tryParseGIRValueToken() else {
return false
}
_ = try self.parser.consume(.identifier("to"))
guard let addressName = tryParseGIRValueToken() else {
return false
}
_ = try self.parser.consumeIf(.colon)
_ = try self.parser.parseGIRTypeExpr()
resultValue = B.createCopyAddress(self.getLocalValue(valueName),
to: self.getLocalValue(addressName))
case .dealloca:
guard let valueName = tryParseGIRValueToken() else {
return false
}
_ = try self.parser.consumeIf(.colon)
_ = try self.parser.parseGIRTypeExpr()
cont.appendCleanupOp(B.createDealloca(self.getLocalValue(valueName)))
case .deallocBox:
guard let valueName = tryParseGIRValueToken() else {
return false
}
_ = try self.parser.consumeIf(.colon)
_ = try self.parser.parseGIRTypeExpr()
cont.appendCleanupOp(B.createDeallocBox(self.getLocalValue(valueName)))
case .destroyValue:
guard let valueName = tryParseGIRValueToken() else {
return false
}
_ = try self.parser.consumeIf(.colon)
_ = try self.parser.parseGIRTypeExpr()
cont.appendCleanupOp(B.createDestroyValue(self.getLocalValue(valueName)))
case .destroyAddress:
guard let valueName = tryParseGIRValueToken() else {
return false
}
_ = try self.parser.consumeIf(.colon)
_ = try self.parser.parseGIRTypeExpr()
cont.appendCleanupOp(
B.createDestroyAddress(self.getLocalValue(valueName)))
case .switchConstr:
guard let val = self.tryParseGIRValueToken() else {
return false
}
let srcVal = self.getLocalValue(val)
_ = try self.parser.consume(.colon)
_ = try self.parser.parseGIRTypeExpr()
var caseConts = [(String, FunctionRefOp)]()
while case .semicolon = self.parser.peek() {
_ = try self.parser.consume(.semicolon)
guard
case let .identifier(ident) = self.parser.peek(), ident == "case"
else {
return false
}
_ = try self.parser.parseIdentifierToken()
let caseName = try self.parser.parseQualifiedName()
_ = try self.parser.consume(.colon)
guard let arg = self.tryParseGIRValueToken() else {
return false
}
// swiftlint:disable force_cast
let fnVal = self.getLocalValue(arg) as! FunctionRefOp
caseConts.append((caseName.render, fnVal))
}
_ = B.createSwitchConstr(cont, srcVal, caseConts)
case .functionRef:
guard
case let .identifier(refName) = parser.peek(), refName.starts(with: "@")
else {
return false
}
let ident = try self.parser.parseIdentifierToken()
let resultFn = getReferencedContinuation(B, ident)
resultValue = B.createFunctionRef(resultFn)
case .dataInit:
let typeRepr = try self.parser.parseGIRTypeExpr()
_ = try self.parser.consume(.semicolon)
let ident = try self.parser.parseQualifiedName()
let type = GIRExprType(typeRepr)
var args = [Value]()
while case .semicolon = self.parser.peek() {
_ = try self.parser.consume(.semicolon)
guard let arg = self.tryParseGIRValueToken() else {
return false
}
let argVal = self.getLocalValue(arg)
_ = try self.parser.consume(.colon)
_ = try self.parser.parseGIRTypeExpr()
args.append(argVal)
}
resultValue = B.createDataInit(ident.render, type, nil)
case .projectBox:
guard let valueName = tryParseGIRValueToken() else {
return false
}
_ = try self.parser.consumeIf(.colon)
let typeRepr = try self.parser.parseGIRTypeExpr()
resultValue = B.createProjectBox(self.getLocalValue(valueName),
type: GIRExprType(typeRepr))
case .load:
guard let valueName = tryParseGIRValueToken() else {
return false
}
_ = try self.parser.consumeIf(.colon)
_ = try self.parser.parseGIRTypeExpr()
resultValue = B.createLoad(self.getLocalValue(valueName), .copy)
case .store:
guard let valueName = tryParseGIRValueToken() else {
return false
}
_ = try self.parser.consume(.identifier("to"))
guard let addressName = tryParseGIRValueToken() else {
return false
}
_ = try self.parser.consumeIf(.colon)
_ = try self.parser.parseGIRTypeExpr()
_ = B.createStore(self.getLocalValue(valueName),
to: self.getLocalValue(addressName))
case .unreachable:
resultValue = B.createUnreachable(cont)
}
guard let resName = resultName, let resValue = resultValue else {
return true
}
self.setLocalValue(resValue, resName)
return true
}
func tryParseGIRValueName() -> String? {
return tryParseGIRValueToken()?.render
}
func tryParseGIRValueToken() -> TokenSyntax? {
guard let result = self.parser.peekToken() else {
return nil
}
guard case let .identifier(ident) = result.tokenKind else {
return nil
}
guard ident.starts(with: "%") else {
return nil
}
self.parser.advance()
return result
}
func parseGIRPrimOpcode() -> PrimOp.Code? {
guard case let .identifier(ident) = self.parser.peek() else {
return nil
}
guard let opCode = PrimOp.Code(rawValue: ident) else {
return nil
}
_ = self.parser.advance()
return opCode
}
}
extension TokenSyntax {
var render: String {
return self.triviaFreeSourceText
}
}
extension QualifiedNameSyntax {
var render: String {
var result = ""
for component in self {
result += component.triviaFreeSourceText
}
return result
}
}
|
7937daf834154c272eec941b10510beb
| 30.307531 | 80 | 0.643502 | false | false | false | false |
scubers/JRDB
|
refs/heads/master
|
JRDB/AViewController.swift
|
mit
|
1
|
//
// AViewController.swift
// JRDB
//
// Created by JMacMini on 16/5/10.
// Copyright © 2016年 Jrwong. All rights reserved.
//
import UIKit
enum Sex : Int {
case man
case woman
}
class AAA: NSObject {
var type: String?
deinit {
print("\(self) deinit")
}
}
class PPP: AAA {
var sss : Sex = .man
var a_int: Int = 0
var a_int1: Int? = nil
var b_string: String = "1"
var b_string1: String! = "2"
var b_string2: String? = "3"
var c_nsstring: NSString = "4"
var c_nsstring1: NSString! = "5"
var c_nsstring2: NSString? = nil
var d_double: Double = 7
var e_float: Float = 8
var f_cgfloat: CGFloat = 9
var g_nsData: Data = Data()
var h_nsDate: Date = Date()
var ccc: CCC?
var ccc1: CCC?
var ppp: PPP?
// override static func jr_singleLinkedPropertyNames() -> [String : AnyObject.Type]? {
// return [
// "ccc" : CCC.self,
// "ccc1" : CCC.self,
// "ppp" : PPP.self,
// ]
// }
}
class CCC: NSObject {
var serialNumber: String = ""
weak var ppp: PPP?
// override static func jr_singleLinkedPropertyNames() -> [String : AnyObject.Type]? {
// return [
// "ppp" : PPP.self,
// ]
// }
deinit {
print("\(self) deinit")
}
}
class AViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// let db = JRDBMgr.shareInstance().createDB(withPath: "/Users/mac/Desktop/test.sqlite")
JRDBMgr.shareInstance().defaultDatabasePath = "/Users/mac/Desktop/test.sqlite";
let db = JRDBMgr.shareInstance().getHandler()
print(db);
// test1Cycle()
// testFindByID()
// testThreeNodeCycle()
// test2Node1Cycle()
// truncateTable()
}
func test2Node1Cycle() {
let p = PPP()
let p1 = PPP()
let c = CCC()
p.ppp = p1
p1.ccc = c
c.ppp = p1
p.jr_save()
}
func testThreeNodeCycle() {
let p1 = PPP()
let p2 = PPP()
let p3 = PPP()
p1.ppp = p2
p2.ppp = p3
p3.ppp = p1
p1.jr_save()
}
func test1Cycle() {
let p = PPP()
let c = CCC()
p.ccc = c
c.ppp = p
p.jr_save()
}
func testFindByID() {
let p = PPP.jr_find(byID: "FBE5701E-ECBB-494A-BE62-7C7114C780A1")
p?.isEqual(nil);
}
func truncateTable() {
PPP.jr_truncateTable()
CCC.jr_truncateTable()
}
}
|
9b1e3491a0a1f00bdf9a558914af5afa
| 19.219697 | 95 | 0.500937 | false | true | false | false |
roroque/Compiladores
|
refs/heads/master
|
MaquinaVirtual/MaquinaVirtual/Commands.swift
|
apache-2.0
|
1
|
//
// Commands.swift
// MaquinaVirtualCompiladores
//
// Created by Gabriel Neves Ferreira on 8/11/16.
// Copyright © 2016 Gabriel Neves Ferreira. All rights reserved.
//
import Cocoa
class Commands {
//Views to modify
var outputView : NSTextView
var inputView : NSTextView
//Engine variables
var s : Int = 0 //numero da pilha
var M : [Int] = [] //pilha de dados
var i : Int = 0 //numero da instrucao
//class init
init(aOutputView: NSTextView,aInputView : NSTextView){
outputView = aOutputView
inputView = aInputView
}
//engine helpers
func getStackCount() -> Int {
return M.count
}
func getStackRowContent(row : Int) -> String{
if row < M.count {
return M[row].description
}
return ""
}
//Virtual Machine Functions
//ldc function
func loadConstant(k : Int) {
s = s + 1
M[s] = k
}
//ldv function
func loadValue(n : Int) {
s = s + 1
M[s] = M[n]
}
//add function
func add() {
M[s-1] = M[s-1] + M[s]
s = s-1
}
//sub function
func sub() {
M[s-1] = M[s-1] - M[s]
s = s-1
}
//mult function
func mult() {
M[s-1] = M[s-1] * M[s]
s = s-1
}
//div function
func div() {
M[s-1] = M[s-1] / M[s]
s = s-1
}
//inv function
func invert() {
M[s] = -M[s]
}
//and function
func and(){
if M[s-1] == 1 && M[s] == 1 {
M[s-1] = 1
}else{
M[s-1] = 0
}
s = s-1
}
//or function
func or(){
if M[s-1] == 1 || M[s] == 1 {
M[s-1] = 1
}else{
M[s-1] = 0
}
s = s-1
}
//neg function
func neg(){
M[s] = 1 - M[s]
}
//less than function
func lessThan() {
if M[s-1] < M[s]{
M[s-1] = 1
}else{
M[s-1] = 0
}
s = s-1
}
//greater than function
func greaterThan() {
if M[s-1] > M[s]{
M[s-1] = 1
}else{
M[s-1] = 0
}
s = s-1
}
//equal than function
func equalThan() {
if M[s-1] == M[s]{
M[s-1] = 1
}else{
M[s-1] = 0
}
s = s-1
}
//different than function
func diferentThan() {
if M[s-1] != M[s]{
M[s-1] = 1
}else{
M[s-1] = 0
}
s = s-1
}
//less or equal than function
func lessEqualThan() {
if M[s-1] <= M[s]{
M[s-1] = 1
}else{
M[s-1] = 0
}
s = s-1
}
//greater or equal than function
func greaterEqualThan() {
if M[s-1] >= M[s]{
M[s-1] = 1
}else{
M[s-1] = 0
}
s = s-1
}
//start Function
func startProgram() {
s = -1
//olhar melhor essa logica
}
//halt function
func haltProgram() {
//olhar melhor essa logica
}
//store function
func store(n : Int) {
M[n] = M[s]
s = s-1
}
//jump function
func jump(t : Int){
i = t
}
//jump false function
func jumpFalse(t : Int){
if M[s] == 0 {
i = t
}else{
i = i + 1
}
s = s - 1
}
//null
func null() {
//do nothing
}
//reading Functions
func startReading(){
s = s + 1
//enable text field for writing
//disable text field to continue
//olhar melhor essa logica
}
func finishReading(value : Int){
M.append(value)
//disable text field for writing
//enable text field to continue
//olhar melhor essa logica
printInAView(value.description, aTextView: inputView)
}
//printing Funtion
func printOutput(){
printInAView(M[s].description, aTextView: outputView)
s = s-1
}
//alloc Function
func alloc(m : Int, n : Int) {
//equal to for int i = 0 ; i < n; i ++
for k in 0...(n - 1) {
s = s + 1
M[s] = M[m + k]
}
}
//dalloc Function
func dalloc(m : Int, n : Int) {
//equal to for int k = n - 1; k >= 0; k--
for k in (0...(n - 1)).reverse() {
M[m+k] = M[s]
s = s-1
}
}
//call Function
func call(t : Int) {
s = s + 1
M[s] = i + 1
i = t
}
//return Function
func returnFromFunction() {
i = M[s]
s = s - 1
}
//Auxiliary Functions
private func printInAView(aString: String,aTextView : NSTextView) {
aTextView.editable = true
aTextView.insertText(aString)
aTextView.insertNewline(nil)
aTextView.editable = false
}
//Switch for functions
func callFunctionWithCommand(command : String,firstParameter : Int?, secondParameter : Int?){
switch command {
case "LDC":
loadConstant(firstParameter!)
break
case "LDV":
loadValue(firstParameter!)
break
case "ADD":
add()
break
case "SUB":
sub()
break
case "MULT":
mult()
break
case "DIVI":
div()
break
case "INV":
invert()
break
case "AND":
and()
break
case "OR":
or()
break
case "NEG":
neg()
break
case "CME":
lessThan()
break
case "CMA":
greaterThan()
break
case "CEQ":
equalThan()
break
case "CDIF":
diferentThan()
break
case "CMEQ":
lessEqualThan()
break
case "CMAQ":
greaterEqualThan()
break
case "START":
startProgram()
break
case "HLT":
haltProgram()
break
case "STR":
store(firstParameter!)
break
case "JMP":
jump(firstParameter!)
break
case "JMPF":
jumpFalse(firstParameter!)
break
case "NULL":
null()
break
case "RD":
startReading()
break
case "PRN":
printOutput()
break
case "ALLOC":
alloc(firstParameter!, n: secondParameter!)
break
case "DALLOC":
dalloc(firstParameter!, n: secondParameter!)
break
case "CALL":
call(firstParameter!)
break
case "RETURN":
returnFromFunction()
break
default:
print(command + " is not valid")
}
//checar se o incremento ta implicito ou nao apenas se for algum dos jumps
if command != "JMP" || command != "JMPF" {
i = i + 1
}
}
}
|
cf9cd91b4d26a8be2fe5adcfa90cab17
| 17.454976 | 97 | 0.39471 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
refs/heads/master
|
Modules/DelegatedSelfCustody/Tests/DelegatedSelfCustodyDataTests/BuildTxResponseTests.swift
|
lgpl-3.0
|
1
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
@testable import DelegatedSelfCustodyData
import ToolKit
import XCTest
// swiftlint:disable line_length
final class BuildTxResponseTests: XCTestCase {
func testDecodes() throws {
guard let jsonData = json.data(using: .utf8) else {
XCTFail("Failed to read data.")
return
}
let response = try JSONDecoder().decode(BuildTxResponse.self, from: jsonData)
XCTAssertEqual(response.summary.relativeFee, "1")
XCTAssertEqual(response.summary.absoluteFeeMaximum, "2")
XCTAssertEqual(response.summary.absoluteFeeEstimate, "3")
XCTAssertEqual(response.summary.amount, "4")
XCTAssertEqual(response.summary.balance, "5")
XCTAssertEqual(response.preImages.count, 1)
let preImage = response.preImages[0]
XCTAssertEqual(preImage.preImage, "1")
XCTAssertEqual(preImage.signingKey, "2")
XCTAssertEqual(preImage.signatureAlgorithm, .secp256k1)
XCTAssertNil(preImage.descriptor)
let payloadJsonValue: JSONValue = .dictionary([
"version": .number(0),
"auth": .dictionary([
"authType": .number(4),
"spendingCondition": .dictionary([
"hashMode": .number(0),
"signer": .string("71cb17c2d7f5e2ba71fab0aa6172f02d7265ff14"),
"nonce": .string("0"),
"fee": .string("600"),
"keyEncoding": .number(0),
"signature": .dictionary([
"type": .number(9),
"data": .string("0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000")
])
])
]),
"payload": .dictionary([
"type": .number(8),
"payloadType": .number(0),
"recipient": .dictionary([
"type": .number(5),
"address": .dictionary([
"type": .number(0),
"version": .number(22),
"hash160": .string("afc896bb4b998cd40dd885b31d7446ef86b04eb0")
])
]),
"amount": .string("1"),
"memo": .dictionary([
"type": .number(3),
"content": .string("")
])
]),
"chainId": .number(1),
"postConditionMode": .number(2),
"postConditions": .dictionary([
"type": .number(7),
"lengthPrefixBytes": .number(4),
"values": .array([])
]),
"anchorMode": .number(3)
])
let rawTxJsonValue: JSONValue = .dictionary(
[
"version": .number(1),
"payload": payloadJsonValue
]
)
XCTAssertEqual(response.rawTx, rawTxJsonValue)
}
}
private let json = """
{
"summary": {
"relativeFee": "1",
"absoluteFeeMaximum": "2",
"absoluteFeeEstimate": "3",
"amount": "4",
"balance": "5"
},
"rawTx": {
"version": 1,
"payload": {
"version": 0,
"auth": {
"authType": 4,
"spendingCondition": {
"hashMode": 0,
"signer": "71cb17c2d7f5e2ba71fab0aa6172f02d7265ff14",
"nonce": "0",
"fee": "600",
"keyEncoding": 0,
"signature": {
"type": 9,
"data": "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
}
}
},
"payload": {
"type": 8,
"payloadType": 0,
"recipient": {
"type": 5,
"address": {
"type": 0,
"version": 22,
"hash160": "afc896bb4b998cd40dd885b31d7446ef86b04eb0"
}
},
"amount": "1",
"memo": {
"type": 3,
"content": ""
}
},
"chainId": 1,
"postConditionMode": 2,
"postConditions": {
"type": 7,
"lengthPrefixBytes": 4,
"values": []
},
"anchorMode": 3
}
},
"preImages": [
{
"preImage": "1",
"signingKey": "2",
"descriptor": null,
"signatureAlgorithm": "secp256k1"
}
]
}
"""
|
ac6b79630ad9679f792692cb98fd11ab
| 32.25 | 173 | 0.456411 | false | false | false | false |
imod/VisualEffect_ios8
|
refs/heads/master
|
VisualEffect_ios8/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// VisualEffect_ios8
//
// Created by Dominik on 09/06/14.
// Copyright (c) 2014 Dominik. All rights reserved.
//
import UIKit
extension Array {
func each(callback: T -> ()) {
for item in self {
callback(item)
}
}
func eachWithIndex(callback: (T, Int) -> ()) {
var index = 0
for item in self {
callback(item, index)
index += 1
}
}
}
class CustomTableViewCell: UITableViewCell {
@IBOutlet var backgroundImage: UIImageView
@IBOutlet var titleLabel: UILabel
func loadItem(#title: String, image: String) {
backgroundImage.image = UIImage(named: image)
titleLabel.text = title
}
}
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var tableView: UITableView
var items: (String, String)[] = [
("❤", "swift 1.jpeg"),
("We", "swift 2.jpeg"),
("❤", "swift 3.jpeg"),
("Swift", "swift 4.jpeg"),
("❤", "swift 5.jpeg")
]
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
var cell: CustomTableViewCell = self.tableView.dequeueReusableCellWithIdentifier("customCell") as CustomTableViewCell
var (title, image) = items[indexPath.row]
cell.loadItem(title: title, image: image)
return cell
}
func tableView(tableView: UITableView!, didSelectRowAtindexPath indexPath: NSIndexPath!) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
println("you selected cell #\(indexPath.row)")
}
func addEffects() {
[
UIBlurEffectStyle.Light,
UIBlurEffectStyle.Dark,
UIBlurEffectStyle.ExtraLight
].map {
UIBlurEffect(style: $0)
}.eachWithIndex { (effect, index) in
var effectView = UIVisualEffectView(effect: effect)
effectView.frame = CGRectMake(0, CGFloat(50 * index), 320, 50)
self.view.addSubview(effectView)
}
}
override func viewDidLoad() {
super.viewDidLoad()
addEffects()
var nib = UINib(nibName: "CustomTableViewCell", bundle: nil)
tableView.registerNib(nib, forCellReuseIdentifier: "customCell")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
e3e5fdc0d5664e78c1200f43b12671e1
| 24.990476 | 125 | 0.594723 | false | false | false | false |
mike-wernli/six-scrum-poker
|
refs/heads/master
|
six-scrum-poker/ClassicViewController.swift
|
apache-2.0
|
1
|
//
// ClassicViewController.swift
// six-scrum-poker
//
// Created by codecamp on 10.06.16.
// Copyright © 2016 six.codecamp16. All rights reserved.
//
import UIKit
class ClassicViewController: 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.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let detailView = segue.destinationViewController as! ClassicDetailsViewController
NSLog("Segue is: " + segue.identifier!)
if segue.identifier == "showCardQuestion" {
detailView.labelCardText = "?"
//detailView.view.backgroundColor = UIColor(red: 0, green: 165/255, blue: 0, alpha: 1)
detailView.view.backgroundColor = UIColor.lightGrayColor()
NSLog("Pressed for Card ?")
} else if segue.identifier == "showCardCoffee" {
detailView.labelCardText = "☕️"
detailView.view.backgroundColor = UIColor.lightGrayColor()
NSLog("Pressed for Card coffee")
} else if segue.identifier == "showCard0" {
detailView.labelCardText = "0"
detailView.view.backgroundColor = UIColor.lightGrayColor()
NSLog("Pressed for Card 0")
} else if segue.identifier == "showCardHalf" {
detailView.labelCardText = "½"
detailView.view.backgroundColor = UIColor.lightGrayColor()
NSLog("Pressed for Card Half")
} else if segue.identifier == "showCard1" {
detailView.labelCardText = "1"
detailView.view.backgroundColor = UIColor.grayColor()
NSLog("Pressed for Card 1")
} else if segue.identifier == "showCard2" {
detailView.labelCardText = "2"
detailView.view.backgroundColor = UIColor.lightGrayColor().colorWithAlphaComponent(0.75)
NSLog("Pressed for Card 2")
} else if segue.identifier == "showCard3" {
detailView.labelCardText = "3"
detailView.view.backgroundColor = UIColor.greenColor().colorWithAlphaComponent(0.75)
NSLog("Pressed for Card 3")
} else if segue.identifier == "showCard5" {
detailView.labelCardText = "5"
detailView.view.backgroundColor = UIColor.yellowColor().colorWithAlphaComponent(0.75)
detailView.view.opaque = true
NSLog("Pressed for Card 5")
} else if segue.identifier == "showCard8" {
detailView.labelCardText = "8"
detailView.view.backgroundColor = UIColor.orangeColor()
detailView.labelPokerCard.textColor = UIColor.lightGrayColor()
NSLog("Pressed for Card 8")
} else if segue.identifier == "showCard13" {
detailView.labelCardText = "13"
detailView.view.backgroundColor = UIColor.blueColor().colorWithAlphaComponent(0.75)
NSLog("Pressed for Card 13")
} else if segue.identifier == "showCard20" {
detailView.labelCardText = "20"
detailView.view.backgroundColor = UIColor.redColor().colorWithAlphaComponent(0.75)
NSLog("Pressed for Card 20")
} else if segue.identifier == "showCard40" {
detailView.labelCardText = "40"
detailView.view.backgroundColor = UIColor.purpleColor().colorWithAlphaComponent(0.75)
NSLog("Pressed for Card 40")
} else if segue.identifier == "showCard100" {
detailView.labelCardText = "100"
detailView.view.backgroundColor = UIColor.brownColor().colorWithAlphaComponent(0.75)
detailView.labelPokerCard.hidden = true
detailView.labelPokerCardSmall.hidden = false
NSLog("Pressed for Card 100")
} else if segue.identifier == "showCardInfinity" {
detailView.labelCardText = "∞"
detailView.view.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.75)
detailView.labelPokerCard.textColor = UIColor.whiteColor()
NSLog("Pressed for Card Infinity")
} else {
detailView.labelCardText = "na"
}
}
/*
// 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.
}
*/
}
|
9fe929d18878480a70f78a4c9f105454
| 38.669421 | 106 | 0.627083 | false | false | false | false |
mbcharbonneau/MonsterPit
|
refs/heads/master
|
Home Control/RoomSensorCell.swift
|
mit
|
1
|
//
// RoomSensorCell.swift
// Home Control
//
// Created by mbcharbonneau on 7/21/15.
// Copyright (c) 2015 Once Living LLC. All rights reserved.
//
import UIKit
class RoomSensorCell: UICollectionViewCell {
@IBOutlet weak private var nameLabel: UILabel?
@IBOutlet weak private var tempLabel: UILabel?
@IBOutlet weak private var humidityLabel: UILabel?
@IBOutlet weak private var lightLabel: UILabel?
@IBOutlet weak private var lastUpdatedLabel: UILabel?
private var lastUpdate: NSDate?
required init?(coder aDecoder: NSCoder) {
super.init(coder:aDecoder)
backgroundColor = Configuration.Colors.Red
layer.cornerRadius = 6.0
}
func configureWithSensor( sensor: RoomSensor ) {
nameLabel?.text = sensor.name
lastUpdate = sensor.updatedAt
if let degreesC = sensor.temperature {
let tempString = NSString( format:"%.1f", celsiusToFahrenheit( degreesC ) )
tempLabel?.text = "\(tempString) ℉"
} else {
tempLabel?.text = "-.- ℉"
}
if let humidity = sensor.humidity {
let humidityString = NSString( format:"%.0f", humidity * 100.0 )
humidityLabel?.text = "H: \(humidityString)%"
} else {
humidityLabel?.text = "H: -.-%"
}
if let light = sensor.light {
let lightString = NSString( format:"%.0f", luxToPercent( light ) * 100.0 )
lightLabel?.text = "L: \(lightString)%"
} else {
lightLabel?.text = "L: -.-%"
}
updateTimeLabel()
}
func updateTimeLabel() {
let formatter = NSDateComponentsFormatter()
formatter.unitsStyle = NSDateComponentsFormatterUnitsStyle.Short
formatter.includesApproximationPhrase = false
formatter.collapsesLargestUnit = false
formatter.maximumUnitCount = 1
formatter.allowedUnits = [.Hour, .Minute, .Second, .Day]
if let date = lastUpdate {
let string = formatter.stringFromDate( date, toDate:NSDate() )!
lastUpdatedLabel?.text = "Data is \(string) old"
} else {
lastUpdatedLabel?.text = ""
}
}
private func celsiusToFahrenheit( celsius: Double ) -> Double {
return celsius * 9 / 5 + 32
}
private func luxToPercent( lux: Double ) -> Double {
return min( lux / 60, 1.0 )
}
}
|
1bc300172b14a1fb6220a43be50533e4
| 29.777778 | 87 | 0.587244 | false | false | false | false |
NoryCao/zhuishushenqi
|
refs/heads/master
|
zhuishushenqi/Root/Controllers/ZSVoucherViewController.swift
|
mit
|
1
|
//
// ZSVoucherViewController.swift
// zhuishushenqi
//
// Created by caony on 2019/1/9.
// Copyright © 2019年 QS. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import MJRefresh
typealias ZSVoucherHandler = (_ indexPath:IndexPath)->Void
class ZSVoucherParentViewController: BaseViewController, ZSSegmentProtocol {
var segmentViewController = ZSSegmentViewController()
var segmentView:UISegmentedControl!
var headerView:UIView!
private var vcs:[UIViewController] = []
override func viewDidLoad() {
super.viewDidLoad()
setupSubviews()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
segmentViewController.scrollViewDidEndDeceleratingHandler = { index in
self.segmentView.selectedSegmentIndex = index
}
segmentViewController.view.frame = CGRect(x: 0, y: headerView.frame.maxY, width: self.view.bounds.width, height: self.view.bounds.height - headerView.frame.maxY)
}
func setupSubviews() {
headerView = UIView(frame: CGRect(x: 0, y: kNavgationBarHeight, width: self.view.bounds.width, height: 60))
headerView.backgroundColor = UIColor.white
segmentView = UISegmentedControl(frame: CGRect(x: 0, y: 20, width: self.view.bounds.width, height: 30))
segmentView.tintColor = UIColor.red
headerView.addSubview(segmentView)
view.addSubview(headerView)
var viewControllers:[UIViewController] = []
var titles = ["可使用","已用完","已过期"]
for i in 0..<3 {
let viewController = ZSVoucherViewController()
viewController.index = i
viewController.title = titles[i]
viewController.didSelectRowHandler = { indexPath in
}
viewControllers.append(viewController)
segmentView.insertSegment(withTitle: titles[i], at: i, animated: false)
}
vcs = viewControllers
segmentView.selectedSegmentIndex = 0
segmentView.addTarget(self, action: #selector(segmentTap), for: .valueChanged)
addChild(segmentViewController)
view.addSubview(segmentViewController.view)
}
func segmentViewControllers() -> [UIViewController] {
return vcs
}
@objc func segmentTap() {
let index = segmentView.selectedSegmentIndex
self.segmentViewController.didSelect(index: index)
}
}
class ZSVoucherViewController: ZSBaseTableViewController, Refreshable {
var index:Int = 0
var viewModel:ZSMyViewModel = ZSMyViewModel()
fileprivate let disposeBag = DisposeBag()
var headerRefresh:MJRefreshHeader?
var footerRefresh:MJRefreshFooter?
var start = 0
var limit = 20
var didSelectRowHandler:ZSVoucherHandler?
override func viewDidLoad() {
super.viewDidLoad()
setupSubviews()
}
func setupSubviews() {
let header = initRefreshHeader(tableView) {
self.start = 0
self.viewModel.fetchVoucher(token: ZSLogin.share.token, type: self.voucherType(), start: self.start, limit: self.limit, completion: { (voucherList) in
self.tableView.reloadData()
})
}
let footer = initRefreshFooter(tableView) {
self.start += self.limit
self.viewModel.fetchMoreVoucher(token: ZSLogin.share.token, type: self.voucherType(), start: self.start, limit: self.limit, completion: { (vouchers) in
self.tableView.reloadData()
})
}
headerRefresh = header
footerRefresh = footer
headerRefresh?.beginRefreshing()
viewModel
.autoSetRefreshHeaderStatus(header: header, footer: footer)
.disposed(by: disposeBag)
}
func vouchers() ->[ZSVoucher]? {
if index == 0 {
return viewModel.useableVoucher
} else if index == 1 {
return viewModel.unuseableVoucher
}
return viewModel.expiredVoucher
}
func voucherType()->String {
let types = ["useable","unuseable","expired"]
return types[index]
}
override func registerCellClasses() -> Array<AnyClass> {
return [ZSVoucherCell.self]
}
//MARK: - UITableView
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return vouchers()?.count ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.qs_dequeueReusableCell(ZSVoucherCell.self)
if let voucherList = vouchers() {
cell?.titleText = "\(voucherList[indexPath.row].amount)"
cell?.rightText = "\(voucherList[indexPath.row].balance)"
cell?.titleDetailText = "\(voucherList[indexPath.row].expired.qs_subStr(to: 10))"
cell?.rightDetailText = voucherList[indexPath.row].from
}
return cell!
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60
}
}
|
b8616aacafa85a2a7361729e4c8824ba
| 32.626582 | 169 | 0.639563 | false | false | false | false |
maxoly/PulsarKit
|
refs/heads/master
|
PulsarKit/PulsarKit/Sources/Sizes/CompositeSize.swift
|
mit
|
1
|
//
// CompositeSize.swift
// PulsarKit
//
// Created by Massimo Oliviero on 02/03/2018.
// Copyright © 2019 Nacoon. All rights reserved.
//
import UIKit
public struct CompositeSize: Sizeable {
let widthSize: Sizeable
let heightSize: Sizeable
public init(widthSize: Sizeable = AutolayoutSize(), heightSize: Sizeable = AutolayoutSize()) {
self.widthSize = widthSize
self.heightSize = heightSize
}
public func size<View: UIView>(for view: View, descriptor: Descriptor, model: AnyHashable, in container: UIScrollView, at indexPath: IndexPath) -> CGSize {
let width = widthSize.size(for: view, descriptor: descriptor, model: model, in: container, at: indexPath).width
let height = heightSize.size(for: view, descriptor: descriptor, model: model, in: container, at: indexPath).height
return CGSize(width: width, height: height)
}
}
|
99753596271f3bfa49bed0308b88093a
| 35.4 | 159 | 0.69011 | false | false | false | false |
RocketChat/Rocket.Chat.iOS
|
refs/heads/develop
|
Rocket.Chat/Models/Mapping/MentionModelMapping.swift
|
mit
|
1
|
//
// MentionModelMapping.swift
// Rocket.Chat
//
// Created by Matheus Cardoso on 9/8/17.
// Copyright © 2017 Rocket.Chat. All rights reserved.
//
import Foundation
import SwiftyJSON
import RealmSwift
extension Mention: ModelMappeable {
func map(_ values: JSON, realm: Realm?) {
self.userId = values["_id"].string
self.username = values["username"].stringValue
if let realName = values["name"].string {
self.realName = realName
} else if let userId = userId {
if let realm = realm {
if let user = realm.object(ofType: User.self, forPrimaryKey: userId as AnyObject) {
self.realName = user.name ?? user.username ?? ""
} else {
self.realName = values["username"].stringValue
}
}
}
}
}
|
550c7bfc692ce8aa2b44180b93ecf785
| 28.689655 | 99 | 0.570267 | false | false | false | false |
davidbutz/ChristmasFamDuels
|
refs/heads/master
|
iOS/Boat Aware/registerControllerViewController.swift
|
mit
|
1
|
//
// registerControllerViewController.swift
// ChristmasFanDuel
//
// Created by Dave Butz on 1/10/16.
// Copyright © 2016 Dave Butz. All rights reserved.
//
import UIKit
class registerControllerViewController: UIViewController {
@IBOutlet weak var txtControllerName: UITextField!
@IBOutlet weak var btnRegister: UIButton!
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.
}
@IBAction func btnRegisterClick(sender: AnyObject) {
//I should be connected to the Thrive Network. (192.168.41.1)
//A known IP address.
//I need to POST a response to /api/register/controller
//TODO: handle blank controllername
let appvar = ApplicationVariables.applicationvariables;
let controller_name = txtControllerName.text;
let JSONObject: [String : AnyObject] = [
"userid" : appvar.userid ,
"account_id" : appvar.account_id,
"fname" : appvar.fname,
"lname" : appvar.lname,
"password" : appvar.password,
"account_name" : appvar.account_name,
"username" : appvar.username,
"cellphone" : appvar.cellphone,
"controller_name" : controller_name!
]
let api = APICalls();
api.apicallout("/api/register/controller" , iptype: "thriveIPAddress", method: "POST", JSONObject: JSONObject, callback: { (response) -> () in
//handle the response. i should get status : fail/success and message: various
let status = (response as! NSDictionary)["status"] as! String;
let message = (response as! NSDictionary)["message"] as! String;
print(message);
if(status=="success"){
dispatch_async(dispatch_get_main_queue(),{
self.performSegueWithIdentifier("SetupSeq3New", sender: self);
});
}
else{
print(message);
}
});
}
/*
// 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.
}
*/
}
|
89889282516f15553fd6fb180ae0f973
| 34.256757 | 150 | 0.607129 | false | false | false | false |
SanctionCo/pilot-ios
|
refs/heads/master
|
pilot/LoginViewController.swift
|
mit
|
1
|
//
// LoginViewController.swift
// pilot
//
// Created by Nick Eckert on 7/24/17.
// Copyright © 2017 sanction. All rights reserved.
//
import Alamofire
import HTTPStatusCodes
import SwiftHash
import UIKit
class LoginViewController: UIViewController {
let authenticationHelper = AuthenticationHelper()
let profileImageView: UIImageView = {
let imageView = UIImageView()
imageView.image = UIImage(named: "ProfileImage")
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFit
return imageView
}()
let loginRegisterSegmentedControl: UISegmentedControl = {
let segmentedControl = UISegmentedControl(items: ["Login", "Register"])
segmentedControl.translatesAutoresizingMaskIntoConstraints = false
segmentedControl.tintColor = UIColor.white
segmentedControl.selectedSegmentIndex = 0
segmentedControl.addTarget(self, action: #selector(updateLoginRegisterView), for: .valueChanged)
return segmentedControl
}()
let inputsContainerView: UIView = {
let inputsView = UIView()
inputsView.backgroundColor = UIColor.white
inputsView.translatesAutoresizingMaskIntoConstraints = false
inputsView.layer.cornerRadius = 5
inputsView.layer.masksToBounds = true
return inputsView
}()
let emailTextField: UITextField = {
let textField = UITextField()
textField.placeholder = "Email"
textField.translatesAutoresizingMaskIntoConstraints = false
textField.autocapitalizationType = .none
textField.autocorrectionType = .no
return textField
}()
let passwordTextField: UITextField = {
let textField = UITextField()
textField.placeholder = "Password"
textField.translatesAutoresizingMaskIntoConstraints = false
textField.isSecureTextEntry = true
return textField
}()
let confirmPasswordTextField: UITextField = {
let textField = UITextField()
textField.placeholder = "Re-type Password"
textField.translatesAutoresizingMaskIntoConstraints = false
textField.isSecureTextEntry = true
return textField
}()
let emailSeparatorView: UIView = {
let view = UIView()
view.backgroundColor = UIColor.LayoutLightGray
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
let passwordSeparatorView: UIView = {
let view = UIView()
view.backgroundColor = UIColor.LayoutLightGray
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
let loginRegisterButton: UIButton = {
let button = UIButton(type: .system)
button.backgroundColor = UIColor.PilotDarkBlue
button.setTitle("Login", for: .normal)
button.setTitleColor(UIColor.TextWhite, for: .normal)
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
button.translatesAutoresizingMaskIntoConstraints = false
button.layer.cornerRadius = 5
button.layer.masksToBounds = true
button.addTarget(self, action: #selector(handleButtonAction), for: .touchUpInside)
return button
}()
let activitySpinner: UIActivityIndicatorView = {
let spinner = UIActivityIndicatorView()
spinner.translatesAutoresizingMaskIntoConstraints = false
spinner.hidesWhenStopped = true
return spinner
}()
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar.isHidden = true
view.backgroundColor = UIColor.PilotLightBlue
view.addSubview(profileImageView)
view.addSubview(loginRegisterSegmentedControl)
view.addSubview(inputsContainerView)
view.addSubview(loginRegisterButton)
view.addSubview(activitySpinner)
setupProfileImageView()
setupLoginRegisterSegmentedControl()
setupInputsContainerView()
setupLoginRegisterButton()
setupActivitySpinner()
NetworkManager.sharedInstance.adapter = AuthAdapter()
attemptAutomaticLogin()
}
@objc private func handleButtonAction() {
if loginRegisterSegmentedControl.selectedSegmentIndex == 0 {
performTextLogin()
} else {
register()
}
}
private func attemptAutomaticLogin() {
self.fillFromKeychain()
// If this is the first login or the user has declined to set up Biometrics, we can't use biometrics
guard UserDefaults.standard.contains(key: "biometrics"),
UserDefaults.standard.bool(forKey: "biometrics") else {
return
}
// Otherwise, Biometrics should be enabled and we can prompt for authentication
authenticationHelper.authenticationWithBiometrics(onSuccess: {
DispatchQueue.main.async {
self.performBiometricLogin()
}
}, onFailure: { fallbackType, message in
// If failure is called with fallback type fallbackWithError, show an alert
if fallbackType == .fallbackWithError {
DispatchQueue.main.async {
let alert = UIAlertController(title: self.authenticationHelper.biometricType().rawValue + " Error",
message: message,
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
})
}
/// Perform a login that the user completed from biometrics
private func performBiometricLogin() {
if let (email, password) = authenticationHelper.getFromKeychain() {
login(email: email, password: password)
}
}
/// Perform a login that the user completed from the text boxes
private func performTextLogin() {
if let error = LoginValidationForm(email: emailTextField.text, password: passwordTextField.text).validate() {
let alert = UIAlertController(title: "Invalid Input", message: error.errorString, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alert, animated: true, completion: nil)
return
}
let hashedPassword = MD5(passwordTextField.text!).lowercased()
authenticationHelper.saveToKeychain(email: emailTextField.text!, password: hashedPassword)
login(email: emailTextField.text!, password: hashedPassword)
}
/// Perform the login by getting the user from Thunder
private func login(email: String, password: String) {
self.activitySpinner.startAnimating()
self.loginRegisterButton.isEnabled = false
PilotUser.fetch(with: ThunderRouter.login(email, password), onSuccess: { pilotUser in
UserManager.sharedInstance = UserManager(pilotUser: pilotUser)
// Attempt to set up biometrics if this is the first time logging in
self.setUpBiometrics(completion: {
let homeTabBarController = HomeTabBarController()
// Set the platform list in the PlatformManager class
PlatformManager.sharedInstance.setPlatforms(platforms: pilotUser.availablePlatforms)
DispatchQueue.main.async { [weak self] in
self?.activitySpinner.stopAnimating()
self?.loginRegisterButton.isEnabled = true
self?.present(homeTabBarController, animated: true, completion: nil)
}
})
}, onError: { _ in
DispatchQueue.main.async { [weak self] in
self?.activitySpinner.stopAnimating()
self?.loginRegisterButton.isEnabled = true
}
})
}
/// Register a new user in Thunder
private func register() {
if let error = RegisterValidationForm(email: emailTextField.text,
password: passwordTextField.text,
confirmPassword: confirmPasswordTextField.text).validate() {
let alert = UIAlertController(title: "Invalid Input", message: error.errorString, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alert, animated: true, completion: nil)
return
}
let hashedPassword = MD5(passwordTextField.text!).lowercased()
authenticationHelper.saveToKeychain(email: emailTextField.text!, password: hashedPassword)
self.activitySpinner.startAnimating()
self.loginRegisterButton.isEnabled = false
let pilotUser = PilotUser(email: emailTextField.text!, password: hashedPassword)
PilotUser.upload(with: ThunderRouter.createPilotUser(pilotUser), onSuccess: { _ in
DispatchQueue.main.async { [weak self] in
self?.activitySpinner.stopAnimating()
self?.loginRegisterButton.isEnabled = true
let alert = UIAlertController(title: "Account Created!", message: "", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { _ in
self?.loginRegisterSegmentedControl.selectedSegmentIndex = 0
self?.updateLoginRegisterView()
}))
self?.present(alert, animated: true, completion: nil)
}
}, onError: { _ in
DispatchQueue.main.async { [weak self] in
self?.activitySpinner.stopAnimating()
self?.loginRegisterButton.isEnabled = true
let alert = UIAlertController(title: "Registration Error",
message: "There was a problem creating your account",
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self?.present(alert, animated: true, completion: nil)
}
})
}
/// Prompt the user to set up biometrics for the first time
private func setUpBiometrics(completion: @escaping () -> Void) {
// Only set up if the user has not been asked before
guard !UserDefaults.standard.contains(key: "biometrics") else {
completion()
return
}
// Only set up if the user can use biometrics
guard authenticationHelper.canUseBiometrics() else {
completion()
return
}
let biometricType = self.authenticationHelper.biometricType().rawValue
let alert = UIAlertController(title: "Enable " + biometricType,
message: "Do you want to enable " + biometricType + " login?",
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { _ in
UserDefaults.standard.set(true, forKey: "biometrics")
completion()
}))
alert.addAction(UIAlertAction(title: "No", style: .default, handler: { _ in
UserDefaults.standard.set(false, forKey: "biometrics")
completion()
}))
present(alert, animated: true, completion: nil)
}
/// Fill the email text field from the keychain
private func fillFromKeychain() {
if let (email, _) = authenticationHelper.getFromKeychain() {
emailTextField.text = email
}
}
@objc private func updateLoginRegisterView() {
// Change height of inputsContainerView
inputsContainerViewHeight?.constant = loginRegisterSegmentedControl.selectedSegmentIndex == 0 ? 80 : 120
// Change the height of the passwordSeperatorView
passwordSeperatorViewHeight?.isActive = false
passwordSeperatorViewHeight = passwordSeparatorView.heightAnchor
.constraint(equalToConstant: loginRegisterSegmentedControl.selectedSegmentIndex == 0 ? 0 : 1)
passwordSeperatorViewHeight?.isActive = true
// Change height of the confirmPasswordTextField
confirmPasswordTextFieldHeight?.isActive = false
confirmPasswordTextFieldHeight = confirmPasswordTextField.heightAnchor
.constraint(equalTo: inputsContainerView.heightAnchor,
multiplier: loginRegisterSegmentedControl.selectedSegmentIndex == 0 ? 0 : 1/3)
confirmPasswordTextFieldHeight?.isActive = true
// Change the height of the emailTextField
emailTextFieldHeight?.isActive = false
emailTextFieldHeight =
emailTextField.heightAnchor.constraint(equalTo: inputsContainerView.heightAnchor,
multiplier: loginRegisterSegmentedControl.selectedSegmentIndex == 0 ? 1/2 : 1/3)
emailTextFieldHeight?.isActive = true
// Change the height of the passwordTextField
passwordTextFieldHeight?.isActive = false
passwordTextFieldHeight = passwordTextField
.heightAnchor.constraint(equalTo: inputsContainerView.heightAnchor,
multiplier: loginRegisterSegmentedControl.selectedSegmentIndex == 0 ? 1/2 : 1/3)
passwordTextFieldHeight?.isActive = true
// Clear the second password field
confirmPasswordTextField.text = ""
// Rename button to "Register"
loginRegisterButton
.setTitle(loginRegisterSegmentedControl.selectedSegmentIndex == 0 ? "Login": "Register", for: .normal)
view.layoutIfNeeded()
}
private func setupProfileImageView() {
profileImageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
profileImageView.widthAnchor.constraint(equalToConstant: 150).isActive = true
profileImageView.heightAnchor.constraint(equalTo: profileImageView.widthAnchor, multiplier: 21/50).isActive = true
profileImageView.bottomAnchor
.constraint(equalTo: loginRegisterSegmentedControl.topAnchor, constant: -50).isActive = true
}
private func setupLoginRegisterSegmentedControl() {
loginRegisterSegmentedControl.centerXAnchor.constraint(equalTo: profileImageView.centerXAnchor).isActive = true
loginRegisterSegmentedControl.widthAnchor.constraint(equalTo: inputsContainerView.widthAnchor).isActive = true
loginRegisterSegmentedControl.heightAnchor.constraint(equalToConstant: 36).isActive = true
loginRegisterSegmentedControl.bottomAnchor
.constraint(equalTo: inputsContainerView.topAnchor, constant: -12).isActive = true
}
var inputsContainerViewHeight: NSLayoutConstraint?
var emailTextFieldHeight: NSLayoutConstraint?
var passwordTextFieldHeight: NSLayoutConstraint?
var passwordSeperatorViewHeight: NSLayoutConstraint?
var confirmPasswordTextFieldHeight: NSLayoutConstraint?
private func setupInputsContainerView() {
// Add the subviews to the inputsContainerView
inputsContainerView.addSubview(emailTextField)
inputsContainerView.addSubview(passwordTextField)
inputsContainerView.addSubview(confirmPasswordTextField)
inputsContainerView.addSubview(passwordSeparatorView)
inputsContainerView.addSubview(emailSeparatorView)
// Add constraints to the inputsContainerView
inputsContainerView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
inputsContainerView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
inputsContainerView.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -25).isActive = true
inputsContainerViewHeight = inputsContainerView.heightAnchor.constraint(equalToConstant: 80)
inputsContainerViewHeight?.isActive = true
// Add constraints to the emailTextField
emailTextField.leftAnchor.constraint(equalTo: inputsContainerView.leftAnchor, constant: 12).isActive = true
emailTextField.topAnchor.constraint(equalTo: inputsContainerView.topAnchor).isActive = true
emailTextField.widthAnchor.constraint(equalTo: inputsContainerView.widthAnchor).isActive = true
emailTextFieldHeight =
emailTextField.heightAnchor.constraint(equalTo: inputsContainerView.heightAnchor, multiplier: 1/2)
emailTextFieldHeight?.isActive = true
// Add constraints to the emailSeperatorView
emailSeparatorView.leftAnchor.constraint(equalTo: inputsContainerView.leftAnchor).isActive = true
emailSeparatorView.topAnchor.constraint(equalTo: emailTextField.bottomAnchor).isActive = true
emailSeparatorView.widthAnchor.constraint(equalTo: inputsContainerView.widthAnchor).isActive = true
emailSeparatorView.heightAnchor.constraint(equalToConstant: 1).isActive = true
// Add constraints to the passwordTextField
passwordTextField.leftAnchor.constraint(equalTo: inputsContainerView.leftAnchor, constant: 12).isActive = true
passwordTextField.topAnchor.constraint(equalTo: emailSeparatorView.bottomAnchor).isActive = true
passwordTextField.widthAnchor.constraint(equalTo: inputsContainerView.widthAnchor).isActive = true
passwordTextFieldHeight =
passwordTextField.heightAnchor.constraint(equalTo: inputsContainerView.heightAnchor, multiplier: 1/2)
passwordTextFieldHeight?.isActive = true
// Add constraints to passwordSeperatorView
passwordSeparatorView.leftAnchor.constraint(equalTo: inputsContainerView.leftAnchor).isActive = true
passwordSeparatorView.topAnchor.constraint(equalTo: passwordTextField.bottomAnchor).isActive = true
passwordSeparatorView.widthAnchor.constraint(equalTo: inputsContainerView.widthAnchor).isActive = true
passwordSeperatorViewHeight = passwordSeparatorView.heightAnchor.constraint(equalToConstant: 0)
passwordSeperatorViewHeight?.isActive = true
// Add constraints to confirmPasswordTextField
confirmPasswordTextField
.leftAnchor.constraint(equalTo: inputsContainerView.leftAnchor, constant: 12).isActive = true
confirmPasswordTextField.topAnchor.constraint(equalTo: passwordSeparatorView.bottomAnchor).isActive = true
confirmPasswordTextField.widthAnchor.constraint(equalTo: inputsContainerView.widthAnchor).isActive = true
confirmPasswordTextFieldHeight =
confirmPasswordTextField.heightAnchor.constraint(equalTo: inputsContainerView.heightAnchor, multiplier: 0)
confirmPasswordTextFieldHeight?.isActive = true
}
private func setupLoginRegisterButton() {
loginRegisterButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
loginRegisterButton.topAnchor.constraint(equalTo: inputsContainerView.bottomAnchor, constant: 12).isActive = true
loginRegisterButton.widthAnchor.constraint(equalTo: inputsContainerView.widthAnchor).isActive = true
loginRegisterButton.heightAnchor.constraint(equalToConstant: 32).isActive = true
}
private func setupActivitySpinner() {
activitySpinner.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
activitySpinner.topAnchor.constraint(equalTo: loginRegisterButton.bottomAnchor, constant: 20).isActive = true
activitySpinner.widthAnchor.constraint(equalToConstant: 10).isActive = true
activitySpinner.heightAnchor.constraint(equalToConstant: 10).isActive = true
}
}
|
33232fba7c74adf853872abb71293f69
| 40.775744 | 118 | 0.740359 | false | false | false | false |
M2Mobi/Marky-Mark
|
refs/heads/master
|
markymark/Classes/Layout Builders/UIView/Block Builders/Block/QuoteBlockLayoutBuilder.swift
|
mit
|
1
|
//
// Created by Jim van Zummeren on 11/05/16.
// Copyright © 2016 M2mobi. All rights reserved.
//
import Foundation
import UIKit
class QuoteBlockLayoutBuilder: InlineAttributedStringViewLayoutBlockBuilder {
// MARK: LayoutBuilder
override func relatedMarkDownItemType() -> MarkDownItem.Type {
return QuoteMarkDownItem.self
}
override func build(_ markDownItem: MarkDownItem, asPartOfConverter converter: MarkDownConverter<UIView>, styling: ItemStyling) -> UIView {
let label = AttributedInteractiveLabel()
label.markDownAttributedString = attributedStringForMarkDownItem(markDownItem, styling: styling)
if let urlOpener = urlOpener {
label.urlOpener = urlOpener
}
let spacing: UIEdgeInsets? = (styling as? ContentInsetStylingRule)?.contentInsets
return ContainerView(view: label, spacing: spacing)
}
}
|
9b080390bdfd626e34461ae11f3eb68a
| 31.142857 | 143 | 0.722222 | false | false | false | false |
mlibai/XZKit
|
refs/heads/master
|
XZKit/Code/UICollectionViewFlowLayout/XZCollectionViewFlowLayout.swift
|
mit
|
1
|
//
// CollectionViewFlowLayout.swift
// XZKit
//
// Created by Xezun on 2018/7/10.
// Copyright © 2018年 XEZUN INC.com All rights reserved.
//
import UIKit
@available(*, unavailable, renamed: "XZKit.UICollectionViewDelegateFlowLayout")
typealias CollectionViewDelegateFlowLayout = XZKit.UICollectionViewDelegateFlowLayout
@available(*, unavailable, renamed: "XZKit.UICollectionViewFlowLayout")
typealias CollectionViewFlowLayout = XZKit.UICollectionViewFlowLayout
/// 通过本协议,可以具体的控制 XZKit.UICollectionViewFlowLayout 布局的 LineAlignment、InteritemAlignment 等内容。
@objc(XZCollectionViewDelegateFlowLayout)
public protocol UICollectionViewDelegateFlowLayout: UIKit.UICollectionViewDelegateFlowLayout {
/// 当 XZKit.UICollectionViewFlowLayout 计算元素布局时,通过此代理方法,获取指定行的对齐方式。
///
/// - Parameters:
/// - collectionView: UICollectionView 视图。
/// - collectionViewLayout: UICollectionViewLayout 视图布局对象。
/// - indexPath: 行的布局信息,包括行所在的区 section、行在区中的次序 line 。
/// - Returns: 行对齐方式。
@objc optional func collectionView(_ collectionView: UIKit.UICollectionView, layout collectionViewLayout: UIKit.UICollectionViewLayout, lineAlignmentForLineAt indexPath: XZKit.UICollectionViewIndexPath) -> XZKit.UICollectionViewFlowLayout.LineAlignment
/// 获取同一行元素间的对齐方式:垂直滚动时,为同一横排元素在垂直方向上的对齐方式;水平滚动时,同一竖排元素,在水平方向的对齐方式。
///
/// - Parameters:
/// - collectionView: UICollectionView 视图。
/// - collectionViewLayout: UICollectionViewLayout 视图布局对象。
/// - indexPath: 元素的布局信息,包括元素所在的区 section、在区中的次序 item、所在的行 line、在行中的次序 column 。
/// - Returns: 元素对齐方式。
@objc optional func collectionView(_ collectionView: UIKit.UICollectionView, layout collectionViewLayout: UIKit.UICollectionViewLayout, interitemAlignmentForItemAt indexPath: XZKit.UICollectionViewIndexPath) -> XZKit.UICollectionViewFlowLayout.InteritemAlignment
/// 获取 section 的内边距,与原生的方法不同,本方法返回的为自适应布局方向的 XZKit.EdgeInsets 结构体。
///
/// - Parameters:
/// - collectionView: UICollectionView 视图。
/// - collectionViewLayout: UICollectionViewLayout 视图布局对象。
/// - section: 指定的 section 序数。
/// - Returns: 内边距。
@objc optional func collectionView(_ collectionView: UIKit.UICollectionView, layout collectionViewLayout: UIKit.UICollectionViewLayout, edgeInsetsForSectionAt section: Int) -> EdgeInsets
}
extension UICollectionViewFlowLayout {
/// LineAlignment 描述了每行内元素的排列方式。
/// 当滚动方向为垂直方向时,水平方向上为一行,那么 LineAlignment 可以表述为向左对齐、向右对齐等;
/// 当滚动方向为水平时,垂直方向为一行,那么 LineAlignment 可以表述为向上对齐、向下对齐。
@objc(XZCollectionViewFlowLayoutLineAlignment)
public enum LineAlignment: Int, CustomStringConvertible {
/// 向首端对齐,末端不足留空。
/// - Note: 首端对齐与布局方向相关,例如 A、B、C 三元素在同一行,自左向右布局 [ A B C _ ],自右向左则为 [ _ C B A ] 。
case leading
/// 向末端对齐,首端不足留空。
/// - Note: 末端对齐与布局方向相关,例如 A、B、C 三元素在同一行,自左向右布局 [ _ A B C ],自右向左则为 [ C B A _ ] 。
case trailing
/// 居中对齐,两端可能留空。
case center
/// 两端对齐,平均分布,占满整行;如果行只有一个元素,该元素首端对齐。
/// - Note: 每行的元素间距可能都不一样。
case justified
/// 两端对齐,平均分布,占满整行,如果行只有一个元素,该元素居中对齐。
/// - Note: 每行的元素间距可能都不一样。
case justifiedCenter
/// 两端对齐,平均分布,占满整行,如果行只有一个元素,该元素末端对齐。
/// - Note: 每行的元素间距可能都不一样。
case justifiedTrailing
public var description: String {
switch self {
case .leading: return "leading"
case .trailing: return "trailing"
case .center: return "center"
case .justified: return "justified"
case .justifiedCenter: return "justifiedCenter"
case .justifiedTrailing: return "justifiedTrailing"
}
}
}
/// 同一行元素与元素的对齐方式。
@objc(XZCollectionViewFlowLayoutInteritemAlignment)
public enum InteritemAlignment: Int, CustomStringConvertible {
/// 垂直滚动时,顶部对齐;水平滚动时,布局方向从左到右,左对齐,布局方向从右到左,右对齐。
case ascender
/// 垂直滚动时,水平中线对齐;水平滚动时,垂直中线对齐。
case median
/// 垂直滚动时,底部对齐;水平滚动时,布局方向从左到右,右对齐,布局方向从右到左,左对齐。
case descender
public var description: String {
switch self {
case .ascender: return "ascender"
case .median: return "median"
case .descender: return "descender"
}
}
}
fileprivate class SectionItem {
let header: XZKit.UICollectionViewLayoutAttributes?
let items: [XZKit.UICollectionViewLayoutAttributes]
let footer: XZKit.UICollectionViewLayoutAttributes?
init(header: XZKit.UICollectionViewLayoutAttributes?, items: [XZKit.UICollectionViewLayoutAttributes], footer: XZKit.UICollectionViewLayoutAttributes?, frame: CGRect) {
self.header = header
self.items = items
self.footer = footer
self.frame = frame
}
/// Section 的 frame ,用于优化性能。
let frame: CGRect
}
}
/// XZKit.UICollectionViewFlowLayout 布局属性,记录了 Cell 所在行列的信息。
@objc(XZCollectionViewLayoutAttributes)
open class UICollectionViewLayoutAttributes: UIKit.UICollectionViewLayoutAttributes, UICollectionViewIndexPath {
public var item: Int {
return indexPath.item
}
public var section: Int {
return indexPath.section
}
public fileprivate(set) var line: Int = 0
public fileprivate(set) var column: Int = 0
}
/// 支持多种对齐方式的 UICollectionView 自定义布局,为了区分于 UIKit.UICollectionViewFlowLayout ,引用需加 XZKit 前缀。
/// - Note: 优先使用 XZKit.UICollectionViewDelegateFlowLayout 作为代理协议,并兼容 UIKit.UICollectionViewDelegateFlowLayout 协议。
/// - Note: 对于 zIndex 进行了特殊处理,排序越后的视图 zIndex 越大;Header/Footer 的 zIndex 比 Cell 的大。
@objc(XZCollectionViewFlowLayout)
open class UICollectionViewFlowLayout: UIKit.UICollectionViewLayout {
/// 滚动方向。默认 .vertical 。
@objc open var scrollDirection: UIKit.UICollectionView.ScrollDirection = .vertical {
didSet { invalidateLayout() }
}
/// 行间距。滚动方向为垂直时,水平方向为一行;滚动方向为水平时,垂直方向为一行。默认 0 ,代理方法的返回值优先。
@objc open var minimumLineSpacing: CGFloat = 0 {
didSet { invalidateLayout() }
}
/// 内间距。同一行内两个元素之间的距离。默认 0 ,代理方法的返回值优先。
@objc open var minimumInteritemSpacing: CGFloat = 0 {
didSet { invalidateLayout() }
}
/// 元素大小。默认 (50, 50),代理方法返回的大小优先。
@objc open var itemSize: CGSize = CGSize.init(width: 50, height: 50) {
didSet { invalidateLayout() }
}
/// SectionHeader 大小,默认 0 ,代理方法的返回值优先。
@objc open var headerReferenceSize: CGSize = .zero {
didSet { invalidateLayout() }
}
/// SectionFooter 大小,默认 0 ,代理方法的返回值优先。
@objc open var footerReferenceSize: CGSize = .zero {
didSet { invalidateLayout() }
}
/// SectionItem 外边距。不包括 SectionHeader/SectionFooter 。默认 .zero ,代理方法的返回值优先。
@objc open var sectionInsets: EdgeInsets = .zero {
didSet { invalidateLayout() }
}
/// 行对齐方式,默认 .leading ,代理方法的返回值优先。
@objc open var lineAlignment: LineAlignment = .justified {
didSet { invalidateLayout() }
}
/// 元素对齐方式,默认 .median ,代理方法的返回值优先。
@objc open var interitemAlignment: InteritemAlignment = .median {
didSet { invalidateLayout() }
}
/// 记录了所有元素信息。
fileprivate var sectionItems = [SectionItem]()
/// 记录了 contentSize 。
fileprivate var contentSize = CGSize.zero
}
extension UICollectionViewFlowLayout {
open override class var layoutAttributesClass: Swift.AnyClass {
return XZKit.UICollectionViewLayoutAttributes.self
}
open override var collectionViewContentSize: CGSize {
return contentSize
}
open override func invalidateLayout() {
super.invalidateLayout()
sectionItems.removeAll()
}
/// 当 UICollectionView 的宽度改变时,需重新计算布局。
///
/// - Parameter newBounds: The collectionView's new bounds.
/// - Returns: true or false.
open override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
switch scrollDirection {
case .vertical:
return (newBounds.width != contentSize.width)
case .horizontal:
return (newBounds.height != contentSize.height)
default:
return false
}
}
private func adjustedContentInset(_ collectionView: UIKit.UICollectionView) -> UIEdgeInsets {
if #available(iOS 11.0, *) {
// iOS 11 以后,导航栏的高度,安全边距合并到这个属性了。
return collectionView.adjustedContentInset
} else {
// iOS 11 之前,导航栏的高度是加入到这个属性里的。
return collectionView.contentInset
}
}
override open func prepare() {
guard let collectionView = self.collectionView else { return }
let delegate = collectionView.delegate as? UIKit.UICollectionViewDelegateFlowLayout
let frame = collectionView.frame
let adjustedContentInset = self.adjustedContentInset(collectionView)
// 使用 (0, 0) 作为起始坐标进行计算,根据 adjustedContentInset 来计算内容区域大小。
switch self.scrollDirection {
case .horizontal:
contentSize = CGSize.init(width: 0, height: frame.height - adjustedContentInset.top - adjustedContentInset.bottom)
for section in 0 ..< collectionView.numberOfSections {
let x = contentSize.width
let headerAttributes = self.prepareHorizontal(collectionView, delegate: delegate, layoutAttributesForHeaderInSection: section)
let itemAttributes = self.prepareHorizontal(collectionView, delegate: delegate, layoutAttributesForItemsInSection: section)
let footerAttributes = self.prepareHorizontal(collectionView, delegate: delegate, layoutAttributesForFooterInSection: section)
headerAttributes?.zIndex = itemAttributes.count + section
footerAttributes?.zIndex = itemAttributes.count + section
let frame = CGRect.init(x: x, y: 0, width: contentSize.width - x, height: contentSize.height)
self.sectionItems.append(SectionItem.init(header: headerAttributes, items: itemAttributes, footer: footerAttributes, frame: frame))
}
case .vertical: fallthrough
default:
contentSize = CGSize.init(width: frame.width - adjustedContentInset.left - adjustedContentInset.right, height: 0)
for section in 0 ..< collectionView.numberOfSections {
let y = contentSize.height
let headerAttributes = self.prepareVertical(collectionView, delegate: delegate, layoutAttributesForHeaderInSection: section)
let itemAttributes = self.prepareVertical(collectionView, delegate: delegate, layoutAttributesForItemsInSection: section)
let footerAttributes = self.prepareVertical(collectionView, delegate: delegate, layoutAttributesForFooterInSection: section)
// 同一 Section 的 Header/Footer 具有相同的 zIndex 并且越靠后越大,保证后面的 SectionHeader/Footer 在前面的之上。
// 同时,Header/Footer 的 zIndex 比 Cell 的 zIndex 都大,Cell 也是索引越大 zIndex 越大。
headerAttributes?.zIndex = itemAttributes.count + section
footerAttributes?.zIndex = itemAttributes.count + section
let frame = CGRect.init(x: 0, y: y, width: contentSize.width, height: contentSize.height - y)
self.sectionItems.append(SectionItem.init(header: headerAttributes, items: itemAttributes, footer: footerAttributes, frame: frame))
}
}
}
override open func layoutAttributesForElements(in rect: CGRect) -> [UIKit.UICollectionViewLayoutAttributes]? {
// 超出范围肯定没有了。
if rect.maxX <= 0 || rect.minX >= contentSize.width || rect.minY >= contentSize.height || rect.maxY <= 0 {
return nil
}
// 如果当前已有找到在 rect 范围内的,那么如果遍历时,又遇到不在 rect 内的,说明已经超出屏幕,没有必要继续遍历了。
// 由于对齐方式的不同,Cell可能与指定区域没有交集,但是其后面的 Cell 却可能在该区域内。
var array = [UICollectionViewLayoutAttributes]()
// 遍历所有 Cell 布局。
for sectionItem in self.sectionItems {
guard rect.intersects(sectionItem.frame) else {
continue
}
if let header = sectionItem.header {
if rect.intersects(header.frame) {
array.append(header)
}
}
for item in sectionItem.items {
if rect.intersects(item.frame) {
array.append(item)
}
}
if let footer = sectionItem.footer {
if rect.intersects(footer.frame) {
array.append(footer)
}
}
}
return array
}
override open func layoutAttributesForItem(at indexPath: Foundation.IndexPath) -> UIKit.UICollectionViewLayoutAttributes? {
return sectionItems[indexPath.section].items[indexPath.item]
}
override open func layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: Foundation.IndexPath) -> UIKit.UICollectionViewLayoutAttributes? {
switch elementKind {
case UIKit.UICollectionView.elementKindSectionHeader: return sectionItems[indexPath.section].header
case UIKit.UICollectionView.elementKindSectionFooter: return sectionItems[indexPath.section].footer
default: fatalError("Not supported UICollectionElementKind `\(elementKind)`.")
}
}
/// Returns .leftToRight.
open override var developmentLayoutDirection: UIUserInterfaceLayoutDirection {
return .leftToRight
}
/// Retruns true.
open override var flipsHorizontallyInOppositeLayoutDirection: Bool {
return true
}
}
extension UICollectionViewFlowLayout {
/// 准备指定 Section 的 Header 布局信息。
@objc open func prepareVertical(_ collectionView: UIKit.UICollectionView, delegate: UIKit.UICollectionViewDelegateFlowLayout?, layoutAttributesForHeaderInSection section: Int) -> XZKit.UICollectionViewLayoutAttributes? {
let headerSize = delegate?.collectionView?(collectionView, layout: self, referenceSizeForHeaderInSection: section) ?? self.headerReferenceSize
guard headerSize != .zero else {
return nil
}
let headerAttributes = XZKit.UICollectionViewLayoutAttributes.init(
forSupplementaryViewOfKind: UIKit.UICollectionView.elementKindSectionHeader,
with: Foundation.IndexPath.init(item: 0, section: section)
)
headerAttributes.frame = CGRect.init(
// SectionHeader 水平居中
x: (contentSize.width - headerSize.width) * 0.5,
y: contentSize.height,
width: headerSize.width,
height: headerSize.height
)
contentSize.height += headerSize.height
return headerAttributes
}
/// 准备指定 Section 的 Footer 布局信息。
@objc open func prepareVertical(_ collectionView: UIKit.UICollectionView, delegate: UIKit.UICollectionViewDelegateFlowLayout?, layoutAttributesForFooterInSection section: Int) -> XZKit.UICollectionViewLayoutAttributes? {
let footerSize = delegate?.collectionView?(collectionView, layout: self, referenceSizeForFooterInSection: section) ?? self.footerReferenceSize
guard footerSize != .zero else {
return nil
}
let footerAttributes = XZKit.UICollectionViewLayoutAttributes.init(
forSupplementaryViewOfKind: UIKit.UICollectionView.elementKindSectionFooter,
with: Foundation.IndexPath.init(item: 0, section: section)
)
footerAttributes.frame = CGRect.init(
x: (contentSize.width - footerSize.width) * 0.5,
y: contentSize.height,
width: footerSize.width,
height: footerSize.height
)
contentSize.height += footerSize.height
return footerAttributes
}
/// 获取行对齐方式。
@objc open func collectionView(_ collectionView: UIKit.UICollectionView, lineAlignmentForLineAt indexPath: XZKit.UICollectionViewIndexPath, delegate: UIKit.UICollectionViewDelegateFlowLayout?) -> LineAlignment {
guard let delegate = delegate as? UICollectionViewDelegateFlowLayout else { return self.lineAlignment }
guard let lineAlignment = delegate.collectionView?(collectionView, layout: self, lineAlignmentForLineAt: indexPath) else { return self.lineAlignment }
return lineAlignment
}
/// 获取元素对齐方式。
@objc open func collectionView(_ collectionView: UIKit.UICollectionView, interitemAlignmentForItemAt indexPath: UICollectionViewIndexPath, delegate: UIKit.UICollectionViewDelegateFlowLayout?) -> InteritemAlignment {
guard let delegate = delegate as? UICollectionViewDelegateFlowLayout else { return self.interitemAlignment }
guard let interitemAlignment = delegate.collectionView?(collectionView, layout: self, interitemAlignmentForItemAt: indexPath) else { return self.interitemAlignment }
return interitemAlignment
}
@objc open func collectionView(_ collectionView: UIKit.UICollectionView, edgeInsetsForSectionAt section: Int, delegate: UIKit.UICollectionViewDelegateFlowLayout?) -> EdgeInsets {
if let delegate = delegate as? UICollectionViewDelegateFlowLayout {
if let edgeInsets = delegate.collectionView?(collectionView, layout: self, edgeInsetsForSectionAt: section) {
return edgeInsets
}
}
if let edgeInsets = delegate?.collectionView?(collectionView, layout: self, insetForSectionAt: section) {
return EdgeInsets.init(edgeInsets, layoutDirection: collectionView.userInterfaceLayoutDirection)
}
return self.sectionInsets
}
@objc open func collectionView(_ collectionView: UIKit.UICollectionView, sizeForItemAt indexPath: IndexPath, delegate: UIKit.UICollectionViewDelegateFlowLayout?) -> CGSize {
guard let delegate = delegate as? UICollectionViewDelegateFlowLayout else { return self.itemSize }
guard let itemSize = delegate.collectionView?(collectionView, layout: self, sizeForItemAt: indexPath) else { return self.itemSize }
return itemSize
}
/// 准备指定 Section 的 Cell 布局信息。
@objc open func prepareVertical(_ collectionView: UIKit.UICollectionView, delegate: UIKit.UICollectionViewDelegateFlowLayout?, layoutAttributesForItemsInSection section: Int) -> [XZKit.UICollectionViewLayoutAttributes] {
let sectionInsets = self.collectionView(collectionView, edgeInsetsForSectionAt: section, delegate: delegate)
contentSize.height += sectionInsets.top
let minimumLineSpacing = delegate?.collectionView?(collectionView, layout: self, minimumLineSpacingForSectionAt: section) ?? self.minimumLineSpacing
let minimumInteritemSpacing = delegate?.collectionView?(collectionView, layout: self, minimumInteritemSpacingForSectionAt: section) ?? self.minimumInteritemSpacing
var sectionAttributes = [XZKit.UICollectionViewLayoutAttributes]()
// 行最大宽度。
let maxLineLength: CGFloat = contentSize.width - sectionInsets.leading - sectionInsets.trailing
// Section 高度,仅内容区域,不包括 header、footer 和内边距。
// 初始值扣除一个间距,方便使用 间距 + 行高度 来计算高度。
// 每计算完一行,增加此值,并在最终增加到 contentSize 中。
var sectionHeight: CGFloat = -minimumLineSpacing
// 当前正在计算的行的宽度,新行开始后此值会被初始化。
// 初始值扣除一个间距,方便使用 间距 + 宽度 来计算总宽度。
var currentLineLength: CGFloat = -minimumInteritemSpacing
// 行最大高度。以行中最高的 Item 为行高度。
var currentLineHeight: CGFloat = 0
/// 保存了一行的 Cell 的布局信息。
var currentLineAttributes = [XZKit.UICollectionViewLayoutAttributes]()
/// 当一行的布局信息获取完毕时,从当前上下文中添加行布局信息,并重置上下文变量。
func addLineAttributesFromCurrentContext() {
var length: CGFloat = 0
let lineLayoutInfo = self.collectionView(collectionView, lineLayoutForLineWith: currentLineAttributes, maxLineLength: maxLineLength, lineLength: currentLineLength, minimumInteritemSpacing: minimumInteritemSpacing, delegate: delegate)
for column in 0 ..< currentLineAttributes.count {
let itemAttributes = currentLineAttributes[column]
itemAttributes.column = column
var x: CGFloat = 0
if column == 0 {
x = sectionInsets.leading + lineLayoutInfo.indent
length = itemAttributes.size.width
} else {
x = sectionInsets.leading + lineLayoutInfo.indent + length + lineLayoutInfo.spacing
length = length + lineLayoutInfo.spacing + itemAttributes.size.width
}
var y: CGFloat = contentSize.height + sectionHeight + minimumLineSpacing
let interitemAlignment = self.collectionView(collectionView, interitemAlignmentForItemAt: itemAttributes, delegate: delegate)
switch interitemAlignment {
case .ascender: break
case .median: y += (currentLineHeight - itemAttributes.size.height) * 0.5
case .descender: y += (currentLineHeight - itemAttributes.size.height)
}
itemAttributes.frame = CGRect.init(x: x, y: y, width: itemAttributes.size.width, height: itemAttributes.size.height)
sectionAttributes.append(itemAttributes)
}
currentLineAttributes.removeAll()
// 开始新的一行,Section 高度增加,重置高度、宽度。
sectionHeight += (minimumLineSpacing + currentLineHeight)
currentLineHeight = 0
currentLineLength = -minimumInteritemSpacing
}
var currentLine: Int = 0
// 获取所有 Cell 的大小。
for index in 0 ..< collectionView.numberOfItems(inSection: section) {
let indexPath = IndexPath.init(item: index, section: section)
let itemSize = self.collectionView(collectionView, sizeForItemAt: indexPath, delegate: delegate)
// 新的宽度超出最大宽度,且行元素不为空,那么该换行了,把当前行中的所有元素移动到总的元素集合中。
var newLineWidth = currentLineLength + (minimumInteritemSpacing + itemSize.width)
if newLineWidth > maxLineLength && !currentLineAttributes.isEmpty {
// 将已有数据添加到布局中。
addLineAttributesFromCurrentContext()
// 换行。
currentLine += 1
// 新行的宽度
newLineWidth = itemSize.width
}
// 如果没有超出最大宽度,或者行为空(其中包括,单个 Cell 的宽度超过最大宽度的情况),或者换行后的新行,将元素添加到行中。
let itemAttributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
itemAttributes.line = currentLine
itemAttributes.size = itemSize
itemAttributes.zIndex = index
currentLineAttributes.append(itemAttributes)
// 当前行宽度、高度。
currentLineLength = newLineWidth
currentLineHeight = max(currentLineHeight, itemSize.height)
}
addLineAttributesFromCurrentContext()
contentSize.height += sectionHeight
contentSize.height += sectionInsets.bottom
return sectionAttributes
}
// MARK: - 水平方向。
@objc open func prepareHorizontal(_ collectionView: UIKit.UICollectionView, delegate: UIKit.UICollectionViewDelegateFlowLayout?, layoutAttributesForHeaderInSection section: Int) -> XZKit.UICollectionViewLayoutAttributes? {
let headerSize = delegate?.collectionView?(collectionView, layout: self, referenceSizeForHeaderInSection: section) ?? self.headerReferenceSize
guard headerSize != .zero else {
return nil
}
let headerAttributes = XZKit.UICollectionViewLayoutAttributes.init(
forSupplementaryViewOfKind: UIKit.UICollectionView.elementKindSectionHeader,
with: Foundation.IndexPath.init(item: 0, section: section)
)
headerAttributes.frame = CGRect.init(
x: contentSize.width,
y: (contentSize.height - headerSize.height) * 0.5,
width: headerSize.width,
height: headerSize.height
)
contentSize.width += headerSize.width
return headerAttributes
}
@objc open func prepareHorizontal(_ collectionView: UIKit.UICollectionView, delegate: UIKit.UICollectionViewDelegateFlowLayout?, layoutAttributesForFooterInSection section: Int) -> XZKit.UICollectionViewLayoutAttributes? {
let footerSize = delegate?.collectionView?(collectionView, layout: self, referenceSizeForFooterInSection: section) ?? self.footerReferenceSize
guard footerSize != .zero else {
return nil
}
let footerAttributes = XZKit.UICollectionViewLayoutAttributes.init(
forSupplementaryViewOfKind: UIKit.UICollectionView.elementKindSectionFooter,
with: Foundation.IndexPath.init(item: 0, section: section)
)
footerAttributes.frame = CGRect.init(
x: contentSize.width,
y: (contentSize.height - footerSize.height) * 0.5,
width: footerSize.width,
height: footerSize.height
)
contentSize.width += footerSize.width
return footerAttributes
}
@objc open func prepareHorizontal(_ collectionView: UIKit.UICollectionView, delegate: UIKit.UICollectionViewDelegateFlowLayout?, layoutAttributesForItemsInSection section: Int) -> [XZKit.UICollectionViewLayoutAttributes] {
let sectionInsets = self.collectionView(collectionView, edgeInsetsForSectionAt: section, delegate: delegate)
contentSize.width += sectionInsets.leading
let minimumLineSpacing = delegate?.collectionView?(collectionView, layout: self, minimumLineSpacingForSectionAt: section) ?? self.minimumLineSpacing
let minimumInteritemSpacing = delegate?.collectionView?(collectionView, layout: self, minimumInteritemSpacingForSectionAt: section) ?? self.minimumInteritemSpacing
var sectionAttributes = [XZKit.UICollectionViewLayoutAttributes]()
// 行最大宽度。
let maxLineLength: CGFloat = contentSize.height - sectionInsets.top - sectionInsets.bottom
// Section 高度,仅内容区域,不包括 header、footer 和内边距。
// 初始值扣除一个间距,方便使用 间距 + 行高度 来计算高度。
// 每计算完一行,增加此值,并在最终增加到 contentSize 中。
var sectionHeight: CGFloat = -minimumLineSpacing
// 当前正在计算的行的宽度,新行开始后此值会被初始化。
// 初始值扣除一个间距,方便使用 间距 + 宽度 来计算总宽度。
var currentLineLength: CGFloat = -minimumInteritemSpacing
// 行最大高度。以行中最高的 Item 为行高度。
var currentLineHeight: CGFloat = 0
/// 保存了一行的 Cell 的布局信息。
var currentLineAttributes = [UICollectionViewLayoutAttributes]()
/// 当一行的布局信息获取完毕时,从当前上下文中添加行布局信息,并重置上下文变量。
func addLineAttributesFromCurrentContext() {
let lineLayoutInfo = self.collectionView(collectionView, lineLayoutForLineWith: currentLineAttributes, maxLineLength: maxLineLength, lineLength: currentLineLength, minimumInteritemSpacing: minimumInteritemSpacing, delegate: delegate)
var length: CGFloat = 0
for column in 0 ..< currentLineAttributes.count {
let itemAttributes = currentLineAttributes[column]
itemAttributes.column = column
var y: CGFloat = 0
if column == 0 {
y = contentSize.height - sectionInsets.bottom - lineLayoutInfo.indent - itemAttributes.size.height
length = itemAttributes.size.height
} else {
y = contentSize.height - sectionInsets.bottom - lineLayoutInfo.indent - length - lineLayoutInfo.spacing - itemAttributes.size.height
length = length + lineLayoutInfo.spacing + itemAttributes.size.height
}
var x: CGFloat = contentSize.width + sectionHeight + minimumLineSpacing
let interitemAlignment = self.collectionView(collectionView, interitemAlignmentForItemAt: itemAttributes, delegate: delegate)
switch interitemAlignment {
case .ascender: break
case .median: x += (currentLineHeight - itemAttributes.size.width) * 0.5
case .descender: x += (currentLineHeight - itemAttributes.size.width)
}
itemAttributes.frame = CGRect.init(x: x, y: y, width: itemAttributes.size.width, height: itemAttributes.size.height)
sectionAttributes.append(itemAttributes)
}
currentLineAttributes.removeAll()
sectionHeight += (minimumLineSpacing + currentLineHeight)
currentLineHeight = 0
currentLineLength = -minimumInteritemSpacing
}
var currentLine: Int = 0
// 获取所有 Cell 的大小。
for index in 0 ..< collectionView.numberOfItems(inSection: section) {
let indexPath = IndexPath.init(item: index, section: section)
let itemSize = self.collectionView(collectionView, sizeForItemAt: indexPath, delegate: delegate)
var newLineLength = currentLineLength + (minimumInteritemSpacing + itemSize.height)
if newLineLength > maxLineLength && !currentLineAttributes.isEmpty {
addLineAttributesFromCurrentContext()
currentLine += 1
newLineLength = itemSize.height
}
let itemAttributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
itemAttributes.line = currentLine
itemAttributes.zIndex = index
itemAttributes.size = itemSize
currentLineAttributes.append(itemAttributes)
currentLineLength = newLineLength
currentLineHeight = max(currentLineHeight, itemSize.width)
}
addLineAttributesFromCurrentContext()
contentSize.width += sectionHeight
contentSize.width += sectionInsets.trailing
return sectionAttributes
}
/// 根据行信息计算行布局。因为每一行不能完全占满,根据对齐方式不同,x 坐标相对于起始点,可能需要不同的偏移,元素的间距也可能需要重新计算。
private func collectionView(_ collectionView: UICollectionView, lineLayoutForLineWith currentLineAttributes: [UICollectionViewLayoutAttributes], maxLineLength: CGFloat, lineLength currentLineLength: CGFloat, minimumInteritemSpacing: CGFloat, delegate: UIKit.UICollectionViewDelegateFlowLayout?) -> (indent: CGFloat, spacing: CGFloat) {
let lineAlignment = self.collectionView(collectionView, lineAlignmentForLineAt: currentLineAttributes[0], delegate: delegate)
switch lineAlignment {
case .leading:
return (0, minimumInteritemSpacing)
case .trailing:
return (maxLineLength - currentLineLength, minimumInteritemSpacing)
case .center:
return ((maxLineLength - currentLineLength) * 0.5, minimumInteritemSpacing)
case .justified:
if currentLineAttributes.count > 1 {
return (0, minimumInteritemSpacing + (maxLineLength - currentLineLength) / CGFloat(currentLineAttributes.count - 1))
}
return (0, 0)
case .justifiedCenter:
if currentLineAttributes.count > 1 {
return (0, minimumInteritemSpacing + (maxLineLength - currentLineLength) / CGFloat(currentLineAttributes.count - 1))
}
return ((maxLineLength - currentLineLength) * 0.5, 0)
case .justifiedTrailing:
if currentLineAttributes.count > 1 {
return (0, minimumInteritemSpacing + (maxLineLength - currentLineLength) / CGFloat(currentLineAttributes.count - 1))
}
return ((maxLineLength - currentLineLength), 0)
}
}
}
/// 描述了 UICollectionView 中元素的布局信息。
@objc(XZCollectionViewIndexPath)
public protocol UICollectionViewIndexPath: NSObjectProtocol {
/// 元素在其所在的 section 中的序数。
@objc var item: Int { get }
/// 元素所在的 section 在 UICollectionView 中的序数。
@objc var section: Int { get }
/// 元素在其所在的 line 中的序数。
@objc var column: Int { get }
/// 元素所在的 line 在 section 中的序数。
@objc var line: Int { get }
}
|
901f14bedb4494e01684c02a6489203a
| 46.172214 | 339 | 0.662627 | false | false | false | false |
edragoev1/pdfjet
|
refs/heads/master
|
Sources/PDFjet/QRCode.swift
|
mit
|
1
|
/**
*
Copyright 2009 Kazuhiko Arase
URL: http://www.d-project.com/
Licensed under the MIT license:
http://www.opensource.org/licenses/mit-license.php
The word "QR Code" is registered trademark of
DENSO WAVE INCORPORATED
http://www.denso-wave.com/qrcode/faqpatent-e.html
*/
///
/// Modified and adapted for use in PDFjet by Eugene Dragoev
///
import Foundation
///
/// Used to create 2D QR Code barcodes. Please see Example_21.
///
/// @author Kazuhiko Arase
///
public class QRCode : Drawable {
private let PAD0: UInt32 = 0xEC
private let PAD1: UInt32 = 0x11
private var modules: [[Bool?]]?
private var moduleCount = 33 // Magic Number
private var errorCorrectLevel = ErrorCorrectLevel.M
private var x: Float = 0.0
private var y: Float = 0.0
private var qrData: [UInt8]?
private var m1: Float = 2.0 // Module length
private var color: UInt32 = Color.black
///
/// Used to create 2D QR Code barcodes.
///
/// @param str the string to encode.
/// @param errorCorrectLevel the desired error correction level.
/// @throws UnsupportedEncodingException
///
public init(
_ str: String,
_ errorCorrectLevel: Int) {
self.qrData = Array(str.utf8)
self.errorCorrectLevel = errorCorrectLevel
self.make(false, getBestMaskPattern())
}
public func setPosition(_ x: Float, _ y: Float) {
setLocation(x, y)
}
///
/// Sets the location where this barcode will be drawn on the page.
///
/// @param x the x coordinate of the top left corner of the barcode.
/// @param y the y coordinate of the top left corner of the barcode.
///
@discardableResult
public func setLocation(_ x: Float, _ y: Float) -> QRCode {
self.x = x
self.y = y
return self
}
///
/// Sets the module length of this barcode.
/// The default value is 2.0
///
/// @param moduleLength the specified module length.
///
@discardableResult
public func setModuleLength(_ moduleLength: Float) -> QRCode {
self.m1 = moduleLength
return self
}
public func setColor(_ color: UInt32) {
self.color = color
}
///
/// Draws this barcode on the specified page.
///
/// @param page the specified page.
/// @return x and y coordinates of the bottom right corner of this component.
/// @throws Exception
///
@discardableResult
public func drawOn(_ page: Page?) -> [Float] {
page!.setBrushColor(self.color)
for row in 0..<modules!.count {
for col in 0..<modules!.count {
if isDark(row, col) {
page!.fillRect(x + Float(col)*m1, y + Float(row)*m1, m1, m1)
}
}
}
let w = m1*Float(modules!.count)
let h = m1*Float(modules!.count)
return [self.x + w, self.y + h]
}
public func getData() -> [[Bool?]]? {
return self.modules
}
///
/// @param row the row.
/// @param col the column.
///
func isDark(_ row: Int, _ col: Int) -> Bool {
if modules![row][col] != nil {
return modules![row][col]!
}
return false
}
func getModuleCount() -> Int {
return self.moduleCount
}
func getBestMaskPattern() -> Int {
var minLostPoint = 0
var pattern = 0
for i in 0..<8 {
make(true, i)
let lostPoint = QRUtil.singleton.getLostPoint(self)
if i == 0 || minLostPoint > lostPoint {
minLostPoint = lostPoint
pattern = i
}
}
return pattern
}
func make(
_ test: Bool,
_ maskPattern: Int) {
modules = [[Bool?]]()
for _ in 0..<moduleCount {
modules!.append([Bool?](repeating: nil, count: moduleCount))
}
setupPositionProbePattern(0, 0)
setupPositionProbePattern(moduleCount - 7, 0)
setupPositionProbePattern(0, moduleCount - 7)
setupPositionAdjustPattern()
setupTimingPattern()
setupTypeInfo(test, maskPattern)
mapData(createData(errorCorrectLevel), maskPattern)
}
private func mapData(
_ data: [UInt8],
_ maskPattern: Int) {
var inc = -1
var row = moduleCount - 1
var bitIndex = 7
var byteIndex = 0
var col = moduleCount - 1
while col > 0 {
if col == 6 {
col -= 1
}
while true {
for c in 0..<2 {
if modules![row][col - c] == nil {
var dark = false
if byteIndex < data.count {
dark = (((data[byteIndex] >> bitIndex) & 1) == 1)
}
let mask = QRUtil.singleton.getMask(maskPattern, row, col - c)
if mask {
dark = !dark
}
modules![row][col - c] = dark
bitIndex -= 1
if (bitIndex == -1) {
byteIndex += 1
bitIndex = 7
}
}
}
row += inc
if row < 0 || moduleCount <= row {
row -= inc
inc = -inc
break
}
}
col -= 2
}
}
private func setupPositionAdjustPattern() {
let pos = [6, 26] // Magic Numbers
for i in 0..<pos.count {
for j in 0..<pos.count {
let row = pos[i]
let col = pos[j]
if modules![row][col] != nil {
continue
}
var r = -2
while r <= 2 {
var c = -2
while c <= 2 {
modules![row + r][col + c] =
r == -2 || r == 2 ||
c == -2 || c == 2 ||
(r == 0 && c == 0)
c += 1
}
r += 1
}
}
}
}
private func setupPositionProbePattern(_ row: Int, _ col: Int) {
for r in -1...7 {
for c in -1...7 {
if (row + r <= -1 || moduleCount <= row + r ||
col + c <= -1 || moduleCount <= col + c) {
continue
}
if (0 <= r && r <= 6 && (c == 0 || c == 6)) ||
(0 <= c && c <= 6 && (r == 0 || r == 6)) ||
(2 <= r && r <= 4 && 2 <= c && c <= 4) {
modules![row + r][col + c] = true
}
else {
modules![row + r][col + c] = false
}
}
}
}
private func setupTimingPattern() {
var r = 8
while r < (moduleCount - 8) {
if modules![r][6] == nil {
modules![r][6] = (r % 2 == 0)
r += 1
}
}
var c = 8
while c < (moduleCount - 8) {
if modules![6][c] == nil {
modules![6][c] = (c % 2 == 0)
c += 1
}
}
}
private func setupTypeInfo(
_ test: Bool,
_ maskPattern: Int) {
let data = (errorCorrectLevel << 3) | maskPattern
let bits = QRUtil.singleton.getBCHTypeInfo(data)
for i in 0..<15 {
let mod = (!test && ((bits >> i) & 1) == 1)
if i < 6 {
modules![i][8] = mod
}
else if i < 8 {
modules![i + 1][8] = mod
}
else {
modules![moduleCount - 15 + i][8] = mod
}
}
for i in 0..<15 {
let mod = (!test && ((bits >> i) & 1) == 1)
if i < 8 {
modules![8][moduleCount - i - 1] = mod
}
else if i < 9 {
modules![8][15 - i - 1 + 1] = mod
}
else {
modules![8][15 - i - 1] = mod
}
}
modules![moduleCount - 8][8] = !test
}
private func createData(_ errorCorrectLevel: Int) -> [UInt8] {
let rsBlocks = RSBlock.getRSBlocks(errorCorrectLevel)
let buffer = BitBuffer()
buffer.put(UInt32(4), 4)
buffer.put(UInt32(qrData!.count), 8)
for i in 0..<qrData!.count {
buffer.put(UInt32(qrData![i]), 8)
}
var totalDataCount = 0
for block in rsBlocks {
totalDataCount += block.getDataCount()
}
if buffer.getLengthInBits() > totalDataCount * 8 {
Swift.print("code length overflow. ( " +
String(describing: buffer.getLengthInBits()) + " > " +
String(describing: (totalDataCount * 8)) + " )")
}
if buffer.getLengthInBits() + 4 <= totalDataCount * 8 {
buffer.put(0, 4)
}
// padding
while buffer.getLengthInBits() % 8 != 0 {
buffer.put(false)
}
// padding
while true {
if buffer.getLengthInBits() >= totalDataCount * 8 {
break
}
buffer.put(PAD0, 8)
if buffer.getLengthInBits() >= totalDataCount * 8 {
break
}
buffer.put(PAD1, 8)
}
return createBytes(buffer, rsBlocks)
}
private func createBytes(
_ buffer: BitBuffer,
_ rsBlocks: [RSBlock]) -> [UInt8] {
var offset = 0
var maxDcCount = 0
var maxEcCount = 0
var dcdata = [[Int]?](repeating: nil, count: rsBlocks.count)
var ecdata = [[Int]?](repeating: nil, count: rsBlocks.count)
for r in 0..<rsBlocks.count {
let dcCount = rsBlocks[r].getDataCount()
let ecCount = rsBlocks[r].getTotalCount() - dcCount
maxDcCount = max(maxDcCount, dcCount)
maxEcCount = max(maxEcCount, ecCount)
dcdata[r] = [Int](repeating: 0, count: dcCount)
for i in 0..<dcdata[r]!.count {
dcdata[r]![i] = Int(buffer.getBuffer()![i + offset])
}
offset += dcCount
let rsPoly = QRUtil.singleton.getErrorCorrectPolynomial(ecCount)
let rawPoly = Polynomial(dcdata[r]!, rsPoly.getLength() - 1)
let modPoly = rawPoly.mod(rsPoly)
ecdata[r] = [Int](repeating: 0, count: (rsPoly.getLength() - 1))
for i in 0..<ecdata[r]!.count {
let modIndex = i + modPoly.getLength() - ecdata[r]!.count
ecdata[r]![i] = (modIndex >= 0) ? modPoly.get(modIndex) : 0
}
}
var totalCodeCount = 0
for block in rsBlocks {
totalCodeCount += block.getTotalCount()
}
var data = [UInt8](repeating: 0, count: totalCodeCount)
var index = 0
for i in 0..<maxDcCount {
for r in 0..<rsBlocks.count {
if i < dcdata[r]!.count {
data[index] = UInt8(dcdata[r]![i])
index += 1
}
}
}
for i in 0..<maxEcCount {
for r in 0..<rsBlocks.count {
if i < ecdata[r]!.count {
data[index] = UInt8(ecdata[r]![i])
index += 1
}
}
}
return data
}
}
|
363fe3588bba9022551c811692a00e4b
| 27.539759 | 86 | 0.448244 | false | false | false | false |
ello/ello-ios
|
refs/heads/master
|
Specs/Networking/UserServiceSpec.swift
|
mit
|
1
|
////
/// UserServiceSpec.swift
//
@testable import Ello
import Quick
import Nimble
class UserServiceSpec: QuickSpec {
override func spec() {
describe("UserService") {
var subject: UserService!
beforeEach {
subject = UserService()
}
describe("join(email:username:password:invitationCode:)") {
it("stores the email and password in the keychain") {
subject.join(
email: "[email protected]",
username: "fake-username",
password: "fake-password",
invitationCode: .none,
success: {},
failure: .none
)
let authToken = AuthToken()
expect(authToken.username) == "fake-username"
expect(authToken.password) == "fake-password"
}
}
}
}
}
|
2d56d27435ab60e4185d8b5ba8ce53a4
| 27.714286 | 71 | 0.455721 | false | false | false | false |
EBGToo/SBFrames
|
refs/heads/master
|
Tests/OrientationTest.swift
|
mit
|
1
|
//
// OrientationTest.swift
// SBFrames
//
// Created by Ed Gamble on 7/2/16.
// Copyright © 2016 Edward B. Gamble Jr. All rights reserved.
//
// See the LICENSE file at the project root for license information.
// See the CONTRIBUTORS file at the project root for a list of contributors.
//
import XCTest
import SBUnits
import GLKit
@testable import SBFrames
class OrientationTest: XCTestCase {
let accuracy = Quaternion.epsilon
let base = Frame.root
let a0 = Quantity<Angle>(value: 0.0, unit: radian)
let a45 = Quantity<Angle>(value: Double.pi / 4, unit: radian)
let a90 = Quantity<Angle>(value: Double.pi / 2, unit: radian)
let a180 = Quantity<Angle>(value: Double.pi / 1, unit: radian)
let a90n = Quantity<Angle>(value: -Double.pi / 2, unit: radian)
override func setUp() {
super.setUp()
// What does Apple say is the direction for a quaternion with 0 angle?
let g1 = GLKQuaternionMakeWithAngleAndAxis (0, 0, 0, 1)
let angle = GLKQuaternionAngle (g1)
let axis = GLKQuaternionAxis (g1)
XCTAssertEqual(Double( angle), 0.0, accuracy: 1e-5)
XCTAssertEqual(Double(axis.x), 0.0, accuracy: 1e-5)
XCTAssertEqual(Double(axis.y), 0.0, accuracy: 1e-5)
XCTAssertEqual(Double(axis.z), 0.0, accuracy: 1e-3)
}
override func tearDown() {
super.tearDown()
}
func checkValues (_ p: Position, frame: Frame, unit: SBUnits.Unit<Length>, x: Double, y: Double, z: Double) {
XCTAssert(p.has (frame: frame))
XCTAssertEqual(p.x.value, x, accuracy: accuracy)
XCTAssertEqual(p.y.value, y, accuracy: accuracy)
XCTAssertEqual(p.z.value, z, accuracy: accuracy)
XCTAssertTrue(p.x.unit === unit)
XCTAssertTrue(p.y.unit === unit)
XCTAssertTrue(p.z.unit === unit)
XCTAssertTrue(p.unit === unit)
XCTAssertEqual(p.unit, unit)
}
func checkOrientation (_ o: Orientation, frame: Frame, a: Double, x: Double, y: Double, z: Double) {
guard let (ao, (xo, yo, zo)) = o.quat.asAngleDirection else {
XCTAssert(false)
return
}
XCTAssertEqual(ao, a, accuracy: accuracy)
XCTAssertEqual(xo, x, accuracy: accuracy)
XCTAssertEqual(yo, y, accuracy: accuracy)
XCTAssertEqual(zo, z, accuracy: accuracy)
XCTAssert(o.has (frame: frame))
}
func checkQuant (qA: Quaternion, qB: Quaternion) {
XCTAssertEqual(qA.q0, qB.q0, accuracy: accuracy)
XCTAssertEqual(qA.q1, qB.q1, accuracy: accuracy)
XCTAssertEqual(qA.q2, qB.q2, accuracy: accuracy)
XCTAssertEqual(qA.q3, qB.q3, accuracy: accuracy)
}
func testInit() {
let ob = Orientation (frame: base)
let o0 = Orientation (frame: base, angle: a0, axis: .z)
checkOrientation(o0, frame: base, a: a0.value, x: 0, y: 0, z: 0)
let o45 = Orientation (frame: base, angle: a45, axis: .z)
let o90 = Orientation (frame: base, angle: a90, axis: .z)
checkOrientation(o90, frame: base, a: a90.value, x: 0, y: 0, z: 1)
let _ = [ob, o0, o45,o90]
}
func testInvert () {
// rot .z 90
let o90p = Orientation (frame: base, angle: a90 , axis: .z)
checkOrientation(o90p, frame: base, a: a90.value, x: 0, y: 0, z: 1)
// rot .z -90 -> quat ambiguity rot -.z 90
let o90n = Orientation (frame: base, angle: a90n, axis: .z)
checkOrientation(o90n, frame: base, a: a90.value, x: 0, y: 0, z: -1)
// rot .z 90 .invert ->
let o90i = o90p.inverse
checkOrientation(o90i, frame: base, a: a90.value, x: 0, y: 0, z: -1)
let oc = o90p.compose(o90i)
checkOrientation(oc, frame: base, a: 0, x: 0, y: 0, z: 0)
}
func testCompose () {
let o0 = Orientation (frame: base, angle: a0, axis: .z)
checkOrientation(o0, frame: base, a: a0.value, x: 0, y: 0, z: 0)
let o45 = Orientation (frame: base, angle: a45, axis: .z)
let o90 = Orientation (frame: base, angle: a90, axis: .z)
checkOrientation(o90, frame: base, a: a90.value, x: 0, y: 0, z: 1)
let o90c = o0.compose(o45).compose(o45)
checkOrientation(o90c, frame: base, a: a90.value, x: 0, y: 0, z: 1)
let o0c = o90c.compose(o90.inverse)
checkOrientation(o0c, frame: base, a: a0.value, x: 0, y: 0, z: 1)
}
func testRotate () {
let o45 = Orientation (frame: base, angle: a45, axis: .z)
let c90 = o45.compose(o45)
let o90 = Orientation (frame: base, angle: a90, axis: .z)
XCTAssertEqual(c90.quat.q0, o90.quat.q0, accuracy: 1e-10)
let c180 = o90.compose(o90)
let o180 = Orientation (frame: base, angle: a180, axis: .z)
XCTAssertEqual(c180.quat.q0, o180.quat.q0, accuracy: 1e-10)
let o180x = Orientation (frame: base, angle: a180, axis: .z)
let c180x = Orientation (frame: base, angle: a0, axis: .z).compose(o180x)
checkQuant(qA: o180x.quat, qB: c180x.quat)
}
/*
func testAngles () {
let (phi,theta,psi) = (37.5, 10.0, 22.0)
let o1 = Orientation(frame: base, unit: degree, convention: .fixedXYZ, x: phi, y: theta, z: psi)
let (oPhi, oTheta, oPsi) = o1.asFixedXYZAngles
XCTAssertEqual(phi, degree.convert(oPhi, unit: radian), accuracy: 1e-10)
XCTAssertEqual(theta, degree.convert(oTheta, unit: radian), accuracy: 1e-10)
XCTAssertEqual(psi, degree.convert(oPsi, unit: radian), accuracy: 1e-10)
}
*/
func testPerformanceExample() {
self.measure {
}
}
}
|
ae517db1a08826659664257d637304ec
| 31.760736 | 111 | 0.636704 | false | true | false | false |
gxf2015/DYZB
|
refs/heads/master
|
DYZB/DYZB/Classes/Main/Model/AncnorGroup.swift
|
mit
|
1
|
//
// AncnorGroup.swift
// DYZB
//
// Created by guo xiaofei on 2017/8/14.
// Copyright © 2017年 guo xiaofei. All rights reserved.
//
import UIKit
import HandyJSON
class AncnorGroup: HandyJSON {
var room_list : [AncnorModel]?
var tag_name : String = ""
var icon_name = "home_header_normal"
var icon_url : String = ""
required init(){}
}
class AncnorModel: HandyJSON {
var room_id : Int = 0
var vertical_src : String = ""
var icon_name = "home_header_normal"
var isVertical : Int = 0
var room_name : String = ""
var nickname : String = ""
var online : Int = 0
var anchor_city : String = ""
required init(){}
}
|
95fa392873080fec7c907a8202a360f4
| 15.377778 | 55 | 0.56038 | false | false | false | false |
vanhuyz/learn_swift
|
refs/heads/master
|
JSON Demo/JSON Demo/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// JSON Demo
//
// Created by Van Huy on 12/3/15.
// Copyright (c) 2015 Example. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let urlPath = "http://api.openweathermap.org/data/2.5/weather?q=Tokyo,jp&appid=2de143494c0b295cca9337e1e96b00e0"
let url = NSURL(string: urlPath)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in
if error != nil {
println(error)
} else {
let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary
println(jsonResult["weather"])
}
})
task.resume()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
6b690ea7a74e007d89ce0f486bc13d4e
| 27.52381 | 155 | 0.611853 | false | false | false | false |
orta/SignalKit
|
refs/heads/master
|
SignalKit/Observables/ObservableProperty.swift
|
mit
|
1
|
//
// ObservableProperty.swift
// SignalKit
//
// Created by Yanko Dimitrov on 8/12/15.
// Copyright © 2015 Yanko Dimitrov. All rights reserved.
//
import Foundation
public final class ObservableProperty<T>: Observable {
public typealias Item = T
private var internalValue: Item
private let lock: LockType
public let dispatcher: Dispatcher<Item>
public var value: Item {
get {
lock.lock()
let theValue = internalValue
lock.unlock()
return theValue
}
set {
lock.lock()
internalValue = newValue
lock.unlock()
dispatcher.dispatch(newValue)
}
}
public init(value: Item, lock: LockType) {
self.internalValue = value
self.lock = lock
self.dispatcher = Dispatcher<Item>(lock: lock)
}
public convenience init(_ value: Item) {
self.init(value: value, lock: SpinLock())
}
public func dispatch(item: Item) {
value = item
}
}
public extension ObservableProperty {
/**
Observe the observable property for value changes
*/
public func observe() -> Signal<Item> {
let signal = Signal<Item>(lock: SpinLock())
signal.observe(self)
return signal
}
}
|
ffac2a4a60b79c6da161ab0a24fc3888
| 19.926471 | 57 | 0.541813 | false | false | false | false |
depl0y/pixelbits
|
refs/heads/develop
|
pixelbits/Other/Swizzling.swift
|
mit
|
1
|
//
// Swizzling.swift
// pixelbits
//
// Created by Wim Haanstra on 19/01/16.
// Copyright © 2016 Wim Haanstra. All rights reserved.
//
internal class Swizzling {
internal static func setup() {
Swizzling.swizzle(UIView.self, originalSelector: #selector(UIView.setNeedsDisplay), swizzledClass: UIView.self, swizzledSelector:
#selector(UIView.pixelbitsSetNeedsDisplay))
}
private static func swizzle(originalClass: AnyClass!, originalSelector: Selector, swizzledClass: AnyClass!, swizzledSelector: Selector) {
let method: Method = class_getInstanceMethod(originalClass, originalSelector)
let swizzledMethod: Method = class_getInstanceMethod(swizzledClass, swizzledSelector)
if method != nil && swizzledMethod != nil {
Log.debug("SWIZZLE: \(originalClass).\(originalSelector) => \(swizzledClass).\(swizzledSelector)")
method_exchangeImplementations(method, swizzledMethod)
}
}
}
|
786fc375d941eff45d327dc8caa0c9fb
| 31.714286 | 138 | 0.752183 | false | false | false | false |
wireapp/wire-ios
|
refs/heads/develop
|
Wire-iOS/Sources/UserInterface/Components/Views/UserCellSubtitleProtocol.swift
|
gpl-3.0
|
1
|
//
// Wire
// Copyright (C) 2018 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 WireDataModel
import WireCommonComponents
protocol UserCellSubtitleProtocol: AnyObject {
func subtitle(forRegularUser user: UserType?) -> NSAttributedString?
static var correlationFormatters: [ColorSchemeVariant: AddressBookCorrelationFormatter] { get set }
static var boldFont: FontSpec { get }
static var lightFont: FontSpec { get }
}
extension UserCellSubtitleProtocol where Self: UIView & Themeable {
func subtitle(forRegularUser user: UserType?) -> NSAttributedString? {
guard let user = user else { return nil }
var components: [NSAttributedString?] = []
if let handle = user.handleDisplayString(withDomain: user.isFederated), !handle.isEmpty {
components.append(handle && UserCell.boldFont.font!)
}
WirelessExpirationTimeFormatter.shared.string(for: user).apply {
components.append($0 && UserCell.boldFont.font!)
}
if let user = user as? ZMUser, let addressBookName = user.addressBookEntry?.cachedName {
let formatter = Self.correlationFormatter(for: colorSchemeVariant)
components.append(formatter.correlationText(for: user, addressBookName: addressBookName))
}
return components.compactMap({ $0 }).joined(separator: " " + String.MessageToolbox.middleDot + " " && UserCell.lightFont.font!)
}
private static func correlationFormatter(for colorSchemeVariant: ColorSchemeVariant) -> AddressBookCorrelationFormatter {
if let formatter = correlationFormatters[colorSchemeVariant] {
return formatter
}
let color = UIColor.from(scheme: .sectionText, variant: colorSchemeVariant)
let formatter = AddressBookCorrelationFormatter(lightFont: lightFont, boldFont: boldFont, color: color)
correlationFormatters[colorSchemeVariant] = formatter
return formatter
}
}
|
4673b1180bded145991cf239aaf41b37
| 37.925373 | 135 | 0.719709 | false | false | false | false |
vimeo/VimeoNetworking
|
refs/heads/develop
|
Sources/Shared/Core/SessionManaging.swift
|
mit
|
1
|
//
// VimeoSessionManaging.swift
// VimeoNetworking
//
// Created by Rogerio de Paula Assis on 9/5/19.
// Copyright © 2019 Vimeo. All rights reserved.
//
import Foundation
public struct SessionManagingResult<T> {
public let request: URLRequest?
public let response: URLResponse?
public let result: Result<T, Error>
init(request: URLRequest? = nil, response: URLResponse? = nil, result: Result<T, Error>) {
self.request = request
self.response = response
self.result = result
}
}
/// A type that can perform asynchronous requests from a
/// URLRequestConvertible parameter and a response callback.
public protocol SessionManaging: AuthenticationListener {
/// Used to invalidate the session manager, and optionally cancel any pending tasks
func invalidate(cancelingPendingTasks cancelPendingTasks: Bool)
/// The various methods below create asynchronous operations described by the
/// requestConvertible object, and return a corresponding task that can be used to identify and
/// control the lifecycle of the request.
/// The callback provided will be executed once the operation completes. It will include
/// the result object along with the originating request and corresponding response objects.
// Data request
func request(
_ requestConvertible: URLRequestConvertible,
parameters: Any?,
then callback: @escaping (SessionManagingResult<Data>) -> Void
) -> Task?
// JSON request
func request(
_ requestConvertible: URLRequestConvertible,
parameters: Any?,
then callback: @escaping (SessionManagingResult<JSON>) -> Void
) -> Task?
// Decodable request
func request<T: Decodable>(
_ requestConvertible: URLRequestConvertible,
parameters: Any?,
then callback: @escaping (SessionManagingResult<T>) -> Void
) -> Task?
// Download request
func download(
_ requestConvertible: URLRequestConvertible,
destinationURL: URL?,
then callback: @escaping (SessionManagingResult<URL>) -> Void
) -> Task?
// Upload request
func upload(
_ requestConvertible: URLRequestConvertible,
sourceFile: URL,
then callback: @escaping (SessionManagingResult<JSON>) -> Void
) -> Task?
}
|
b0fb92c3164de7fa907632d147558872
| 31.929577 | 99 | 0.685201 | false | false | false | false |
eno314/MyTopics
|
refs/heads/develop
|
MyTopics/AppDelegate.swift
|
mit
|
1
|
//
// AppDelegate.swift
// MyTopics
//
// Created by hiroto kitamur on 2014/11/15.
// Copyright (c) 2014年 eno. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let navigationController = self.window!.rootViewController as UINavigationController
let controller = navigationController.topViewController as MasterViewController
controller.managedObjectContext = self.managedObjectContext
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "jp.eno.MyTopics" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("MyTopics", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("MyTopics.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
let dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
|
7233a0250be474cec065f824226ade83
| 54.824561 | 290 | 0.719516 | false | false | false | false |
kentya6/Fuwari
|
refs/heads/master
|
Fuwari/FloatWindow.swift
|
mit
|
1
|
//
// FloatWindow.swift
// Fuwari
//
// Created by Kengo Yokoyama on 2016/12/07.
// Copyright © 2016年 AppKnop. All rights reserved.
//
import Cocoa
import Magnet
import Sauce
import Carbon
protocol FloatDelegate: AnyObject {
func save(floatWindow: FloatWindow, image: CGImage)
func close(floatWindow: FloatWindow)
}
class FloatWindow: NSWindow {
override var canBecomeKey: Bool { return true }
override var canBecomeMain: Bool { return true }
weak var floatDelegate: FloatDelegate? = nil
private var closeButton: NSButton!
private var spaceButton: NSButton!
private var allSpaceMenuItem: NSMenuItem!
private var currentSpaceMenuItem: NSMenuItem!
private var originalRect = NSRect()
private var popUpLabel = NSTextField()
private var windowScale = CGFloat(1.0)
private var windowOpacity = CGFloat(1.0)
private var spaceMode = SpaceMode.all {
didSet {
collectionBehavior = spaceMode.getCollectionBehavior()
if spaceMode == .all {
allSpaceMenuItem.state = .on
currentSpaceMenuItem.state = .off
NSAnimationContext.runAnimationGroup({ context in
context.duration = self.buttonOpacityDuration
self.spaceButton.animator().alphaValue = 0.0
}, completionHandler: {
self.spaceButton.image = NSImage(named: "SpaceAll")
NSAnimationContext.runAnimationGroup({ context in
context.duration = self.buttonOpacityDuration
self.spaceButton.animator().alphaValue = self.buttonOpacity
})
})
} else {
allSpaceMenuItem.state = .off
currentSpaceMenuItem.state = .on
NSAnimationContext.runAnimationGroup({ context in
context.duration = self.buttonOpacityDuration
self.spaceButton.animator().alphaValue = 0.0
}, completionHandler: {
self.spaceButton.image = NSImage(named: "SpaceCurrent")
NSAnimationContext.runAnimationGroup({ context in
context.duration = self.buttonOpacityDuration
self.spaceButton.animator().alphaValue = self.buttonOpacity
})
})
}
}
}
private let defaults = UserDefaults.standard
private let windowScaleInterval = CGFloat(0.25)
private let minWindowScale = CGFloat(0.25)
private let maxWindowScale = CGFloat(2.5)
private let buttonOpacity = CGFloat(0.5)
private let buttonOpacityDuration = TimeInterval(0.3)
init(contentRect: NSRect, styleMask style: NSWindow.StyleMask = [.borderless, .resizable], backing bufferingType: NSWindow.BackingStoreType = .buffered, defer flag: Bool = false, image: CGImage, spaceMode: SpaceMode) {
super.init(contentRect: contentRect, styleMask: style, backing: bufferingType, defer: flag)
contentView = FloatView(frame: contentRect)
originalRect = contentRect
self.spaceMode = spaceMode
collectionBehavior = spaceMode.getCollectionBehavior()
level = .floating
isMovableByWindowBackground = true
hasShadow = true
contentView?.wantsLayer = true
contentView?.layer?.contents = image
minSize = NSMakeSize(30, 30)
animationBehavior = NSWindow.AnimationBehavior.alertPanel
popUpLabel = NSTextField(frame: NSRect(x: 10, y: 10, width: 120, height: 26))
popUpLabel.textColor = .white
popUpLabel.font = NSFont.boldSystemFont(ofSize: 20)
popUpLabel.alignment = .center
popUpLabel.drawsBackground = true
popUpLabel.backgroundColor = NSColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.4)
popUpLabel.wantsLayer = true
popUpLabel.layer?.cornerRadius = 10.0
popUpLabel.isBordered = false
popUpLabel.isEditable = false
popUpLabel.isSelectable = false
popUpLabel.alphaValue = 0.0
contentView?.addSubview(popUpLabel)
if let image = NSImage(named: "Close") {
closeButton = NSButton(frame: NSRect(x: 4, y: frame.height - 20, width: 16, height: 16))
closeButton.image = image
closeButton.imageScaling = .scaleProportionallyDown
closeButton.isBordered = false
closeButton.alphaValue = 0.0
closeButton.target = self
closeButton.action = #selector(closeWindow)
contentView?.addSubview(closeButton)
}
if let image = NSImage(named: spaceMode == .all ? "SpaceAll" : "SpaceCurrent") {
spaceButton = NSButton(frame: NSRect(x: frame.width - 20, y: frame.height - 20, width: 16, height: 16))
spaceButton.image = image
spaceButton.imageScaling = .scaleProportionallyDown
spaceButton.isBordered = false
spaceButton.alphaValue = 0.0
spaceButton.target = self
spaceButton.action = #selector(changeSpaceMode)
contentView?.addSubview(spaceButton)
}
allSpaceMenuItem = NSMenuItem(title: LocalizedString.ShowAllSpaces.value, action: #selector(changeSpaceModeAll), keyEquivalent: "k")
currentSpaceMenuItem = NSMenuItem(title: LocalizedString.ShowCurrentSpace.value, action: #selector(changeSpaceModeCurrent), keyEquivalent: "l")
allSpaceMenuItem.state = spaceMode == .all ? .on : .off
currentSpaceMenuItem.state = spaceMode == .all ? .off : .on
menu = NSMenu()
menu?.addItem(NSMenuItem(title: LocalizedString.Copy.value, action: #selector(copyImage), keyEquivalent: "c"))
menu?.addItem(NSMenuItem.separator())
menu?.addItem(NSMenuItem(title: LocalizedString.Save.value, action: #selector(saveImage), keyEquivalent: "s"))
menu?.addItem(NSMenuItem.separator())
menu?.addItem(NSMenuItem(title: LocalizedString.Upload.value, action: #selector(uploadImage), keyEquivalent: ""))
menu?.addItem(NSMenuItem.separator())
menu?.addItem(NSMenuItem(title: LocalizedString.ZoomReset.value, action: #selector(resetWindowScale), keyEquivalent: "r"))
menu?.addItem(NSMenuItem(title: LocalizedString.ResetWindow.value, action: #selector(resetWindow), keyEquivalent: "0"))
menu?.addItem(NSMenuItem(title: LocalizedString.ZoomIn.value, action: #selector(zoomInWindow), keyEquivalent: "+"))
menu?.addItem(NSMenuItem(title: LocalizedString.ZoomOut.value, action: #selector(zoomOutWindow), keyEquivalent: "-"))
menu?.addItem(allSpaceMenuItem)
menu?.addItem(currentSpaceMenuItem)
menu?.addItem(NSMenuItem.separator())
menu?.addItem(NSMenuItem(title: LocalizedString.Close.value, action: #selector(closeWindow), keyEquivalent: "w"))
fadeWindow(isIn: true)
}
func windowDidResize(_ notification: Notification) {
windowScale = frame.width > frame.height ? frame.height / originalRect.height : frame.width / originalRect.width
closeButton.frame = NSRect(x: 4, y: frame.height - 20, width: 16, height: 16)
spaceButton.frame = NSRect(x: frame.width - 20, y: frame.height - 20, width: 16, height: 16)
showPopUp(text: "\(Int(windowScale * 100))%")
}
override func keyDown(with event: NSEvent) {
guard let key = Sauce.shared.key(for: Int(event.keyCode)) else { return }
var moveOffset = (dx: 0.0, dy: 0.0)
switch key {
case .leftArrow:
moveOffset = (dx: -1, dy: 0)
case .rightArrow:
moveOffset = (dx: 1, dy: 0)
case .upArrow:
moveOffset = (dx: 0, dy: 1)
case .downArrow:
moveOffset = (dx: 0, dy: -1)
case .escape:
closeWindow()
default:
break
}
if event.modifierFlags.rawValue & NSEvent.ModifierFlags.shift.rawValue != 0 {
moveOffset = (moveOffset.dx * 10, moveOffset.dy * 10)
}
if moveOffset.dx != 0.0 || moveOffset.dy != 0.0 {
guard let screen = screen else { return }
// clamp offset
if frame.origin.x + moveOffset.dx < screen.frame.origin.x - (frame.width / 2) || (screen.frame.origin.x + screen.frame.width) - (frame.width / 2) < frame.origin.x + moveOffset.dx {
moveOffset.dx = 0
}
if frame.origin.y + moveOffset.dy < screen.frame.origin.y - (frame.height / 2) || (screen.frame.origin.y + screen.frame.height) - (frame.height / 2) < frame.origin.y + moveOffset.dy {
moveOffset.dy = 0
}
moveWindow(dx: moveOffset.dx, dy: moveOffset.dy)
}
if event.modifierFlags.rawValue & NSEvent.ModifierFlags.command.rawValue != 0 {
switch key {
case .s:
saveImage()
case .c:
copyImage()
case .k:
changeSpaceModeAll()
case .l:
changeSpaceModeCurrent()
case .zero, .keypadZero:
resetWindow()
case .one, .keypadOne:
resetWindowScale()
case .equal, .six, .semicolon, .keypadPlus:
zoomInWindow()
case .minus, .keypadMinus:
zoomOutWindow()
case .w:
closeWindow()
default:
break
}
}
}
override func rightMouseDown(with event: NSEvent) {
if let menu = menu, let contentView = contentView {
NSMenu.popUpContextMenu(menu, with: event, for: contentView)
}
}
override func mouseEntered(with event: NSEvent) {
NSAnimationContext.runAnimationGroup { context in
context.duration = self.buttonOpacityDuration
self.closeButton.animator().alphaValue = self.buttonOpacity
self.spaceButton.animator().alphaValue = self.buttonOpacity
}
}
override func mouseExited(with event: NSEvent) {
NSAnimationContext.runAnimationGroup { context in
context.duration = self.buttonOpacityDuration
self.closeButton.animator().alphaValue = 0.0
self.spaceButton.animator().alphaValue = 0.0
}
}
override func scrollWheel(with event: NSEvent) {
let min = CGFloat(0.1), max = CGFloat(1.0)
if windowOpacity > min || windowOpacity < max {
windowOpacity += event.deltaY * 0.005
if windowOpacity < min { windowOpacity = min }
else if windowOpacity > max { windowOpacity = max }
alphaValue = windowOpacity
}
}
override func performClose(_ sender: Any?) {
closeWindow()
}
override func mouseDown(with event: NSEvent) {
let movingOpacity = defaults.float(forKey: Constants.UserDefaults.movingOpacity)
if movingOpacity < 1 {
alphaValue = CGFloat(movingOpacity)
}
closeButton.alphaValue = 0.0
spaceButton.alphaValue = 0.0
}
override func mouseUp(with event: NSEvent) {
alphaValue = windowOpacity
closeButton.alphaValue = buttonOpacity
spaceButton.alphaValue = buttonOpacity
// Double click to close
if event.clickCount >= 2 {
closeWindow()
}
}
@objc private func saveImage() {
DispatchQueue.main.asyncAfter(deadline: .now()) {
if let image = self.contentView?.layer?.contents {
self.showPopUp(text: "Save")
self.floatDelegate?.save(floatWindow: self, image: image as! CGImage)
}
}
}
@objc private func copyImage() {
DispatchQueue.main.asyncAfter(deadline: .now()) {
if let image = self.contentView?.layer?.contents {
let cgImage = image as! CGImage
let size = CGSize(width: cgImage.width, height: cgImage.height)
let nsImage = NSImage(cgImage: cgImage, size: size)
NSPasteboard.general.clearContents()
NSPasteboard.general.writeObjects([nsImage])
self.showPopUp(text: "Copy")
}
}
}
@objc private func uploadImage() {
DispatchQueue.main.asyncAfter(deadline: .now()) {
if let image = self.contentView?.layer?.contents {
let cgImage = image as! CGImage
let size = CGSize(width: cgImage.width, height: cgImage.height)
let nsImage = NSImage(cgImage: cgImage, size: size)
GyazoManager.shared.uploadImage(image: nsImage)
}
}
}
@objc private func zoomInWindow() {
let scale = floor((windowScale + windowScaleInterval) * 100) / 100
if scale <= maxWindowScale {
windowScale = scale
setFrame(NSRect(x: frame.origin.x - (originalRect.width / 2 * windowScaleInterval), y: frame.origin.y - (originalRect.height / 2 * windowScaleInterval), width: originalRect.width * windowScale, height: originalRect.height * windowScale), display: true, animate: true)
}
showPopUp(text: "\(Int(windowScale * 100))%")
}
@objc private func zoomOutWindow() {
let scale = floor((windowScale - windowScaleInterval) * 100) / 100
if scale >= minWindowScale {
windowScale = scale
setFrame(NSRect(x: frame.origin.x + (originalRect.width / 2 * windowScaleInterval), y: frame.origin.y + (originalRect.height / 2 * windowScaleInterval), width: originalRect.width * windowScale, height: originalRect.height * windowScale), display: true, animate: true)
}
showPopUp(text: "\(Int(windowScale * 100))%")
}
@objc private func moveWindow(dx: CGFloat, dy: CGFloat) {
setFrame(NSRect(x: frame.origin.x + dx, y: frame.origin.y + dy, width: frame.width, height: frame.height), display: true, animate: true)
showPopUp(text: "(\(Int(frame.origin.x)),\(Int(frame.origin.y)))")
}
@objc private func resetWindowScale() {
let diffScale = 1.0 - windowScale
windowScale = CGFloat(1.0)
setFrame(NSRect(x: frame.origin.x - (originalRect.width * diffScale / 2), y: frame.origin.y - (originalRect.height * diffScale / 2), width: originalRect.width * windowScale, height: originalRect.height * windowScale), display: true, animate: true)
showPopUp(text: "\(Int(windowScale * 100))%")
}
@objc private func resetWindow() {
windowScale = CGFloat(1.0)
setFrame(originalRect, display: true, animate: true)
}
@objc private func changeSpaceModeAll() {
spaceMode = .all
}
@objc private func changeSpaceModeCurrent() {
spaceMode = .current
}
@objc private func changeSpaceMode() {
spaceMode = spaceMode == .all ? .current : .all
}
@objc private func closeWindow() {
floatDelegate?.close(floatWindow: self)
}
private func showPopUp(text: String, duration: Double = 0.5, interval: Double = 0.5) {
popUpLabel.stringValue = text
NSAnimationContext.runAnimationGroup({ context in
context.duration = duration
context.timingFunction = CAMediaTimingFunction(name: .easeOut)
popUpLabel.animator().alphaValue = 1.0
}) {
DispatchQueue.main.asyncAfter(deadline: .now() + interval) {
NSAnimationContext.runAnimationGroup({ context in
context.duration = duration
context.timingFunction = CAMediaTimingFunction(name: .easeIn)
self.popUpLabel.animator().alphaValue = 0.0
})
}
}
}
internal override func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
if menuItem.action == #selector(resetWindowScale) {
return windowScale != CGFloat(1.0)
}
return true
}
func fadeWindow(isIn: Bool, completion: (() -> Void)? = nil) {
makeKeyAndOrderFront(self)
NSAnimationContext.runAnimationGroup({ context in
context.duration = 0.2
animator().alphaValue = isIn ? 1.0 : 0.0
}, completionHandler: { [weak self] in
if !isIn {
self?.orderOut(self)
}
completion?()
})
}
}
|
1768735dfe4290349edc5853b58fe6e0
| 40.861809 | 279 | 0.603385 | false | false | false | false |
See-Ku/SK4Toolkit
|
refs/heads/master
|
SK4Toolkit/extention/SK4UIPopoverPresentationControllerExtension.swift
|
mit
|
1
|
//
// SK4UIPopoverPresentationControllerExtension.swift
// SK4Toolkit
//
// Created by See.Ku on 2016/06/10.
// Copyright (c) 2016 AxeRoad. All rights reserved.
//
import UIKit
extension UIPopoverPresentationController {
/// 表示する位置を指定
public func sk4SetSourceItem(item: AnyObject) {
// UIBarButtonItemか?
if let bar = item as? UIBarButtonItem {
barButtonItem = bar
return
}
// UIViewか?
if let view = item as? UIView {
sk4SetSourceView(view)
return
}
}
/// 表示する位置を指定 ※矢印の向きは自動で判定
public func sk4SetSourceView(view: UIView) {
sourceView = view
sourceRect.size = CGSize()
sourceRect.origin.x = view.bounds.midX
sourceRect.origin.y = view.bounds.midY
guard let sv = view.superview else { return }
let pos = view.center
let base = sv.bounds
if pos.y < base.height / 3 {
sourceRect.origin.y = view.bounds.maxY
permittedArrowDirections = .Up
} else if pos.y > (base.height * 2) / 3 {
sourceRect.origin.y = 0
permittedArrowDirections = .Down
} else if pos.x < base.width / 3 {
sourceRect.origin.x = view.bounds.maxX
permittedArrowDirections = .Left
} else if pos.x > (base.width * 2) / 3 {
sourceRect.origin.x = 0
permittedArrowDirections = .Right
} else {
sourceRect.origin.y = view.bounds.maxY
permittedArrowDirections = .Up
}
}
}
// eof
|
eee76e9c2100ca219726c3dca7e29ab4
| 19.569231 | 53 | 0.67988 | false | false | false | false |
Ossey/WUO-iOS
|
refs/heads/master
|
WUO/WUO/Classes/DetailPages/TrendDetail/XYTrendDetaileSelectView.swift
|
apache-2.0
|
1
|
//
// XYTrendDetaileSelectView.swift
// WUO
//
// Created by mofeini on 17/1/20.
// Copyright © 2017年 com.test.demo. All rights reserved.
//
import UIKit
class XYTrendDetaileSelectView: UITableViewHeaderFooterView {
lazy var labelView : XYTrendDetailLabelView = {
let labelView = XYTrendDetailLabelView.init(frame: CGRect.init(x: 0, y: 0, width: SCREENT_W(), height: SIZE_TREND_DETAIL_SELECTVIEW_H), delegate: nil, channelCates: nil, rightBtnWidth: 0)
labelView.itemNameKey = "labelName"
labelView.itemImageNameKey = "labelEname"
return labelView
}()
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
contentView.addSubview(labelView)
// 这句代码,尽然引发labelView不能响应事件,肯定是frame不正确导致的,郁闷了
// labelView.frame = contentView.bounds
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
6d2f2bdc029d60f437a6ab0826bff06a
| 28.878788 | 195 | 0.677485 | false | false | false | false |
cloudconvert/cloudconvert-swift
|
refs/heads/master
|
CloudConvert/CloudConvert.swift
|
mit
|
1
|
//
// CloudConvert.swift
//
// Copyright (c) 2015 CloudConvert (https://cloudconvert.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//
// Created by Josias Montag on 03.04.15.
//
import Foundation
import Alamofire
public let apiProtocol = "https"
public let apiHost = "api.cloudconvert.com"
public var apiKey: String = "" {
didSet {
// reset manager instance because we need a new auth header
managerInstance = nil;
}
}
public let errorDomain = "com.cloudconvert.error"
// MARK: - Request
private var managerInstance: Alamofire.SessionManager?
private var manager: Alamofire.SessionManager {
if (managerInstance != nil) {
return managerInstance!
}
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = [
"Authorization": "Bearer " + apiKey
]
managerInstance = SessionManager(configuration: configuration)
return managerInstance!
}
/**
*/
private func stringURL(for endpoint: String) -> String {
var url = endpoint
if url.hasPrefix("//") {
url = apiProtocol + ":" + url;
} else if !url.hasPrefix("http") {
url = apiProtocol + "://" + apiHost + url;
}
return url
}
/**
Wrapper for Alamofire.request()
:param: url The URL String, can be relative to api Host
:param: method HTTP Method (.GET, .POST...)
:param: parameters Dictionary of Query String (GET) or JSON Body (POST) parameters
:returns: Alamofire.Request
*/
public func req(url: String, method: Alamofire.HTTPMethod, parameters: Parameters? = nil) -> Alamofire.DataRequest {
var encoding: Alamofire.ParameterEncoding = URLEncoding()
if method == .post {
encoding = JSONEncoding()
}
let strURL = stringURL(for: url)
let request = manager.request(strURL, method: method, parameters: parameters, encoding: encoding)
return request
}
/**
Wrapper for Alamofire.upload()
:param: url The URL String, can be relative to api Host
:param: file The URL to the local file to upload
:returns: Alamofire.Request
*/
public func ccUpload(url: String, file: URL) -> Alamofire.UploadRequest {
let strURL = stringURL(for: url)
let request = manager.upload(file, to: strURL, method: .put)
return request
}
/**
Wrapper for Alamofire.download()
:param: url The URL String, can be relative to api Host
:param: parameters Dictionary of Query String parameters
:param: destination Closure to generate the destination NSURL
:returns: Alamofire.Request
*/
public func ccDownload(url: String, parameters: Parameters? = nil, destination: @escaping Alamofire.DownloadRequest.DownloadFileDestination) -> Alamofire.DownloadRequest {
let strURL = stringURL(for: url)
let request = manager.download(strURL, method: .get, parameters: parameters, to: destination)
return request
}
// MARK: - Process
public protocol ProcessDelegate {
/**
Monitor conversion progress
:param: process The CloudConvert.Process
:param: step Current step of the process; see https://cloudconvert.com/apidoc#status
:param: percent Percentage (0-100) of the current step as Float value
:param: message Description of the current progress
*/
func conversionProgress(process: Process, step: String?, percent: CGFloat?, message: String?)
/**
Conversion completed on server side. This happens before the output file was downloaded!
:param: process The CloudConvert.Process
:param: error Error object if the conversion failed
*/
func conversionCompleted(process: Process?, error: Error?)
/**
Conversion output file was downloaded to local path
:param: process The CloudConvert.Process
:param: path URL of the downloaded output file
*/
func conversionFileDownloaded(process: Process?, path: URL)
}
public class Process: NSObject {
public var delegate: ProcessDelegate? = nil
public var url: String?
private var data: [String: Any]? = [:] {
didSet {
if let url = data?["url"] as? String {
self.url = url
}
}
}
private var currentRequest: Alamofire.Request? = nil
private var waitCompletionHandler: ((Error?) -> Void)? = nil
fileprivate var progressHandler: ((_ step: String?, _ percent: CGFloat?, _ message: String?) -> Void)? = nil
private var refreshTimer: Timer? = nil
subscript(name: String) -> Any? {
return data?[name]
}
override init() { }
init(url: String) {
self.url = url
}
/**
Create Process on the CloudConvert API
:param: parameters Dictionary of parameters. See: https://cloudconvert.com/apidoc#create
:param: completionHandler The code to be executed once the request has finished.
:returns: CloudConvert.Process
*/
public func create(parameters: [String: Any], completionHandler: @escaping (Error?) -> Void) -> Self {
var parameters = parameters
parameters.removeValue(forKey: "file")
parameters.removeValue(forKey: "download")
req(url: "/process", method: .post, parameters: parameters).responseJSON { (response: DataResponse<Any>) in
if let error = response.error {
completionHandler(error)
} else if let dict = response.value as? [String : Any],
let url = dict["url"] as? String {
self.url = url
completionHandler(nil)
} else {
completionHandler(NSError(domain: errorDomain, code: -1, userInfo: nil))
}
}
return self
}
/**
Refresh process data from API
:param: parameters Dictionary of Query String parameters
:param: completionHandler The code to be executed once the request has finished.
:returns: CloudConvert.Process
*/
public func refresh(parameters: Parameters? = nil, completionHandler: ((Error?) -> Void)? = nil) -> Self {
if currentRequest != nil {
// if there is a active refresh request, cancel it
self.currentRequest?.cancel()
}
guard let url = url else {
completionHandler?(NSError(domain: errorDomain, code: -1, userInfo: ["localizedDescription" : "No Process URL!"] ))
return self
}
currentRequest = req(url: url, method: .get, parameters: parameters).responseJSON { [weak self] response in
self?.currentRequest = nil
let currentValue = response.value as? [String : Any]
if let error = response.error {
completionHandler?(error)
} else if let value = currentValue {
self?.data = value
completionHandler?(nil)
}
self?.progressHandler?(currentValue?["step"] as? String, currentValue?["percent"] as? CGFloat, currentValue?["message"] as? String)
if let strongSelf = self {
strongSelf.delegate?.conversionProgress(process: strongSelf, step: currentValue?["step"] as? String, percent: currentValue?["percent"] as? CGFloat, message: currentValue?["message"] as? String)
}
if response.error != nil || (currentValue?["step"] as? String) == "finished" {
// Conversion finished
DispatchQueue.main.async {
self?.refreshTimer?.invalidate()
self?.refreshTimer = nil
}
self?.waitCompletionHandler?(response.error)
self?.waitCompletionHandler = nil
self?.delegate?.conversionCompleted(process: self, error: response.error)
}
}
return self
}
/**
Starts the conversion on the CloudConvert API
:param: parameters Dictionary of parameters. See: https://cloudconvert.com/apidoc#start
:param: completionHandler The code to be executed once the request has finished.
:returns: CloudConvert.Process
*/
public func start(parameters: Parameters? = nil, completionHandler: ((Error?) -> Void)? = nil) -> Self {
guard let url = url else {
completionHandler?(NSError(domain: errorDomain, code: -1, userInfo: ["localizedDescription" : "No Process URL!"] ))
return self
}
var parameters = parameters
let file: URL? = parameters?["file"] as? URL
parameters?.removeValue(forKey: "download")
if let file = file {
parameters?["file"] = file.absoluteString
}
currentRequest = req(url: url, method: .post, parameters: parameters).responseJSON { [weak self] response in
self?.currentRequest = nil
let currentValue = response.value as? [String : Any]
if let error = response.error {
completionHandler?(error)
} else {
self?.data = currentValue
if let file = file, (parameters?["input"] as? String) == "upload" {
// Upload
_ = self?.upload(uploadPath: file, completionHandler: completionHandler)
} else {
completionHandler?(nil)
}
}
}
return self
}
/**
Uploads an input file to the CloudConvert API
:param: uploadPath Local path of the input file.
:param: completionHandler The code to be executed once the upload has finished.
:returns: CloudConvert.Process
*/
public func upload(uploadPath: URL, completionHandler: ((Error?) -> Void)?) -> Self {
if let upload = self.data?["upload"] as? [String: String], var url = upload["url"] {
url += "/" + uploadPath.lastPathComponent
let formatter = ByteCountFormatter()
formatter.allowsNonnumericFormatting = false
currentRequest = ccUpload(url: url, file: uploadPath).uploadProgress(closure: { [weak self] progress in
let totalBytesExpectedToSend = progress.totalUnitCount
let totalBytesSent = progress.completedUnitCount
let percent = CGFloat(totalBytesSent) / CGFloat(totalBytesExpectedToSend)
let message = "Uploading (" + formatter.string(fromByteCount: totalBytesSent) + " / " + formatter.string(fromByteCount: totalBytesExpectedToSend) + ") ..."
if let strongSelf = self {
strongSelf.delegate?.conversionProgress(process: strongSelf, step: "upload", percent: percent, message: message)
strongSelf.progressHandler?("upload", percent, message)
}
}).responseJSON(completionHandler: { (response) in
if let error = response.error {
completionHandler?(error)
} else {
completionHandler?(nil)
}
})
} else {
completionHandler?(NSError(domain: errorDomain, code: -1, userInfo: ["localizedDescription" : "File cannot be uploaded in this process state!"] ))
}
return self
}
/**
Downloads the output file from the CloudConvert API
:param: downloadPath Local path for downloading the output file.
If set to nil a temporary location will be choosen.
Can be set to a directory or a file. Any existing file will be overwritten.
:param: completionHandler The code to be executed once the download has finished.
:returns: CloudConvert.Process
*/
public func download(downloadPath: URL? = nil, completionHandler: ((URL?, Error?) -> Void)?) -> Self {
var downloadPath = downloadPath
if let output = self.data?["output"] as? [String: Any], let url = output["url"] as? String {
let formatter = ByteCountFormatter()
formatter.allowsNonnumericFormatting = false
let destination: DownloadRequest.DownloadFileDestination = { (temporaryURL, response) in
if let downloadName = response.suggestedFilename {
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
downloadPath = documentsURL.appendingPathComponent(downloadName)
return (downloadPath!, [.removePreviousFile, .createIntermediateDirectories])
} else {
return (temporaryURL, [.removePreviousFile, .createIntermediateDirectories])
}
}
currentRequest = ccDownload(url: url, destination: destination).downloadProgress(closure: { [weak self] progress in
let totalBytesExpectedToSend = progress.totalUnitCount
let totalBytesSent = progress.completedUnitCount
let percent = CGFloat(totalBytesSent) / CGFloat(totalBytesExpectedToSend)
let message = "Uploading (" + formatter.string(fromByteCount: totalBytesSent) + " / " + formatter.string(fromByteCount: totalBytesExpectedToSend) + ") ..."
if let strongSelf = self {
strongSelf.delegate?.conversionProgress(process: strongSelf, step: "download", percent: percent, message: message)
strongSelf.progressHandler?("download", percent, message)
}
}).response(completionHandler: { [weak self] response in
if let strongSelf = self {
strongSelf.delegate?.conversionProgress(process: strongSelf, step: "finished", percent: 100, message: "Conversion finished!")
}
self?.progressHandler?("finished", 100, "Conversion finished!")
completionHandler?(downloadPath, response.error)
if let downloadPath = downloadPath {
self?.delegate?.conversionFileDownloaded(process: self, path: downloadPath)
}
})
} else {
completionHandler?(nil, NSError(domain: errorDomain, code: -1, userInfo: ["localizedDescription" : "Output file not yet available!"] ))
}
return self
}
/**
Waits until the conversion has finished
:param: completionHandler The code to be executed once the conversion has finished.
:returns: CloudConvert.Process
*/
public func wait(completionHandler: ((Error?) -> Void)?) -> Self {
self.waitCompletionHandler = completionHandler
DispatchQueue.main.async {
self.refreshTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(Process.refreshTimerTick), userInfo: nil, repeats: true)
}
return self
}
@objc public func refreshTimerTick() {
_ = self.refresh()
}
/**
Cancels the conversion, including any running upload or download.
Also deletes the process from the CloudConvert API.
:returns: CloudConvert.Process
*/
@discardableResult
public func cancel() -> Self {
self.currentRequest?.cancel()
self.currentRequest = nil;
DispatchQueue.main.async {
self.refreshTimer?.invalidate()
self.refreshTimer = nil
}
if let url = self.url {
_ = req(url: url, method: .delete, parameters: nil)
}
return self
}
// Printable
public override var description: String {
return "Process " + (self.url ?? "") + " " + ( data?.description ?? "")
}
}
// MARK: - Methods
/**
Converts a file using the CloudConvert API.
:param: parameters Parameters for the conversion.
Can be generated using the API Console: https://cloudconvert.com/apiconsole
:param: progressHandler Can be used to monitor the progress of the conversion.
Parameters of the Handler:
step: Current step of the process; see https://cloudconvert.com/apidoc#status ;
percent: Percentage (0-100) of the current step as Float value;
message: Description of the current progress
:param: completionHandler The code to be executed once the conversion has finished.
Parameters of the Handler:
path: local NSURL of the downloaded output file;
error: Error if the conversion failed
:returns: A CloudConvert.Porcess object, which can be used to cancel the conversion.
*/
public func convert(parameters: [String: Any], progressHandler: ((_ step: String?, _ percent: CGFloat?, _ message: String?) -> Void)? = nil, completionHandler: ((URL?, Error?) -> Void)? = nil) -> Process {
var process = Process()
process.progressHandler = progressHandler
process = process.create(parameters: parameters) { error in
if let error = error {
completionHandler?(nil, error)
} else {
process = process.start(parameters: parameters) { error in
if let error = error {
completionHandler?(nil, error)
} else {
process = process.wait { error in
if let error = error {
completionHandler?(nil, error)
} else {
if let download = parameters["download"] as? URL {
process = process.download(downloadPath: download, completionHandler: completionHandler)
} else if let download = parameters["download"] as? String, download != "false" {
process = process.download(completionHandler: completionHandler)
} else if let download = parameters["download"] as? Bool, download != false {
process = process.download(completionHandler: completionHandler)
} else {
completionHandler?(nil, nil)
}
}
}
}
}
}
}
return process
}
/**
Find possible conversion types.
:param: parameters Find conversion types for a specific inputformat and/or outputformat.
For example: ["inputformat" : "png"]
See https://cloudconvert.com/apidoc#types
:param: completionHandler The code to be executed once the request has finished.
*/
public func conversionTypes(parameters: [String: Any], completionHandler: @escaping (Array<[String: Any]>?, Error?) -> Void) -> Void {
req(url: "/conversiontypes", method: .get, parameters: parameters).responseJSON { (response) in
if let types = response.value as? Array<[String: Any]> {
completionHandler(types, nil)
} else {
completionHandler(nil, response.error)
}
}
}
|
0b23c363ec51bf220f1736746836bdc7
| 32.54958 | 209 | 0.618225 | false | false | false | false |
CoderST/DYZB
|
refs/heads/master
|
DYZB/DYZB/Class/Tools/Category/DownButton.swift
|
mit
|
1
|
//
// DownButton.swift
// DYZB
//
// Created by xiudou on 2017/6/22.
// Copyright © 2017年 xiudo. All rights reserved.
//
import UIKit
class DownButton: UIButton {
init(frame: CGRect, title : String, backGroundColor : UIColor?, font : UIFont, cornerRadius : CGFloat? = 0) {
super.init(frame: frame)
backgroundColor = backGroundColor
setTitle(title, for: .normal)
titleLabel?.font = font
layer.cornerRadius = cornerRadius ?? 0
clipsToBounds = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
33302ce0cdded57f5ef8166897658e2b
| 22.703704 | 113 | 0.623438 | false | false | false | false |
onevcat/CotEditor
|
refs/heads/develop
|
CotEditor/Sources/Collection+String.swift
|
apache-2.0
|
1
|
//
// Collection+String.swift
//
// CotEditor
// https://coteditor.com
//
// Created by 1024jp on 2017-03-19.
//
// ---------------------------------------------------------------------------
//
// © 2017-2020 1024jp
//
// 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
//
// https://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
// MARK: Sort
struct StringComparisonOptions: OptionSet {
let rawValue: Int
static let localized = StringComparisonOptions(rawValue: 1 << 0)
static let caseInsensitive = StringComparisonOptions(rawValue: 1 << 1)
}
extension MutableCollection where Self: RandomAccessCollection, Element == String {
/// Sort the collection in place, using the string value that the given key path refers as the comparison between elements.
///
/// - Parameters:
/// - keyPath: The key path to the string to compare.
/// - options: The storategy to compare strings.
mutating func sort(_ keyPath: KeyPath<Element, String> = \Element.self, options: StringComparisonOptions) {
let compare = compareFunction(options: options)
self.sort { compare($0[keyPath: keyPath], $1[keyPath: keyPath]) == .orderedAscending }
}
}
extension Sequence where Element == String {
/// Return the elements of the sequence, sorted using the string value that the given key path refers with the desired string comparison storategy.
///
/// - Parameters:
/// - keyPath: The key path to the string to compare.
/// - options: The storategy to compare strings.
/// - Returns: A sorted array of the sequence’s elements.
func sorted(_ keyPath: KeyPath<Element, String> = \Element.self, options: StringComparisonOptions) -> [Element] {
let compare = compareFunction(options: options)
return self.sorted { compare($0[keyPath: keyPath], $1[keyPath: keyPath]) == .orderedAscending }
}
}
private func compareFunction(options: StringComparisonOptions) -> (String, String) -> ComparisonResult {
switch options {
case [.localized, .caseInsensitive]:
return { $0.localizedCaseInsensitiveCompare($1) }
case [.localized]:
return { $0.localizedCompare($1) }
case [.caseInsensitive]:
return { $0.caseInsensitiveCompare($1) }
case []:
return { $0.compare($1) }
default:
fatalError()
}
}
// MARK: - File Name
extension Collection where Element == String {
/// Create a unique name from the receiver's elements by adding the suffix and also a number if needed.
///
/// - Parameters:
/// - proposedName: The name candidate.
/// - suffix: The name suffix to be appended before the number.
/// - Returns: An unique name.
func createAvailableName(for proposedName: String, suffix: String? = nil) -> String {
let spaceSuffix = suffix.flatMap { " " + $0 } ?? ""
let (rootName, baseCount): (String, Int?) = {
let suffixPattern = NSRegularExpression.escapedPattern(for: spaceSuffix)
let regex = try! NSRegularExpression(pattern: suffixPattern + "(?: ([0-9]+))?$")
guard let result = regex.firstMatch(in: proposedName, range: proposedName.nsRange) else { return (proposedName, nil) }
let root = (proposedName as NSString).substring(to: result.range.location)
let numberRange = result.range(at: 1)
guard numberRange != .notFound else { return (root, nil) }
let number = Int((proposedName as NSString).substring(with: numberRange))
return (root, number)
}()
let baseName = rootName + spaceSuffix
guard baseCount != nil || self.contains(baseName) else { return baseName }
return ((baseCount ?? 2)...).lazy
.map { baseName + " " + String($0) }
.first { !self.contains($0) }!
}
}
|
4e0b01d47c1de83dc5af6feaa35eb2eb
| 33.664122 | 151 | 0.61242 | false | false | false | false |
icapps/ios-air-rivet
|
refs/heads/master
|
Example/Pods/Stella/Sources/Printing/Print.swift
|
mit
|
3
|
//
// Dispatch.swift
// Pods
//
// Created by Jelle Vandebeeck on 06/06/16.
//
//
/**
Writes the textual representations of items, prefixed with a 🍞 emoji, into the standard output.
This textual representations is used for breadcrumbs.
- Parameter items: The items to write to the output.
- Returns : text to be printed
*/
@discardableResult
public func printBreadcrumb(_ items: Any...) -> String? {
guard Output.level == .verbose else {
return nil
}
let text = "🍞 " + items.map { String(describing: $0) }.joined(separator: " ")
print("\(text)")
return text
}
/**
Writes the textual representations of items, prefixed with a 🔥 emoji, into the standard output.
This textual representations is used for errors.
- Parameter items: The items to write to the output.
- Returns : text to be printed
*/
@discardableResult
public func printError(_ items: Any...) -> String? {
guard Output.level != .nothing || Output.level == .error else {
return nil
}
let text = "🔥 " + items.map { String(describing: $0) }.joined(separator: " ")
print(text)
return text
}
/**
Writes the textual representations of items, prefixed with a 🎯 emoji, into the standard output.
This textual representations is used for user actions.
- Parameter items: The items to write to the output.
- Returns : text to be printed
*/
@discardableResult
public func printAction(_ items: Any...) -> String? {
guard Output.level == .verbose || Output.level == .quiet else {
return nil
}
let text = "🎯 " + items.map { String(describing: $0) }.joined(separator: " ")
print("\(text)")
return text
}
/**
Writes the textual representations of items, prefixed with a 🤔 emoji, into the standard output.
This textual representations is used for times when you want to log a text in conspicuous situations. Like when parsing and a key that is not obligatoiry is missing. You tell the developer:" You use my code but I think this is wrong."
- Parameter items: The items to write to the output.
- Returns : text to be printed
*/
@discardableResult
public func printQuestion(_ items: Any...) -> String? {
guard Output.level == .verbose else {
return nil
}
let text = "❓ " + items.map { String(describing: $0) }.joined(separator: " ")
print("\(text)")
return text
}
// MARK: - Print Throw
/**
Uses `printError` when something is thrown inside `function`.
- Parameter function: closure that can potentially throw
- Returns : text to be printed
*/
@discardableResult
public func printThrowAsError(_ function: () throws -> Void) -> String? {
do {
try function()
return nil
} catch {
let result = "\(error)"
printError(result)
return result
}
}
/**
Uses `printQuestion` when something is thrown inside `function`.
- Parameter function: closure that can potentially throw
- Returns : text to be printed
*/
@discardableResult
public func printThrowAsQuestion(_ function: () throws -> Void) -> String? {
do {
try function()
return nil
} catch {
let result = "\(error)"
printQuestion(result)
return result
}
}
/**
Uses `printBreadcrumb` when something is thrown inside `function`.
- Parameter function: closure that can potentially throw
- Returns : text to be printed
*/
@discardableResult
public func printThrowAsBreadcrumb(_ function: () throws -> Void) -> String? {
do {
try function()
return nil
} catch {
let result = "\(error)"
printBreadcrumb(result)
return result
}
}
/**
Uses `printAction` when something is thrown inside `function`.
- Parameter function: closure that can potentially throw
- Returns : text to be printed
*/
@discardableResult
public func printThrowAsAction(_ function: () throws -> Void) -> String? {
do {
try function()
return nil
} catch {
let result = "\(error)"
printAction(result)
return result
}
}
|
bddea1935efd4b3845d27261c6bd0f03
| 22.962963 | 235 | 0.679547 | false | false | false | false |
easyui/EZPlayer
|
refs/heads/master
|
EZPlayer/EZPlayer.swift
|
mit
|
1
|
//
// EZPlayer.swift
// EZPlayer
//
// Created by yangjun zhu on 2016/12/28.
// Copyright © 2016年 yangjun zhu. All rights reserved.
//
import Foundation
import AVFoundation
import AVKit
/// 播放器错误类型
public enum EZPlayerError: Error {
case invalidContentURL //错误的url
case playerFail // AVPlayer failed to load the asset.
}
/// 播放器的状态
public enum EZPlayerState {
case unknown // 播放前
case error(EZPlayerError) // 出现错误
case readyToPlay // 可以播放
case buffering // 缓冲中
case bufferFinished // 缓冲完毕
case playing // 播放
case seekingForward // 快进
case seekingBackward // 快退
case pause // 播放暂停
case stopped // 播放结束
}
//播放器浮框模式
public enum EZPlayerFloatMode {
case none
case auto //支持系统pip的就是system,否则是window
case system //iPhone在ios14一下不显示
case window
}
//播放器显示模式类型
public enum EZPlayerDisplayMode {
case none
case embedded
case fullscreen
case float
}
//播放器全屏模式类型
public enum EZPlayerFullScreenMode {
case portrait
case landscape
}
//播放器流的显示比例
public enum EZPlayerVideoGravity : String {
case aspect = "AVLayerVideoGravityResizeAspect" //视频值 ,等比例填充,直到一个维度到达区域边界
case aspectFill = "AVLayerVideoGravityResizeAspectFill" //等比例填充,直到填充满整个视图区域,其中一个维度的部分区域会被裁剪
case scaleFill = "AVLayerVideoGravityResize" //非均匀模式。两个维度完全填充至整个视图区域
}
//播放器结束原因
public enum EZPlayerPlaybackDidFinishReason {
case playbackEndTime
case playbackError
case stopByUser
}
//屏幕左右上下划动时的类型
public enum EZPlayerSlideTrigger{
case none
case volume
case brightness
}
//public enum EZPlayerFileType: String {
// case unknown
// case mp4
// case m3u8
//
//}
open class EZPlayer: NSObject {
// MARK: - player utils
public static var showLog = true//是否显示log
// MARK: - player setting
open weak var delegate: EZPlayerDelegate?
open var videoGravity = EZPlayerVideoGravity.aspect{
didSet {
if let layer = self.playerView?.layer as? AVPlayerLayer{
layer.videoGravity = AVLayerVideoGravity(rawValue: videoGravity.rawValue)
}
}
}
/// 设置url会自动播放
open var autoPlay = true
/// 设备横屏时自动旋转(phone)
open var autoLandscapeFullScreenLandscape = UIDevice.current.userInterfaceIdiom == .phone
/// 浮框的模式
open var floatMode = EZPlayerFloatMode.auto
/// 全屏的模式
open var fullScreenMode = EZPlayerFullScreenMode.landscape
/// 全屏时status bar的样式
open var fullScreenPreferredStatusBarStyle = UIStatusBarStyle.lightContent
/// 全屏时status bar的背景色
open var fullScreenStatusbarBackgroundColor = UIColor.black.withAlphaComponent(0.3)
/// 支持airplay
open var allowsExternalPlayback = true{
didSet{
guard let avplayer = self.player else {
return
}
avplayer.allowsExternalPlayback = allowsExternalPlayback
}
}
/// airplay连接状态
open var isExternalPlaybackActive: Bool {
guard let avplayer = self.player else {
return false
}
return avplayer.isExternalPlaybackActive
}
private var timeObserver: Any?//addPeriodicTimeObserver的返回值
private var timer : Timer?//.EZPlayerHeartbeat使用
// MARK: - player resource
open var contentItem: EZPlayerContentItem?
open private(set) var contentURL :URL?{//readonly
didSet{
guard let url = contentURL else {
return
}
self.isM3U8 = url.absoluteString.hasSuffix(".m3u8")
}
}
open private(set) var player: AVPlayer?
open private(set) var playerasset: AVAsset?{
didSet{
if oldValue != playerasset{
if playerasset != nil {
self.imageGenerator = AVAssetImageGenerator(asset: playerasset!)
}else{
self.imageGenerator = nil
}
}
}
}
open private(set) var playerItem: AVPlayerItem?{
willSet{
if playerItem != newValue{
if let item = playerItem{
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: item)
item.removeObserver(self, forKeyPath: #keyPath(AVPlayerItem.status))
item.removeObserver(self, forKeyPath: #keyPath(AVPlayerItem.loadedTimeRanges))
item.removeObserver(self, forKeyPath: #keyPath(AVPlayerItem.isPlaybackBufferEmpty))
item.removeObserver(self, forKeyPath: #keyPath(AVPlayerItem.isPlaybackLikelyToKeepUp))
}
}
}
didSet {
if playerItem != oldValue{
if let item = playerItem{
NotificationCenter.default.addObserver(self, selector: #selector(self.playerDidPlayToEnd(_:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: playerItem)
item.addObserver(self, forKeyPath: #keyPath(AVPlayerItem.status), options: NSKeyValueObservingOptions.new, context: nil)
//缓冲区大小
item.addObserver(self, forKeyPath: #keyPath(AVPlayerItem.loadedTimeRanges), options: NSKeyValueObservingOptions.new, context: nil)
// 缓冲区空了,需要等待数据
item.addObserver(self, forKeyPath: #keyPath(AVPlayerItem.isPlaybackBufferEmpty), options: NSKeyValueObservingOptions.new, context: nil)
// 缓冲区有足够数据可以播放了
item.addObserver(self, forKeyPath: #keyPath(AVPlayerItem.isPlaybackLikelyToKeepUp), options: NSKeyValueObservingOptions.new, context: nil)
}
}
}
}
/// 视频截图
open private(set) var imageGenerator: AVAssetImageGenerator?
/// 视频截图m3u8
open private(set) var videoOutput: AVPlayerItemVideoOutput?
open private(set) var isM3U8 = false
open var isLive: Bool? {
if let duration = self.duration {
return duration.isNaN
}
return nil
}
/// 上下滑动屏幕的控制类型
open var slideTrigger = (left:EZPlayerSlideTrigger.volume,right:EZPlayerSlideTrigger.brightness)
/// 左右滑动屏幕改变视频进度
open var canSlideProgress = true
// MARK: - player component
//只读
open var controlView : UIView?{
if let view = self.controlViewForIntercept{
return view
}
switch self.displayMode {
case .embedded:
return self.controlViewForEmbedded
case .fullscreen:
return self.controlViewForFullscreen
case .float:
return self.controlViewForFloat
case .none:
return self.controlViewForEmbedded
}
}
/// 拦截原来的各种controlView,作用:比如你要插入一个广告的view,广告结束置空即可
open var controlViewForIntercept : UIView? {
didSet{
self.updateCustomView()
}
}
///cactus todo EZPlayerControlView
/// 嵌入模式的控制皮肤
open var controlViewForEmbedded : UIView?
/// 浮动模式的控制皮肤
open var controlViewForFloat : UIView?
/// 全屏模式的控制皮肤
open var controlViewForFullscreen : UIView?
/// 全屏模式控制器
open private(set) var fullScreenViewController : EZPlayerFullScreenViewController?
/// 视频控制器视图
fileprivate var playerView: EZPlayerView?
open var view: UIView{
if self.playerView == nil{
self.playerView = EZPlayerView(controlView: self.controlView)
}
return self.playerView!
}
/// 嵌入模式的容器
open weak var embeddedContentView: UIView?
/// 嵌入模式的显示隐藏
open private(set) var controlsHidden = false
/// 过多久自动消失控件,设置为<=0不消失
open var autohiddenTimeInterval: TimeInterval = 8
/// 返回按钮block
open var backButtonBlock:(( _ fromDisplayMode: EZPlayerDisplayMode) -> Void)?
open var floatContainer: EZPlayerWindowContainer?
open var floatContainerRootViewController: EZPlayerWindowContainerRootViewController?
open var floatInitFrame = CGRect(x: UIScreen.main.bounds.size.width - 213 - 10, y: UIScreen.main.bounds.size.height - 120 - 49 - 34 - 10, width: 213, height: 120)
// autohideTimeInterval//
// MARK: - player status
open fileprivate(set) var state = EZPlayerState.unknown{
didSet{
printLog("old state: \(oldValue)")
printLog("new state: \(state)")
if oldValue != state{
(self.controlView as? EZPlayerDelegate)?.player(self, playerStateDidChange: state)
self.delegate?.player(self, playerStateDidChange: state)
NotificationCenter.default.post(name: .EZPlayerStatusDidChange, object: self, userInfo: [Notification.Key.EZPlayerNewStateKey: state,Notification.Key.EZPlayerOldStateKey: oldValue])
var loading = false;
switch state {
case .readyToPlay,.playing ,.pause,.seekingForward,.seekingBackward,.stopped,.bufferFinished://cactus todo
loading = false;
break
default:
loading = true;
break
}
(self.controlView as? EZPlayerDelegate)?.player(self, showLoading: loading)
self.delegate?.player(self, showLoading: loading)
NotificationCenter.default.post(name: .EZPlayerLoadingDidChange, object: self, userInfo: [Notification.Key.EZPlayerLoadingDidChangeKey: loading])
if case .error(_) = state {
NotificationCenter.default.post(name: .EZPlayerPlaybackDidFinish, object: self, userInfo: [Notification.Key.EZPlayerPlaybackDidFinishReasonKey: EZPlayerPlaybackDidFinishReason.playbackError])
}
}
}
}
open private(set) var displayMode = EZPlayerDisplayMode.none{
didSet{
if oldValue != displayMode{
(self.controlView as? EZPlayerDelegate)?.player(self, playerDisplayModeDidChange: displayMode)
self.delegate?.player(self, playerDisplayModeDidChange: displayMode)
NotificationCenter.default.post(name: .EZPlayerDisplayModeDidChange, object: self, userInfo: [Notification.Key.EZPlayerDisplayModeDidChangeKey: displayMode])
}
}
}
open private(set) var lastDisplayMode = EZPlayerDisplayMode.none
open var isPlaying:Bool{
guard let player = self.player else {
return false
}
if #available(iOS 10.0, *) {
return player.timeControlStatus == .playing;
}else{
return player.rate > Float(0) && player.error == nil
}
}
/// 视频长度,live是NaN
open var duration: TimeInterval? {
if let duration = self.player?.duration {
return duration
}
return nil
}
/// 视频进度
open var currentTime: TimeInterval? {
if let currentTime = self.player?.currentTime {
return currentTime
}
return nil
}
/// 视频播放速率
open var rate: Float{
get {
if let player = self.player {
return player.rate
}
return .nan
}
set {
if let player = self.player {
player.rate = newValue
}
}
}
/// 系统音量
open var systemVolume: Float{
get {
return systemVolumeSlider.value
}
set {
systemVolumeSlider.value = newValue
}
}
private let systemVolumeSlider = EZPlayerUtils.systemVolumeSlider
open weak var scrollView: UITableView?{
willSet{
if scrollView != newValue{
if let view = scrollView{
view.removeObserver(self, forKeyPath: #keyPath(UITableView.contentOffset))
}
}
}
didSet {
if playerItem != oldValue{
if let view = scrollView{
view.addObserver(self, forKeyPath: #keyPath(UITableView.contentOffset), options: NSKeyValueObservingOptions.new, context: nil)
}
}
}
}
open var indexPath: IndexPath?
// MARK: - Picture in Picture
open var pipController: AVPictureInPictureController?
fileprivate var startPIPWithCompletion : ((Error?) -> Void)?
fileprivate var endPIPWithCompletion : (() -> Void)?
// MARK: - Life cycle
deinit {
NotificationCenter.default.removeObserver(self)
self.timer?.invalidate()
self.timer = nil
self.releasePlayerResource()
}
public override init() {
super.init()
self.commonInit()
}
public init(controlView: UIView? ) {
super.init()
if controlView == nil{
self.controlViewForEmbedded = UIView()
}else{
self.controlViewForEmbedded = controlView
}
self.commonInit()
}
// MARK: - Player action
open func playWithURL(_ url: URL,embeddedContentView contentView: UIView? = nil, title: String? = nil) {
self.contentItem = EZPlayerContentItem(url: url, title: title)
self.contentURL = url
self.prepareToPlay()
if contentView != nil {
self.embeddedContentView = contentView
self.embeddedContentView!.addSubview(self.view)
self.view.frame = self.embeddedContentView!.bounds
self.displayMode = .embedded
}else{
self.toFull()
}
}
open func replaceToPlayWithURL(_ url: URL, title: String? = nil) {
self.resetPlayerResource()
self.contentItem = EZPlayerContentItem(url: url, title: title)
self.contentURL = url
guard let url = self.contentURL else {
self.state = .error(.invalidContentURL)
return
}
self.playerasset = AVAsset(url: url)
let keys = ["tracks","duration","commonMetadata","availableMediaCharacteristicsWithMediaSelectionOptions"]
self.playerItem = AVPlayerItem(asset: self.playerasset!, automaticallyLoadedAssetKeys: keys)
self.player?.replaceCurrentItem(with: self.playerItem)
self.setControlsHidden(false, animated: true)
}
open func play(){
self.state = .playing
self.player?.play()
}
open func pause(){
self.state = .pause
self.player?.pause()
}
open func stop(){
let lastState = self.state
self.state = .stopped
self.player?.pause()
self.releasePlayerResource()
guard case .error(_) = lastState else{
if lastState != .stopped {
NotificationCenter.default.post(name: .EZPlayerPlaybackDidFinish, object: self, userInfo: [Notification.Key.EZPlayerPlaybackDidFinishReasonKey: EZPlayerPlaybackDidFinishReason.stopByUser])
}
return
}
}
open func seek(to time: TimeInterval, completionHandler: ((Bool) -> Swift.Void )? = nil){
guard let player = self.player else {
return
}
let lastState = self.state
if let currentTime = self.currentTime {
if currentTime > time {
self.state = .seekingBackward
}else if currentTime < time {
self.state = .seekingForward
}
}
playerItem?.cancelPendingSeeks()
playerasset?.cancelLoading()
player.seek(to: CMTimeMakeWithSeconds(time,preferredTimescale: CMTimeScale(NSEC_PER_SEC)), toleranceBefore: CMTime.zero, toleranceAfter: CMTime.zero, completionHandler: { [weak self] (finished) in
guard let weakSelf = self else {
return
}
switch (weakSelf.state) {
case .seekingBackward,.seekingForward:
weakSelf.state = lastState
default: break
}
completionHandler?(finished)
})
}
private var isChangingDisplayMode = false
open func toFull(_ orientation:UIDeviceOrientation = .landscapeLeft, animated: Bool = true ,completion: ((Bool) -> Swift.Void)? = nil) {
if self.isChangingDisplayMode == true {
completion?(false)
return
}
if self.displayMode == .fullscreen {
completion?(false)
return
}
guard let activityViewController = EZPlayerUtils.activityViewController() else {
completion?(false)
return
}
func __toFull(from view: UIView) {
self.isChangingDisplayMode = true
self.updateCustomView(toDisplayMode: .fullscreen)
NotificationCenter.default.post(name: .EZPlayerDisplayModeChangedWillAppear, object: self, userInfo: [Notification.Key.EZPlayerDisplayModeChangedFrom : self.lastDisplayMode, Notification.Key.EZPlayerDisplayModeChangedTo : EZPlayerDisplayMode.fullscreen])
self.setControlsHidden(true, animated: false)
self.fullScreenViewController = EZPlayerFullScreenViewController()
self.fullScreenViewController!.preferredlandscapeForPresentation = orientation == .landscapeRight ? .landscapeLeft : .landscapeRight
self.fullScreenViewController!.player = self
if animated {
let rect = view.convert(self.view.frame, to: activityViewController.view)
let x = activityViewController.view.bounds.size.width - rect.size.width - rect.origin.x
let y = activityViewController.view.bounds.size.height - rect.size.height - rect.origin.y
self.fullScreenViewController!.modalPresentationStyle = .fullScreen
activityViewController.present(self.fullScreenViewController!, animated: false, completion: {
self.view.removeFromSuperview()
self.fullScreenViewController!.view.addSubview(self.view)
self.fullScreenViewController!.view.sendSubviewToBack(self.view)
if self.autoLandscapeFullScreenLandscape && self.fullScreenMode == .landscape{
self.view.transform = CGAffineTransform(rotationAngle:orientation == .landscapeRight ? CGFloat(Double.pi / 2) : -CGFloat(Double.pi / 2))
self.view.frame = orientation == .landscapeRight ? CGRect(x: y, y: rect.origin.x, width: rect.size.height, height: rect.size.width) : CGRect(x: rect.origin.y, y: x, width: rect.size.height, height: rect.size.width)
}else{
self.view.frame = rect
}
UIView.animate(withDuration: EZPlayerAnimatedDuration, animations: {
if self.autoLandscapeFullScreenLandscape && self.fullScreenMode == .landscape{
self.view.transform = CGAffineTransform.identity
}
self.view.bounds = self.fullScreenViewController!.view.bounds
self.view.center = self.fullScreenViewController!.view.center
}, completion: {finished in
self.setControlsHidden(false, animated: true)
NotificationCenter.default.post(name: .EZPlayerDisplayModeChangedDidAppear, object: self, userInfo: [Notification.Key.EZPlayerDisplayModeChangedFrom : self.lastDisplayMode, Notification.Key.EZPlayerDisplayModeChangedTo : EZPlayerDisplayMode.fullscreen])
completion?(finished)
self.isChangingDisplayMode = false
})
})
}else{
self.fullScreenViewController!.modalPresentationStyle = .fullScreen
activityViewController.present(self.fullScreenViewController!, animated: false, completion: {
self.view.removeFromSuperview()
self.fullScreenViewController!.view.addSubview(self.view)
self.fullScreenViewController!.view.sendSubviewToBack(self.view)
self.view.bounds = self.fullScreenViewController!.view.bounds
self.view.center = self.fullScreenViewController!.view.center
self.setControlsHidden(false, animated: true)
NotificationCenter.default.post(name: .EZPlayerDisplayModeChangedDidAppear, object: self, userInfo: [Notification.Key.EZPlayerDisplayModeChangedFrom : self.lastDisplayMode, Notification.Key.EZPlayerDisplayModeChangedTo : EZPlayerDisplayMode.fullscreen])
completion?(true)
self.isChangingDisplayMode = false
})
}
}
let lastDisplayModeTemp = self.displayMode
if lastDisplayModeTemp == .embedded{
guard let embeddedContentView = self.embeddedContentView else {
completion?(false)
return
}
self.lastDisplayMode = lastDisplayModeTemp
__toFull(from: embeddedContentView)
}else if lastDisplayModeTemp == .float{
let floatModelSupported = EZPlayerUtils.floatModelSupported(self)
if floatModelSupported == .system{
self.lastDisplayMode = .fullscreen//特殊处理:设置目标
self.stopPIP {
}
}else{
guard let floatContainer = self.floatContainer else {
completion?(false)
return
}
self.lastDisplayMode = lastDisplayModeTemp
floatContainer.hidden()
__toFull(from: floatContainer.floatWindow)
}
}else{
//直接进入全屏
self.updateCustomView(toDisplayMode: .fullscreen)
NotificationCenter.default.post(name: .EZPlayerDisplayModeChangedWillAppear, object: self, userInfo: [Notification.Key.EZPlayerDisplayModeChangedFrom : self.lastDisplayMode, Notification.Key.EZPlayerDisplayModeChangedTo : EZPlayerDisplayMode.fullscreen])
self.setControlsHidden(true, animated: false)
self.fullScreenViewController = EZPlayerFullScreenViewController()
self.fullScreenViewController!.preferredlandscapeForPresentation = orientation == .landscapeRight ? .landscapeLeft : .landscapeRight
self.fullScreenViewController!.player = self
self.view.frame = self.fullScreenViewController!.view.bounds
self.fullScreenViewController!.view.addSubview(self.view)
self.fullScreenViewController!.view.sendSubviewToBack(self.view)
self.fullScreenViewController!.modalPresentationStyle = .fullScreen
activityViewController.present(self.fullScreenViewController!, animated: animated, completion: {
self.floatContainer?.hidden()
self.setControlsHidden(false, animated: true)
completion?(true)
NotificationCenter.default.post(name: .EZPlayerDisplayModeChangedDidAppear, object: self, userInfo: [Notification.Key.EZPlayerDisplayModeChangedFrom : self.lastDisplayMode, Notification.Key.EZPlayerDisplayModeChangedTo : EZPlayerDisplayMode.fullscreen])
})
}
}
open func toEmbedded(animated: Bool = true , completion: ((Bool) -> Swift.Void)? = nil){
if self.isChangingDisplayMode == true {
completion?(false)
return
}
if self.displayMode == .embedded {
completion?(false)
return
}
guard let embeddedContentView = self.embeddedContentView else{
completion?(false)
return
}
func __endToEmbedded(finished :Bool) {
self.view.removeFromSuperview()
embeddedContentView.addSubview(self.view)
self.view.frame = embeddedContentView.bounds
self.setControlsHidden(false, animated: true)
self.fullScreenViewController = nil
completion?(finished)
NotificationCenter.default.post(name: .EZPlayerDisplayModeChangedDidAppear, object: self, userInfo: [Notification.Key.EZPlayerDisplayModeChangedFrom : self.lastDisplayMode, Notification.Key.EZPlayerDisplayModeChangedTo : EZPlayerDisplayMode.embedded])
self.isChangingDisplayMode = false
}
let lastDisplayModeTemp = self.displayMode
if lastDisplayModeTemp == .fullscreen{
guard let fullScreenViewController = self.fullScreenViewController else{
completion?(false)
return
}
self.lastDisplayMode = lastDisplayModeTemp
self.isChangingDisplayMode = true
self.updateCustomView(toDisplayMode: .embedded)
NotificationCenter.default.post(name: .EZPlayerDisplayModeChangedWillAppear, object: self, userInfo: [Notification.Key.EZPlayerDisplayModeChangedFrom : self.lastDisplayMode, Notification.Key.EZPlayerDisplayModeChangedTo : EZPlayerDisplayMode.embedded])
self.setControlsHidden(true, animated: false)
if animated {
let rect = fullScreenViewController.view.bounds
self.view.removeFromSuperview()
UIApplication.shared.keyWindow?.addSubview(self.view)
fullScreenViewController.dismiss(animated: false, completion: {
if self.autoLandscapeFullScreenLandscape && self.fullScreenMode == .landscape{
self.view.transform = CGAffineTransform(rotationAngle : fullScreenViewController.currentOrientation == .landscapeLeft ? CGFloat(Double.pi / 2) : -CGFloat(Double.pi / 2))
self.view.frame = CGRect(x: rect.origin.x, y: rect.origin.y, width: rect.size.height, height: rect.size.width)
}else{
self.view.bounds = embeddedContentView.bounds
}
UIView.animate(withDuration: EZPlayerAnimatedDuration, animations: {
if self.autoLandscapeFullScreenLandscape && self.fullScreenMode == .landscape{
self.view.transform = CGAffineTransform.identity
}
var center = embeddedContentView.center
if let embeddedContentSuperview = embeddedContentView.superview {
center = embeddedContentSuperview.convert(embeddedContentView.center, to: UIApplication.shared.keyWindow)
}
self.view.bounds = embeddedContentView.bounds
self.view.center = center
}, completion: {finished in
__endToEmbedded(finished: finished)
})
})
}else{
fullScreenViewController.dismiss(animated: false, completion: {
__endToEmbedded(finished: true)
})
}
}else if lastDisplayModeTemp == .float{
let floatModelSupported = EZPlayerUtils.floatModelSupported(self)
if floatModelSupported == .system{
self.lastDisplayMode = .embedded//特殊处理:设置目标
self.stopPIP {
}
}else{
guard let floatContainer = self.floatContainer else {
completion?(false)
return
}
self.lastDisplayMode = lastDisplayModeTemp
floatContainer.hidden()
// self.controlView = Bundle(for: EZPlayerControlView.self).loadNibNamed(String(describing: EZPlayerControlView.self), owner: self, options: nil)?.last as? EZPlayerControlView
// self.displayMode = .embedded
self.isChangingDisplayMode = true
self.updateCustomView(toDisplayMode: .embedded)
NotificationCenter.default.post(name: .EZPlayerDisplayModeChangedWillAppear, object: self, userInfo: [Notification.Key.EZPlayerDisplayModeChangedFrom : self.lastDisplayMode, Notification.Key.EZPlayerDisplayModeChangedTo : EZPlayerDisplayMode.embedded])
self.setControlsHidden(true, animated: false)
if animated {
let rect = floatContainer.floatWindow.convert(self.view.frame, to: UIApplication.shared.keyWindow)
self.view.removeFromSuperview()
UIApplication.shared.keyWindow?.addSubview(self.view)
self.view.frame = rect
UIView.animate(withDuration: EZPlayerAnimatedDuration, animations: {
self.view.bounds = embeddedContentView.bounds
self.view.center = embeddedContentView.center
}, completion: {finished in
__endToEmbedded(finished: finished)
})
}else{
__endToEmbedded(finished: true)
}
}
}else{
completion?(false)
}
}
/// 进入浮层模式,
/// - Parameters:
/// - animated: <#animated description#>
/// - completion: <#completion description#>
open func toFloat(animated: Bool = true, completion: ((Bool) -> Swift.Void)? = nil) {
if self.floatMode == .none {
completion?(false)
return
}
if self.isChangingDisplayMode == true {
completion?(false)
return
}
if self.displayMode == .float {
completion?(false)
return
}
let floatModelSupported = EZPlayerUtils.floatModelSupported(self)
if floatModelSupported == .system{
self.isChangingDisplayMode = true
NotificationCenter.default.post(name: .EZPlayerDisplayModeChangedWillAppear, object: self, userInfo: [Notification.Key.EZPlayerDisplayModeChangedFrom : self.displayMode, Notification.Key.EZPlayerDisplayModeChangedTo : EZPlayerDisplayMode.float])
self.startPIP { [weak self] error in
guard let weakSelf = self else{
return
}
weakSelf.isChangingDisplayMode = false
weakSelf.lastDisplayMode = weakSelf.displayMode
if weakSelf.lastDisplayMode == .fullscreen{
guard let fullScreenViewController = weakSelf.fullScreenViewController else{
return
}
fullScreenViewController.dismiss(animated: false) {
weakSelf.fullScreenViewController = nil
}
}else if weakSelf.lastDisplayMode == .embedded{
// weakSelf.view.removeFromSuperview()
// weakSelf.controlViewForEmbedded = nil
weakSelf.view.isHidden = true
}
weakSelf.updateCustomView(toDisplayMode: .float)
completion?(error != nil ? true : false)
NotificationCenter.default.post(name: .EZPlayerDisplayModeChangedDidAppear, object: weakSelf, userInfo: [Notification.Key.EZPlayerDisplayModeChangedFrom : weakSelf.lastDisplayMode, Notification.Key.EZPlayerDisplayModeChangedTo : error != nil ? weakSelf.lastDisplayMode : EZPlayerDisplayMode.float])
}
}else{
self.toWindow(animated: animated, completion: completion)
}
}
// MARK: - public
open func setControlsHidden(_ hidden: Bool, animated: Bool = false){
self.controlsHidden = hidden
(self.controlView as? EZPlayerDelegate)?.player(self, playerControlsHiddenDidChange: hidden ,animated: animated )
self.delegate?.player(self, playerControlsHiddenDidChange: hidden,animated: animated)
NotificationCenter.default.post(name: .EZPlayerControlsHiddenDidChange, object: self, userInfo: [Notification.Key.EZPlayerControlsHiddenDidChangeKey: hidden,Notification.Key.EZPlayerControlsHiddenDidChangeByAnimatedKey: animated])
}
open func updateCustomView(toDisplayMode: EZPlayerDisplayMode? = nil){
var nextDisplayMode = self.displayMode
if toDisplayMode != nil{
nextDisplayMode = toDisplayMode!
}
if let view = self.controlViewForIntercept{
self.playerView?.controlView = view
self.displayMode = nextDisplayMode
return
}
switch nextDisplayMode {
case .embedded:
//playerView加问号,其实不关心playerView存不存在,存在就更新
if self.playerView?.controlView == nil || self.playerView?.controlView != self.controlViewForEmbedded{
if self.controlViewForEmbedded == nil {
self.controlViewForEmbedded = self.controlViewForFullscreen ?? Bundle(for: EZPlayerControlView.self).loadNibNamed(String(describing: EZPlayerControlView.self), owner: self, options: nil)?.last as? EZPlayerControlView
}
}
self.playerView?.controlView = self.controlViewForEmbedded
case .fullscreen:
if self.playerView?.controlView == nil || self.playerView?.controlView != self.controlViewForFullscreen{
if self.controlViewForFullscreen == nil {
self.controlViewForFullscreen = self.controlViewForEmbedded ?? Bundle(for: EZPlayerControlView.self).loadNibNamed(String(describing: EZPlayerControlView.self), owner: self, options: nil)?.last as? EZPlayerControlView
}
}
self.playerView?.controlView = self.controlViewForFullscreen
case .float:
// if self.controlViewForFloat == nil {
// self.controlViewForFloat = Bundle(for: EZPlayerFloatView.self).loadNibNamed(String(describing: EZPlayerFloatView.self), owner: self, options: nil)?.last as? UIView
// }
let floatModelSupported = EZPlayerUtils.floatModelSupported(self)
if self.playerView?.controlView == nil || self.playerView?.controlView != self.controlViewForFloat{
if self.controlViewForFloat == nil {
self.controlViewForFloat = floatModelSupported == .window ? Bundle(for: EZPlayerWindowView.self).loadNibNamed(String(describing: EZPlayerWindowView.self), owner: self, options: nil)?.last as? UIView : Bundle(for: EZPlayerControlView.self).loadNibNamed(String(describing: EZPlayerControlView.self), owner: self, options: nil)?.last as? EZPlayerControlView
}
}
self.playerView?.controlView = self.controlViewForFloat
break
case .none:
//初始化的时候
if self.controlView == nil {
self.controlViewForEmbedded = Bundle(for: EZPlayerControlView.self).loadNibNamed(String(describing: EZPlayerControlView.self), owner: self, options: nil)?.last as? EZPlayerControlView
}
}
self.displayMode = nextDisplayMode
}
// MARK: - private
private func commonInit() {
self.updateCustomView()//走case .none:,防止没有初始化
NotificationCenter.default.addObserver(self, selector: #selector(self.applicationWillEnterForeground(_:)), name: UIApplication.willEnterForegroundNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.applicationDidBecomeActive(_:)), name: UIApplication.didBecomeActiveNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.applicationWillResignActive(_:)), name: UIApplication.willResignActiveNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.applicationDidEnterBackground(_:)), name: UIApplication.didEnterBackgroundNotification, object: nil)
UIDevice.current.beginGeneratingDeviceOrientationNotifications()
NotificationCenter.default.addObserver(self, selector: #selector(self.deviceOrientationDidChange(_:)), name: UIDevice.orientationDidChangeNotification, object: nil)
// NotificationCenter.default.addObserver(self, selector: #selector(self.playerDidPlayToEnd(_:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: playerItem)
self.timer?.invalidate()
self.timer = nil
self.timer = Timer.timerWithTimeInterval(0.5, block: { [weak self] in
// guard let weakself = self, let player = weakself.pl
guard let weakSelf = self, let _ = weakSelf.player, let playerItem = weakSelf.playerItem else{
return
}
if !playerItem.isPlaybackLikelyToKeepUp && weakSelf.state == .playing{
weakSelf.state = .buffering
}
if playerItem.isPlaybackLikelyToKeepUp && (weakSelf.state == .buffering || weakSelf.state == .readyToPlay){
weakSelf.state = .bufferFinished
if weakSelf.autoPlay {
weakSelf.state = .playing
}
}
(weakSelf.controlView as? EZPlayerDelegate)?.playerHeartbeat(weakSelf)
weakSelf.delegate?.playerHeartbeat(weakSelf)
NotificationCenter.default.post(name: .EZPlayerHeartbeat, object: self, userInfo:nil)
}, repeats: true)
RunLoop.current.add(self.timer!, forMode: RunLoop.Mode.common)
}
private func prepareToPlay(){
guard let url = self.contentURL else {
self.state = .error(.invalidContentURL)
return
}
self.releasePlayerResource()
self.playerasset = AVAsset(url: url)
let keys = ["tracks","duration","commonMetadata","availableMediaCharacteristicsWithMediaSelectionOptions"]
self.playerItem = AVPlayerItem(asset: self.playerasset!, automaticallyLoadedAssetKeys: keys)
self.player = AVPlayer(playerItem: playerItem!)
// if #available(iOS 10.0, *) {
// self.player!.automaticallyWaitsToMinimizeStalling = false
// }
self.player!.allowsExternalPlayback = self.allowsExternalPlayback
if self.playerView == nil {
self.playerView = EZPlayerView(controlView: self.controlView )
}
(self.playerView?.layer as! AVPlayerLayer).videoGravity = AVLayerVideoGravity(rawValue: self.videoGravity.rawValue)
self.playerView?.config(player: self)
(self.controlView as? EZPlayerDelegate)?.player(self, showLoading: true)
self.delegate?.player(self, showLoading: true)
NotificationCenter.default.post(name: .EZPlayerLoadingDidChange, object: self, userInfo: [Notification.Key.EZPlayerLoadingDidChangeKey: true])
self.addPlayerItemTimeObserver()
}
private func addPlayerItemTimeObserver(){
self.timeObserver = self.player?.addPeriodicTimeObserver(forInterval: CMTimeMakeWithSeconds(0.5, preferredTimescale: CMTimeScale(NSEC_PER_SEC)), queue: DispatchQueue.main, using: { [weak self] time in
guard let weakSelf = self else {
return
}
(weakSelf.controlView as? EZPlayerDelegate)?.player(weakSelf, currentTime: weakSelf.currentTime ?? 0, duration: weakSelf.duration ?? 0)
weakSelf.delegate?.player(weakSelf, currentTime: weakSelf.currentTime ?? 0, duration: weakSelf.duration ?? 0)
NotificationCenter.default.post(name: .EZPlayerPlaybackTimeDidChange, object: self, userInfo:nil)
})
}
private func resetPlayerResource() {
self.contentItem = nil
self.contentURL = nil
if self.videoOutput != nil {
self.playerItem?.remove(self.videoOutput!)
}
self.videoOutput = nil
self.playerasset = nil
self.playerItem = nil
self.player?.replaceCurrentItem(with: nil)
self.playerView?.layer.removeAllAnimations()
(self.controlView as? EZPlayerDelegate)?.player(self, bufferDurationDidChange: 0, totalDuration: 0)
self.delegate?.player(self, bufferDurationDidChange: 0, totalDuration: 0)
(self.controlView as? EZPlayerDelegate)?.player(self, currentTime:0, duration: 0)
self.delegate?.player(self, currentTime: 0, duration: 0)
NotificationCenter.default.post(name: .EZPlayerPlaybackTimeDidChange, object: self, userInfo:nil)
}
private func releasePlayerResource() {
self.releasePIPResource()
if self.fullScreenViewController != nil {
self.fullScreenViewController!.dismiss(animated: true, completion: {
})
}
self.scrollView = nil
self.indexPath = nil
if self.videoOutput != nil {
self.playerItem?.remove(self.videoOutput!)
}
self.videoOutput = nil
self.playerasset = nil
self.playerItem = nil
self.player?.replaceCurrentItem(with: nil)
self.playerView?.layer.removeAllAnimations()
self.playerView?.removeFromSuperview()
self.playerView = nil
if self.timeObserver != nil{
self.player?.removeTimeObserver(self.timeObserver!)
self.timeObserver = nil
}
}
}
// MARK: - Notification
extension EZPlayer {
@objc fileprivate func playerDidPlayToEnd(_ notifiaction: Notification) {
self.state = .stopped
NotificationCenter.default.post(name: .EZPlayerPlaybackDidFinish, object: self, userInfo: [Notification.Key.EZPlayerPlaybackDidFinishReasonKey: EZPlayerPlaybackDidFinishReason.playbackEndTime])
}
@objc fileprivate func deviceOrientationDidChange(_ notifiaction: Notification){
// if !self.autoLandscapeFullScreenLandscape || self.embeddedContentView == nil{
//app前后台切换
if UIApplication.shared.applicationState != UIApplication.State.active {
return
}
if !self.autoLandscapeFullScreenLandscape || self.fullScreenMode == .portrait {
return
}
switch UIDevice.current.orientation {
case .portrait:
//如果后台切回前台保持原来竖屏状态
if self.displayMode == .embedded || self.displayMode == .float {
return
}
if self.lastDisplayMode == .embedded{
self.toEmbedded()
}else if self.lastDisplayMode == .float{
self.toFloat()
}
case .landscapeLeft:
self.toFull(UIDevice.current.orientation)
case .landscapeRight:
self.toFull(UIDevice.current.orientation)
default:
break
}
}
@objc fileprivate func applicationWillEnterForeground(_ notifiaction: Notification){
}
@objc fileprivate func applicationDidBecomeActive(_ notifiaction: Notification){
}
@objc fileprivate func applicationWillResignActive(_ notifiaction: Notification){
}
@objc fileprivate func applicationDidEnterBackground(_ notifiaction: Notification){
}
}
// MARK: - KVO
extension EZPlayer {
override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if let item = object as? AVPlayerItem, let keyPath = keyPath {
if item == self.playerItem {
switch keyPath {
case #keyPath(AVPlayerItem.status):
//todo check main thread
//3)然后是kAVPlayerItemStatus的变化,从0变为1,即变为readyToPlay
printLog("AVPlayerItem's status is changed: \(item.status.rawValue)")
if item.status == .readyToPlay {//可以播放
let lastState = self.state
if self.state != .playing{
self.state = .readyToPlay
}
//自动播放
if self.autoPlay && lastState == .unknown{
self.play()
}
} else if item.status == .failed {
self.state = .error(.playerFail)
}
case #keyPath(AVPlayerItem.loadedTimeRanges):
printLog("AVPlayerItem's loadedTimeRanges is changed")
(self.controlView as? EZPlayerDelegate)?.player(self, bufferDurationDidChange: item.bufferDuration ?? 0, totalDuration: self.duration ?? 0)
self.delegate?.player(self, bufferDurationDidChange: item.bufferDuration ?? 0, totalDuration: self.duration ?? 0)
case #keyPath(AVPlayerItem.isPlaybackBufferEmpty):
//1)首先是观察到kAVPlayerItemPlaybackBufferEmpty的变化,从1变为0,说有缓存到内容了,已经有loadedTimeRanges了,但这时候还不一定能播放,因为数据可能还不够播放;
printLog("AVPlayerItem's playbackBufferEmpty is changed")
case #keyPath(AVPlayerItem.isPlaybackLikelyToKeepUp):
//2)然后是kAVPlayerItemPlaybackLikelyToKeepUp,从0变到1,说明可以播放了,这时候会自动开始播放
printLog("AVPlayerItem's playbackLikelyToKeepUp is changed")
default:
break
}
}
}else if let view = object as? UITableView ,let keyPath = keyPath{
switch keyPath {
case #keyPath(UITableView.contentOffset):
if isChangingDisplayMode == true{
return
}
if view == self.scrollView {
if let index = self.indexPath {
let cellrectInTable = view.rectForRow(at: index)
let cellrectInTableSuperView = view.convert(cellrectInTable, to: view.superview)
if cellrectInTableSuperView.origin.y + cellrectInTableSuperView.size.height/2 < view.frame.origin.y + view.contentInset.top || cellrectInTableSuperView.origin.y + cellrectInTableSuperView.size.height/2 > view.frame.origin.y + view.frame.size.height - view.contentInset.bottom{
self.toFloat()
}else{
if let cell = view.cellForRow(at: index){
if !self.view.isDescendant(of: cell){
self.view.removeFromSuperview()
self.embeddedContentView = self.embeddedContentView ?? cell.contentView
self.embeddedContentView!.addSubview(self.view)
}
self.toEmbedded(animated: false, completion: { flag in
})
}
}
}
}
default:
break
}
}
}
}
// MARK: - generateThumbnails
extension EZPlayer {
//不支持m3u8
open func generateThumbnails(times: [TimeInterval],maximumSize: CGSize, completionHandler: @escaping (([EZPlayerThumbnail]) -> Swift.Void )){
guard let imageGenerator = self.imageGenerator else {
return
}
var values = [NSValue]()
for time in times {
values.append(NSValue(time: CMTimeMakeWithSeconds(time,preferredTimescale: CMTimeScale(NSEC_PER_SEC))))
}
var thumbnailCount = values.count
var thumbnails = [EZPlayerThumbnail]()
imageGenerator.cancelAllCGImageGeneration()
imageGenerator.appliesPreferredTrackTransform = true// 截图的时候调整到正确的方向
imageGenerator.maximumSize = maximumSize//设置后可以获取缩略图
imageGenerator.generateCGImagesAsynchronously(forTimes:values) { (requestedTime: CMTime,image: CGImage?,actualTime: CMTime,result: AVAssetImageGenerator.Result,error: Error?) in
let thumbnail = EZPlayerThumbnail(requestedTime: requestedTime, image: image == nil ? nil : UIImage(cgImage: image!) , actualTime: actualTime, result: result, error: error)
thumbnails.append(thumbnail)
thumbnailCount -= 1
if thumbnailCount == 0 {
DispatchQueue.main.async {
completionHandler(thumbnails)
}
}
}
}
//支持m3u8
open func snapshotImage() -> UIImage? {
guard let playerItem = self.playerItem else { //playerItem is AVPlayerItem
return nil
}
if self.videoOutput == nil {
self.videoOutput = AVPlayerItemVideoOutput(pixelBufferAttributes: nil)
playerItem.remove(self.videoOutput!)
playerItem.add(self.videoOutput!)
}
guard let videoOutput = self.videoOutput else {
return nil
}
let time = videoOutput.itemTime(forHostTime: CACurrentMediaTime())
if videoOutput.hasNewPixelBuffer(forItemTime: time) {
let lastSnapshotPixelBuffer = videoOutput.copyPixelBuffer(forItemTime: time, itemTimeForDisplay: nil)
if lastSnapshotPixelBuffer != nil {
let ciImage = CIImage(cvPixelBuffer: lastSnapshotPixelBuffer!)
let context = CIContext(options: nil)
let rect = CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(CVPixelBufferGetWidth(lastSnapshotPixelBuffer!)), height: CGFloat(CVPixelBufferGetHeight(lastSnapshotPixelBuffer!)))
let cgImage = context.createCGImage(ciImage, from: rect)
if cgImage != nil {
return UIImage(cgImage: cgImage!)
}
}
}
return nil
}
}
// MARK: - display Mode
extension EZPlayer {
private func configFloatVideo(){
if self.floatContainerRootViewController == nil {
self.floatContainerRootViewController = EZPlayerWindowContainerRootViewController(nibName: String(describing: EZPlayerWindowContainerRootViewController.self), bundle: Bundle(for: EZPlayerWindowContainerRootViewController.self))
}
if self.floatContainer == nil {
self.floatContainer = EZPlayerWindowContainer(frame: self.floatInitFrame, rootViewController: self.floatContainerRootViewController!)
}
}
open func toWindow(animated: Bool = true, completion: ((Bool) -> Swift.Void)? = nil) {
func __endToWindow(finished :Bool) {
self.view.removeFromSuperview()
self.floatContainerRootViewController?.addVideoView(self.view)
self.floatContainer?.show()
self.setControlsHidden(false, animated: true)
self.fullScreenViewController = nil
completion?(finished)
NotificationCenter.default.post(name: .EZPlayerDisplayModeChangedDidAppear, object: self, userInfo: [Notification.Key.EZPlayerDisplayModeChangedFrom : self.lastDisplayMode, Notification.Key.EZPlayerDisplayModeChangedTo : EZPlayerDisplayMode.float])
self.isChangingDisplayMode = false
}
self.lastDisplayMode = self.displayMode
if self.lastDisplayMode == .embedded {
self.configFloatVideo()
self.isChangingDisplayMode = true
self.updateCustomView(toDisplayMode: .float)
NotificationCenter.default.post(name: .EZPlayerDisplayModeChangedWillAppear, object: self, userInfo: [Notification.Key.EZPlayerDisplayModeChangedFrom : self.lastDisplayMode, Notification.Key.EZPlayerDisplayModeChangedTo : EZPlayerDisplayMode.float])
self.setControlsHidden(true, animated: false)
if animated{
let rect = self.embeddedContentView!.convert(self.view.frame, to: UIApplication.shared.keyWindow)
self.view.removeFromSuperview()
UIApplication.shared.keyWindow?.addSubview(self.view)
self.view.frame = rect
UIView.animate(withDuration: EZPlayerAnimatedDuration, animations: {
self.view.bounds = self.floatContainer!.floatWindow.bounds
self.view.center = self.floatContainer!.floatWindow.center
}, completion: {finished in
__endToWindow(finished: finished)
})
}else{
__endToWindow(finished: true)
}
}else if self.lastDisplayMode == .fullscreen{
guard let fullScreenViewController = self.fullScreenViewController else{
completion?(false)
return
}
self.configFloatVideo()
self.isChangingDisplayMode = true
self.updateCustomView(toDisplayMode: .float)
NotificationCenter.default.post(name: .EZPlayerDisplayModeChangedWillAppear, object: self, userInfo: [Notification.Key.EZPlayerDisplayModeChangedFrom : self.lastDisplayMode, Notification.Key.EZPlayerDisplayModeChangedTo : EZPlayerDisplayMode.float])
self.setControlsHidden(true, animated: false)
if animated{
let rect = fullScreenViewController.view.bounds
self.view.removeFromSuperview()
UIApplication.shared.keyWindow?.addSubview(self.view)
fullScreenViewController.dismiss(animated: false, completion: {
if self.autoLandscapeFullScreenLandscape && self.fullScreenMode == .landscape{
self.view.transform = CGAffineTransform(rotationAngle : fullScreenViewController.currentOrientation == .landscapeLeft ? CGFloat(Double.pi / 2) : -CGFloat(Double.pi / 2))
self.view.frame = CGRect(x: rect.origin.x, y: rect.origin.y, width: rect.size.height, height: rect.size.width)
}else{
self.view.bounds = self.floatContainer!.floatWindow.bounds
}
UIView.animate(withDuration: EZPlayerAnimatedDuration, animations: {
if self.autoLandscapeFullScreenLandscape && self.fullScreenMode == .landscape{
self.view.transform = CGAffineTransform.identity
}
self.view.bounds = self.floatContainer!.floatWindow.bounds
self.view.center = self.floatContainer!.floatWindow.center
}, completion: {finished in
__endToWindow(finished: finished)
})
})
}else{
fullScreenViewController.dismiss(animated: false, completion: {
__endToWindow(finished: true)
})
}
}else{
completion?(false)
}
}
}
// MARK: - Picture in Picture Mode
extension EZPlayer: AVPictureInPictureControllerDelegate {
/// 是否支持pip
open var isPIPSupported: Bool{
return AVPictureInPictureController.isPictureInPictureSupported()
}
/// 当前是否处于画中画状态显示在屏幕上
open var isPIPActive: Bool{
return self.pipController?.isPictureInPictureActive ?? false
}
/// 当前画中画是否被挂起。如果你的app因为其他的app在使用PiP而导致你的视频后台播放播放状态为暂停并且不可见,将会返回true。当其他的app离开了PiP时,你的视频会被重新播放
open var isPIPSuspended: Bool{
return self.pipController?.isPictureInPictureSuspended ?? false
}
/// 告诉你画中画窗口是可用的。如果其他的app再使用PiP模式,他将会返回false。这个实行也能够通过KVO来观察,同样通过观察这种状态的改变,你也能够很好地额处理PiP按钮的的隐藏于展示。
open var isPIPPossible: Bool{
return self.pipController?.isPictureInPicturePossible ?? false
}
open func startPIP(completion: ((Error?) -> Void)? = nil){
self.configPIP()
self.startPIPWithCompletion = completion
//isPIPSupported和isPIPPossible为true才有效
// self.pipController?.startPictureInPicture()
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1) {
self.pipController?.startPictureInPicture()
}
}
open func stopPIP(completion: (() -> Void)? = nil){
self.endPIPWithCompletion = completion
self.pipController?.stopPictureInPicture()
}
private func configPIP(){
if isPIPSupported && playerView != nil && pipController == nil {
pipController = AVPictureInPictureController(playerLayer: playerView!.layer as! AVPlayerLayer)
pipController?.delegate = self
}
}
private func releasePIPResource() {
pipController?.delegate = nil
pipController = nil
}
/// 即将开启画中画
/// - Parameter pictureInPictureController: <#pictureInPictureController description#>
public func pictureInPictureControllerWillStartPictureInPicture(_ pictureInPictureController: AVPictureInPictureController) {
printLog("pip 即将开启画中画")
(self.controlView as? EZPlayerDelegate)?.player(self, pictureInPictureControllerWillStartPictureInPicture: pictureInPictureController)
self.delegate?.player(self, pictureInPictureControllerWillStartPictureInPicture: pictureInPictureController)
NotificationCenter.default.post(name: .EZPlayerPIPControllerWillStart, object: self, userInfo: nil)
}
/// 已经开启画中画
/// - Parameter pictureInPictureController: <#pictureInPictureController description#>
public func pictureInPictureControllerDidStartPictureInPicture(_ pictureInPictureController: AVPictureInPictureController) {
printLog("pip 已经开启画中画")
self.startPIPWithCompletion?(nil)
(self.controlView as? EZPlayerDelegate)?.player(self, pictureInPictureControllerDidStartPictureInPicture: pictureInPictureController)
self.delegate?.player(self, pictureInPictureControllerDidStartPictureInPicture: pictureInPictureController)
NotificationCenter.default.post(name: .EZPlayerPIPControllerDidStart, object: self, userInfo: nil)
}
/// 开启画中画失败
/// - Parameters:
/// - pictureInPictureController: <#pictureInPictureController description#>
/// - error: <#error description#>
public func pictureInPictureController(_ pictureInPictureController: AVPictureInPictureController, failedToStartPictureInPictureWithError error: Error) {
printLog("pip 开启画中画失败")
self.releasePIPResource()
self.startPIPWithCompletion?(error)
(self.controlView as? EZPlayerDelegate)?.player(self, pictureInPictureController: pictureInPictureController, failedToStartPictureInPictureWithError: error)
self.delegate?.player(self, pictureInPictureController: pictureInPictureController, failedToStartPictureInPictureWithError: error)
NotificationCenter.default.post(name: .EZPlayerPIPFailedToStart, object: self, userInfo: [Notification.Key.EZPlayerPIPFailedToStart: error])
}
/// 即将关闭画中画
/// - Parameter pictureInPictureController: <#pictureInPictureController description#>
public func pictureInPictureControllerWillStopPictureInPicture(_ pictureInPictureController: AVPictureInPictureController) {
printLog("pip 即将关闭画中画")
self.isChangingDisplayMode = true
NotificationCenter.default.post(name: .EZPlayerDisplayModeChangedWillAppear, object: self, userInfo: [Notification.Key.EZPlayerDisplayModeChangedFrom : self.displayMode, Notification.Key.EZPlayerDisplayModeChangedTo : self.lastDisplayMode])
(self.controlView as? EZPlayerDelegate)?.player(self, pictureInPictureControllerWillStopPictureInPicture: pictureInPictureController)
self.delegate?.player(self, pictureInPictureControllerWillStopPictureInPicture: pictureInPictureController)
NotificationCenter.default.post(name: .EZPlayerPIPControllerWillEnd, object: self, userInfo: nil)
}
/// 已经关闭画中画
/// - Parameter pictureInPictureController: <#pictureInPictureController description#>
public func pictureInPictureControllerDidStopPictureInPicture(_ pictureInPictureController: AVPictureInPictureController) {
printLog("pip 已经关闭画中画")
self.releasePIPResource()
// 按钮last float x , last x float
self.isChangingDisplayMode = false
// if self.lastDisplayMode != .float{
let lastDisPlayModeTemp = self.lastDisplayMode
self.lastDisplayMode = .float
self.updateCustomView(toDisplayMode: lastDisPlayModeTemp)
// }else{
// self.updateCustomView(toDisplayMode: lastDisPlayModeTemp)
// self.updateCustomView(toDisplayMode: self.displayMode)
// }
// self.view.removeFromSuperview()
// self.embeddedContentView!.addSubview(self.view)
// self.view.frame = self.embeddedContentView!.bounds
self.endPIPWithCompletion?()
NotificationCenter.default.post(name: .EZPlayerDisplayModeChangedDidAppear, object: self, userInfo: [Notification.Key.EZPlayerDisplayModeChangedFrom : .float, Notification.Key.EZPlayerDisplayModeChangedTo : self.displayMode])
(self.controlView as? EZPlayerDelegate)?.player(self, pictureInPictureControllerDidStopPictureInPicture: pictureInPictureController)
self.delegate?.player(self, pictureInPictureControllerDidStopPictureInPicture: pictureInPictureController)
NotificationCenter.default.post(name: .EZPlayerPIPControllerDidEnd, object: self, userInfo: nil)
if self.displayMode == .fullscreen{
if self.state == .playing {
self.play()
}
if self.fullScreenViewController == nil {
self.fullScreenViewController = EZPlayerFullScreenViewController()
self.fullScreenViewController!.preferredlandscapeForPresentation = UIDevice.current.orientation == .landscapeRight ? .landscapeLeft : .landscapeRight
self.fullScreenViewController!.player = self
}
// guard let fullScreenViewController = self.fullScreenViewController else{
// return
// }
self.fullScreenViewController!.modalPresentationStyle = .fullScreen
guard let activityViewController = EZPlayerUtils.activityViewController() else {
return
}
activityViewController.present(self.fullScreenViewController!, animated: false) {
// self.view.removeFromSuperview()
self.fullScreenViewController!.view.addSubview(self.view)
self.fullScreenViewController!.view.sendSubviewToBack(self.view)
self.view.bounds = self.fullScreenViewController!.view.bounds
self.view.center = self.fullScreenViewController!.view.center
self.view.isHidden = false
self.setControlsHidden(false, animated: true)
}
}else if self.displayMode == .embedded{
self.view.isHidden = false
}
}
/// 关闭画中画且恢复播放界面
/// - Parameters:
/// - pictureInPictureController: <#pictureInPictureController description#>
/// - completionHandler: <#completionHandler description#>
public func pictureInPictureController(_ pictureInPictureController: AVPictureInPictureController, restoreUserInterfaceForPictureInPictureStopWithCompletionHandler completionHandler: @escaping (Bool) -> Void) {
printLog("pip 关闭画中画且恢复播放界面")
// completionHandler(true)
(self.controlView as? EZPlayerDelegate)?.player(self, pictureInPictureController: pictureInPictureController, restoreUserInterfaceForPictureInPictureStopWithCompletionHandler: completionHandler)
self.delegate?.player(self, pictureInPictureController: pictureInPictureController, restoreUserInterfaceForPictureInPictureStopWithCompletionHandler: completionHandler)
NotificationCenter.default.post(name: .EZPlayerPIPRestoreUserInterfaceForStop, object: self, userInfo: [Notification.Key.EZPlayerPIPStopWithCompletionHandler: completionHandler])
}
}
|
82b50749e1af2d96ea7d7fbf268033be
| 41.475399 | 375 | 0.634144 | false | false | false | false |
younata/RSSClient
|
refs/heads/master
|
TethysKit/WebPageParser.swift
|
mit
|
1
|
import Kanna
public final class WebPageParser: Operation {
public enum SearchType {
case feeds
case links
case `default`
var acceptableTypes: [String] {
switch self {
case .feeds:
return [
"application/rss+xml",
"application/rdf+xml",
"application/atom+xml",
"application/xml",
"text/xml"
]
case .links, .default:
return []
}
}
}
private let webPage: String
private let callback: ([URL]) -> Void
private var urls = [URL]()
public var searchType: SearchType = .default
public init(string: String, callback: @escaping ([URL]) -> Void) {
self.webPage = string
self.callback = callback
super.init()
}
public override func main() {
if let doc = try? Kanna.HTML(html: self.webPage, encoding: String.Encoding.utf8) {
switch self.searchType {
case .feeds:
for link in doc.xpath("//link") where link["rel"] == "alternate" &&
self.searchType.acceptableTypes.contains(link["type"] ?? "") {
if let urlString = link["href"], let url = URL(string: urlString) {
self.urls.append(url as URL)
}
}
case .links:
for link in doc.xpath("//a") {
if let urlString = link["href"], let url = URL(string: urlString) {
self.urls.append(url as URL)
}
}
default:
break
}
}
self.callback(self.urls)
}
}
|
c8a218811ba0b32b2130e34e7a4c87d8
| 29.066667 | 91 | 0.45898 | false | false | false | false |
ngageoint/mage-ios
|
refs/heads/master
|
Mage/ObservationViewCardCollectionViewController.swift
|
apache-2.0
|
1
|
//
// ObservationViewCardCollectionViewController.swift
// MAGE
//
// Created by Daniel Barela on 12/16/20.
// Copyright © 2020 National Geospatial Intelligence Agency. All rights reserved.
//
import Foundation
import UIKit
import MaterialComponents.MaterialCollections
import MaterialComponents.MDCCard
import MaterialComponents.MDCContainerScheme;
class ObservationViewCardCollectionViewController: UIViewController {
var didSetupConstraints = false;
weak var observation: Observation?;
var observationForms: [[String: Any]] = [];
var cards: [ExpandableCard] = [];
var attachmentViewCoordinator: AttachmentViewCoordinator?;
var headerCard: ObservationHeaderView?;
var observationEditCoordinator: ObservationEditCoordinator?;
var bottomSheet: MDCBottomSheetController?;
var scheme: MDCContainerScheming?;
var attachmentCard: ObservationAttachmentCard?;
let attachmentHeader: CardHeader = CardHeader(headerText: "ATTACHMENTS");
let formsHeader = FormsHeader(forAutoLayout: ());
private lazy var event: Event? = {
guard let observation = observation, let eventId = observation.eventId, let context = observation.managedObjectContext else {
return nil
}
return Event.getEvent(eventId: eventId, context: context)
}()
private lazy var eventForms: [Form] = {
return event?.forms ?? []
}()
private lazy var editFab : MDCFloatingButton = {
let fab = MDCFloatingButton(shape: .default);
fab.setImage(UIImage(systemName: "pencil", withConfiguration: UIImage.SymbolConfiguration(weight: .black)), for: .normal);
fab.addTarget(self, action: #selector(startObservationEditCoordinator), for: .touchUpInside);
return fab;
}()
private lazy var scrollView: UIScrollView = {
let scrollView = UIScrollView.newAutoLayout();
scrollView.accessibilityIdentifier = "card scroll";
scrollView.accessibilityLabel = "card scroll";
scrollView.contentInset.bottom = 100;
return scrollView;
}()
private lazy var stackView: UIStackView = {
let stackView = UIStackView.newAutoLayout();
stackView.axis = .vertical
stackView.alignment = .fill
stackView.spacing = 8
stackView.distribution = .fill
stackView.directionalLayoutMargins = NSDirectionalEdgeInsets(top: 8, leading: 8, bottom: 8, trailing: 8)
stackView.isLayoutMarginsRelativeArrangement = true;
return stackView;
}()
private lazy var syncStatusView: ObservationSyncStatus = {
let syncStatusView = ObservationSyncStatus(observation: observation);
stackView.addArrangedSubview(syncStatusView);
return syncStatusView;
}()
func applyTheme(withContainerScheme containerScheme: MDCContainerScheming?) {
self.scheme = containerScheme;
guard let containerScheme = containerScheme else {
return;
}
self.view.backgroundColor = containerScheme.colorScheme.backgroundColor;
self.syncStatusView.applyTheme(withScheme: containerScheme);
headerCard?.applyTheme(withScheme: containerScheme);
attachmentCard?.applyTheme(withScheme: containerScheme);
formsHeader.applyTheme(withScheme: containerScheme);
attachmentHeader.applyTheme(withScheme: containerScheme);
editFab.applySecondaryTheme(withScheme: containerScheme);
}
override func loadView() {
view = UIView();
view.addSubview(scrollView);
scrollView.addSubview(stackView);
view.addSubview(editFab);
let user = User.fetchCurrentUser(context: NSManagedObjectContext.mr_default())
editFab.isHidden = !(user?.hasEditPermission ?? false)
view.setNeedsUpdateConstraints();
}
override func updateViewConstraints() {
if (!didSetupConstraints) {
scrollView.autoPinEdgesToSuperviewEdges(with: .zero);
stackView.autoPinEdgesToSuperviewEdges();
stackView.autoMatch(.width, to: .width, of: view);
editFab.autoPinEdge(toSuperviewMargin: .right);
editFab.autoPinEdge(toSuperviewMargin: .bottom, withInset: 25);
didSetupConstraints = true;
}
super.updateViewConstraints();
}
init(frame: CGRect) {
super.init(nibName: nil, bundle: nil);
}
convenience public init(observation: Observation, scheme: MDCContainerScheming?) {
self.init(frame: CGRect.zero);
self.observation = observation;
self.scheme = scheme;
}
required init(coder aDecoder: NSCoder) {
fatalError("This class does not support NSCoding")
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.accessibilityIdentifier = "ObservationViewCardCollection"
self.view.accessibilityLabel = "ObservationViewCardCollection"
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated);
ObservationPushService.singleton.addDelegate(delegate: self);
setupObservation();
if let scheme = self.scheme {
applyTheme(withContainerScheme: scheme);
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated);
let removedSubviews = cards.reduce([]) { (allSubviews, subview) -> [UIView] in
stackView.removeArrangedSubview(subview)
return allSubviews + [subview]
}
for v in removedSubviews {
if v.superview != nil {
v.removeFromSuperview()
}
}
cards = [];
ObservationPushService.singleton.removeDelegate(delegate: self);
}
func setupObservation() {
self.title = "Observation";
if let properties = self.observation?.properties as? [String: Any] {
if (properties.keys.contains("forms")) {
observationForms = properties["forms"] as! [[String: Any]];
}
} else {
observationForms = [];
}
syncStatusView.updateObservationStatus(observation: observation);
addHeaderCard(stackView: stackView);
addLegacyAttachmentCard(stackView: stackView);
var headerViews = 2;
if (MageServer.isServerVersion5) {
headerViews = 4;
}
if (stackView.arrangedSubviews.count > headerViews) {
for v in stackView.arrangedSubviews.suffix(from: headerViews) {
v.removeFromSuperview();
}
}
addFormViews(stackView: stackView);
}
func addHeaderCard(stackView: UIStackView) {
if let observation = observation {
if let headerCard = headerCard {
headerCard.populate(observation: observation);
} else {
headerCard = ObservationHeaderView(observation: observation, observationActionsDelegate: self);
if let scheme = self.scheme {
headerCard!.applyTheme(withScheme: scheme);
}
stackView.addArrangedSubview(headerCard!);
}
}
}
// for legacy servers add the attachment field to common
// TODO: this can be removed once all servers are upgraded
func addLegacyAttachmentCard(stackView: UIStackView) {
if (MageServer.isServerVersion5) {
if let observation = observation {
if let attachmentCard = attachmentCard {
attachmentCard.populate(observation: observation);
} else {
attachmentCard = ObservationAttachmentCard(observation: observation, attachmentSelectionDelegate: self);
if let scheme = self.scheme {
attachmentCard!.applyTheme(withScheme: scheme);
attachmentHeader.applyTheme(withScheme: scheme);
}
stackView.addArrangedSubview(attachmentHeader);
stackView.addArrangedSubview(attachmentCard!);
}
let attachmentCount = (observation.attachments)?.filter() { attachment in
return !attachment.markedForDeletion
}.count
if (attachmentCount != 0) {
attachmentHeader.isHidden = false;
attachmentCard?.isHidden = false;
} else {
attachmentHeader.isHidden = true;
attachmentCard?.isHidden = true;
}
}
}
}
func addFormViews(stackView: UIStackView) {
formsHeader.reorderButton.isHidden = true;
stackView.addArrangedSubview(formsHeader);
for (index, form) in self.observationForms.enumerated() {
let card: ExpandableCard = addObservationFormView(observationForm: form, index: index);
card.expanded = index == 0;
}
}
func addObservationFormView(observationForm: [String: Any], index: Int) -> ExpandableCard {
let eventForm = event?.form(id: observationForm[EventKey.formId.key] as? NSNumber)
var formPrimaryValue: String? = nil;
var formSecondaryValue: String? = nil;
if let primaryField = eventForm?.primaryFeedField, let primaryFieldName = primaryField[FieldKey.name.key] as? String {
if let obsfield = observationForm[primaryFieldName] {
formPrimaryValue = Observation.fieldValueText(value: obsfield, field: primaryField)
}
}
if let secondaryField = eventForm?.secondaryFeedField, let secondaryFieldName = secondaryField[FieldKey.name.key] as? String {
if let obsfield = observationForm[secondaryFieldName] {
formSecondaryValue = Observation.fieldValueText(value: obsfield, field: secondaryField)
}
}
let formView = ObservationFormView(observation: self.observation!, form: observationForm, eventForm: eventForm, formIndex: index, editMode: false, viewController: self, attachmentSelectionDelegate: self, observationActionsDelegate: self);
if let scheme = self.scheme {
formView.applyTheme(withScheme: scheme);
}
var formSpacerView: UIView?;
if (!formView.isEmpty()) {
formSpacerView = UIView(forAutoLayout: ());
let divider = UIView(forAutoLayout: ());
divider.backgroundColor = scheme?.colorScheme.onSurfaceColor.withAlphaComponent(0.12) ?? UIColor.black.withAlphaComponent(0.12);
divider.autoSetDimension(.height, toSize: 1);
formSpacerView?.addSubview(divider);
formSpacerView?.addSubview(formView);
divider.autoPinEdgesToSuperviewEdges(with: .zero, excludingEdge: .bottom);
formView.autoPinEdgesToSuperviewEdges(with: UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16));
}
var tintColor: UIColor? = nil;
if let color = eventForm?.color {
tintColor = UIColor(hex: color);
} else {
tintColor = scheme?.colorScheme.primaryColor
}
let card = ExpandableCard(header: formPrimaryValue, subheader: formSecondaryValue, systemImageName: "doc.text.fill", title: eventForm?.name, imageTint: tintColor, expandedView: formSpacerView);
if let scheme = self.scheme {
card.applyTheme(withScheme: scheme);
}
stackView.addArrangedSubview(card)
cards.append(card);
return card;
}
@objc func startObservationEditCoordinator() {
guard let observation = self.observation else {
return;
}
observationEditCoordinator = ObservationEditCoordinator(rootViewController: self.navigationController, delegate: self, observation: observation);
observationEditCoordinator?.applyTheme(withContainerScheme: self.scheme);
observationEditCoordinator?.start();
}
}
extension ObservationViewCardCollectionViewController: AttachmentSelectionDelegate {
func selectedAttachment(_ attachment: Attachment!) {
if (attachment.url == nil) {
return;
}
guard let nav = self.navigationController else {
return;
}
attachmentViewCoordinator = AttachmentViewCoordinator(rootViewController: nav, attachment: attachment, delegate: self, scheme: scheme);
attachmentViewCoordinator?.start();
}
func selectedUnsentAttachment(_ unsentAttachment: [AnyHashable : Any]!) {
guard let nav = self.navigationController else {
return;
}
attachmentViewCoordinator = AttachmentViewCoordinator(rootViewController: nav, url: URL(fileURLWithPath: unsentAttachment["localPath"] as! String), contentType: unsentAttachment["contentType"] as! String, delegate: self, scheme: scheme);
attachmentViewCoordinator?.start();
}
func selectedNotCachedAttachment(_ attachment: Attachment!, completionHandler handler: ((Bool) -> Void)!) {
if (attachment.url == nil) {
return;
}
guard let nav = self.navigationController else {
return;
}
attachmentViewCoordinator = AttachmentViewCoordinator(rootViewController: nav, attachment: attachment, delegate: self, scheme: scheme);
attachmentViewCoordinator?.start();
}
}
extension ObservationViewCardCollectionViewController: AttachmentViewDelegate {
func doneViewing(coordinator: NSObject) {
attachmentViewCoordinator = nil;
}
}
extension ObservationViewCardCollectionViewController: ObservationPushDelegate {
func didPush(observation: Observation, success: Bool, error: Error?) {
if (observation.objectID != self.observation?.objectID) {
return;
}
headerCard?.populate(observation: observation, ignoreGeometry: true);
syncStatusView.updateObservationStatus();
if let scheme = self.scheme {
syncStatusView.applyTheme(withScheme: scheme);
}
view.setNeedsUpdateConstraints();
}
}
extension ObservationViewCardCollectionViewController: ObservationActionsDelegate {
func moreActionsTapped(_ observation: Observation) {
let actionsSheet: ObservationActionsSheetController = ObservationActionsSheetController(observation: observation, delegate: self);
actionsSheet.applyTheme(withContainerScheme: scheme);
bottomSheet = MDCBottomSheetController(contentViewController: actionsSheet);
self.navigationController?.present(bottomSheet!, animated: true, completion: nil);
}
func showFavorites(_ observation: Observation) {
var userIds: [String] = [];
if let favorites = observation.favorites {
for favorite in favorites {
if let userId = favorite.userId {
userIds.append(userId)
}
}
}
if (userIds.count != 0) {
let locationViewController = LocationsTableViewController(userIds: userIds, actionsDelegate: nil, scheme: scheme);
locationViewController.title = "Favorited By";
self.navigationController?.pushViewController(locationViewController, animated: true);
}
}
func favoriteObservation(_ observation: Observation, completion: ((Observation?) -> Void)?) {
observation.toggleFavorite() { success, error in
observation.managedObjectContext?.refresh(observation, mergeChanges: false);
self.headerCard?.populate(observation: observation);
}
}
func copyLocation(_ locationString: String) {
UIPasteboard.general.string = locationString;
MDCSnackbarManager.default.show(MDCSnackbarMessage(text: "Location \(locationString) copied to clipboard"))
}
func getDirectionsToObservation(_ observation: Observation, sourceView: UIView? = nil) {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
let notification = DirectionsToItemNotification(observation: observation, user: nil, feedItem: nil, sourceView: sourceView)
NotificationCenter.default.post(name: .DirectionsToItem, object: notification)
}
}
func makeImportant(_ observation: Observation, reason: String) {
observation.flagImportant(description: reason) { success, error in
// update the view
observation.managedObjectContext?.refresh(observation, mergeChanges: true);
self.headerCard?.populate(observation: observation);
}
}
func removeImportant(_ observation: Observation) {
observation.removeImportant() { success, error in
// update the view
observation.managedObjectContext?.refresh(observation, mergeChanges: false);
self.headerCard?.populate(observation: observation);
}
}
func editObservation(_ observation: Observation) {
bottomSheet?.dismiss(animated: true, completion: nil);
startObservationEditCoordinator()
}
func reorderForms(_ observation: Observation) {
bottomSheet?.dismiss(animated: true, completion: nil);
observationEditCoordinator = ObservationEditCoordinator(rootViewController: self.navigationController, delegate: self, observation: self.observation!);
observationEditCoordinator?.applyTheme(withContainerScheme: self.scheme);
observationEditCoordinator?.startFormReorder();
}
func deleteObservation(_ observation: Observation) {
bottomSheet?.dismiss(animated: true, completion: nil);
ObservationActionHandler.deleteObservation(observation: observation, viewController: self) { (success, error) in
self.navigationController?.popViewController(animated: true);
}
}
func cancelAction() {
bottomSheet?.dismiss(animated: true, completion: nil);
}
func viewUser(_ user: User) {
bottomSheet?.dismiss(animated: true, completion: nil);
let uvc = UserViewController(user: user, scheme: self.scheme!);
self.navigationController?.pushViewController(uvc, animated: true);
}
}
extension ObservationViewCardCollectionViewController: ObservationEditDelegate {
func editCancel(_ coordinator: NSObject) {
observationEditCoordinator = nil;
}
func editComplete(_ observation: Observation, coordinator: NSObject) {
observationEditCoordinator = nil;
guard let observation = self.observation else {
return;
}
self.observation!.managedObjectContext?.refresh(observation, mergeChanges: false);
// reload the observation
setupObservation();
}
}
|
2058c64b0c177ff4bda1017f8284a73e
| 40.528384 | 246 | 0.652313 | false | false | false | false |
mrdepth/EVEUniverse
|
refs/heads/master
|
Legacy/Neocom/Neocom/NCTreeViewController.swift
|
lgpl-2.1
|
2
|
//
// NCTreeViewController.swift
// Neocom
//
// Created by Artem Shimanski on 07.07.17.
// Copyright © 2017 Artem Shimanski. All rights reserved.
//
import UIKit
import CloudData
import EVEAPI
import Futures
enum NCTreeViewControllerError: LocalizedError {
case noResult
var errorDescription: String? {
switch self {
case .noResult:
return NSLocalizedString("No Results", comment: "")
}
}
}
//extension NCTreeViewControllerError {
//}
protocol NCSearchableViewController: UISearchResultsUpdating {
var searchController: UISearchController? {get set}
}
extension NCSearchableViewController where Self: UITableViewController {
func setupSearchController(searchResultsController: UIViewController) {
searchController = UISearchController(searchResultsController: searchResultsController)
searchController?.searchBar.searchBarStyle = UISearchBarStyle.default
searchController?.searchResultsUpdater = self
searchController?.searchBar.barStyle = UIBarStyle.black
searchController?.searchBar.isTranslucent = false
searchController?.hidesNavigationBarDuringPresentation = false
tableView.backgroundView = UIView()
tableView.tableHeaderView = searchController?.searchBar
definesPresentationContext = true
}
}
class NCTreeViewController: UITableViewController, TreeControllerDelegate, NCAPIController {
var accountChangeObserver: NotificationObserver?
var becomeActiveObserver: NotificationObserver?
var refreshHandler: NCActionHandler<UIRefreshControl>?
var treeController: TreeController?
override func viewDidLoad() {
super.viewDidLoad()
tableView.backgroundColor = UIColor.background
tableView.estimatedRowHeight = tableView.rowHeight
tableView.rowHeight = UITableViewAutomaticDimension
treeController = TreeController()
treeController?.delegate = self
treeController?.tableView = tableView
tableView.delegate = treeController
tableView.dataSource = treeController
if let refreshControl = refreshControl {
refreshHandler = NCActionHandler(refreshControl, for: .valueChanged) { [weak self] _ in
self?.reload(cachePolicy: .reloadIgnoringLocalCacheData)
}
}
becomeActiveObserver = NotificationCenter.default.addNotificationObserver(forName: .UIApplicationDidBecomeActive, object: nil, queue: nil) { [weak self] _ in
self?.reloadIfNeeded()
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
reloadIfNeeded()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
if let context = NCCache.sharedCache?.viewContext, context.hasChanges {
try? context.save()
}
}
//MARK: - NCAPIController
var accountChangeAction: AccountChangeAction = .none {
didSet {
switch accountChangeAction {
case .none:
accountChangeObserver = nil
case .reload:
accountChangeObserver = NotificationCenter.default.addNotificationObserver(forName: .NCCurrentAccountChanged, object: nil, queue: nil) { [weak self] _ in
self?.reload()
}
case .update:
accountChangeObserver = NotificationCenter.default.addNotificationObserver(forName: .NCCurrentAccountChanged, object: nil, queue: nil) { [weak self] _ in
self?.updateContent()
}
}
}
}
var isLoading: Bool = false
lazy var dataManager: NCDataManager = NCDataManager(account: NCAccount.current)
// func updateContent(completionHandler: @escaping () -> Void) {
// completionHandler()
// }
func content() -> Future<TreeNode?> {
return .init(.failure(NCTreeViewControllerError.noResult))
}
@discardableResult func updateContent() -> Future<TreeNode?> {
return content().then(on: .main) { content -> TreeNode? in
self.tableView.backgroundView = nil
self.treeController?.content = content
return content
}.catch(on: .main) { error in
self.tableView.backgroundView = NCTableViewBackgroundLabel(text: error.localizedDescription)
}
}
// func reload(cachePolicy: URLRequest.CachePolicy, completionHandler: @escaping ([NCCacheRecord]) -> Void ) {
// completionHandler([])
// }
func load(cachePolicy: URLRequest.CachePolicy) -> Future<[NCCacheRecord]> {
return .init([])
}
func didStartLoading() {
tableView.backgroundView = nil
}
func didFailLoading(error: Error) {
treeController?.content = nil
tableView.backgroundView = NCTableViewBackgroundLabel(text: error.localizedDescription)
if let refreshControl = refreshControl, refreshControl.isRefreshing {
refreshControl.endRefreshing()
}
}
func didFinishLoading() {
if let refreshControl = refreshControl, refreshControl.isRefreshing {
refreshControl.endRefreshing()
}
}
var managedObjectsObserver: NCManagedObjectObserver?
lazy var updateGate = NCGate()
var updateWork: DispatchWorkItem?
var expireDate: Date?
//MARK: - TreeControllerDelegate
func treeController(_ treeController: TreeController, didSelectCellWithNode node: TreeNode) {
if (!isEditing && !tableView.allowsMultipleSelection) || (isEditing && !tableView.allowsMultipleSelectionDuringEditing) {
treeController.deselectCell(for: node, animated: true)
if let route = (node as? TreeNodeRoutable)?.route {
route.perform(source: self, sender: treeController.cell(for: node))
}
}
else {
if isEditing && (self as TreeControllerDelegate).treeController?(treeController, editActionsForNode: node) == nil {
treeController.deselectCell(for: node, animated: true)
if let route = (node as? TreeNodeRoutable)?.route {
route.perform(source: self, sender: treeController.cell(for: node))
}
}
}
}
func treeController(_ treeController: TreeController, didDeselectCellWithNode node: TreeNode) {
}
func treeController(_ treeController: TreeController, accessoryButtonTappedWithNode node: TreeNode) {
if let route = (node as? TreeNodeRoutable)?.accessoryButtonRoute {
route.perform(source: self, sender: treeController.cell(for: node))
}
}
}
enum AccountChangeAction {
case none
case reload
case update
}
protocol NCAPIController: class {
// func updateContent(completionHandler: @escaping () -> Void)
// func reload(cachePolicy: URLRequest.CachePolicy, completionHandler: @escaping ([NCCacheRecord]) -> Void )
func didStartLoading()
func didFailLoading(error: Error)
func didFinishLoading()
func load(cachePolicy: URLRequest.CachePolicy) -> Future<[NCCacheRecord]>
func content() -> Future<TreeNode?>
@discardableResult func updateContent() -> Future<TreeNode?>
var accountChangeAction: AccountChangeAction {get set}
var isLoading: Bool {get set}
var dataManager: NCDataManager {get set}
var managedObjectsObserver: NCManagedObjectObserver? {get set}
var updateGate: NCGate {get}
var expireDate: Date? {get set}
var updateWork: DispatchWorkItem? {get set}
}
enum NCAPIControllerError: LocalizedError {
case authorizationRequired
case noResult(String?)
var errorDescription: String? {
switch self {
case .authorizationRequired:
return NSLocalizedString("Please Sign In", comment: "")
case let .noResult(message):
return message ?? NSLocalizedString("No Result", comment: "")
}
}
}
extension NCAPIController where Self: UIViewController {
func reloadIfNeeded() {
if let expireDate = expireDate, expireDate < Date() {
reload()
}
}
func reload() {
self.reload(cachePolicy: .useProtocolCachePolicy)
}
fileprivate func delayedUpdate() {
let date = Date()
expireDate = managedObjectsObserver?.objects.compactMap {($0 as? NCCacheRecord)?.expireDate as Date?}.filter {$0 > date}.min()
let progress = NCProgressHandler(viewController: self, totalUnitCount: 1)
updateGate.perform {
DispatchQueue.main.async {
progress.progress.perform {
return self.updateContent()
}
}.wait()
progress.finish()
}
}
func reload(cachePolicy: URLRequest.CachePolicy) {
guard !isLoading else {return}
didStartLoading()
let account = NCAccount.current
guard accountChangeAction != .reload || account != nil else {
didFailLoading(error: NCAPIControllerError.authorizationRequired)
return
}
isLoading = true
dataManager = NCDataManager(account: account, cachePolicy: cachePolicy)
managedObjectsObserver = nil
let progress = NCProgressHandler(viewController: self, totalUnitCount: 2)
progress.progress.perform {
self.load(cachePolicy: cachePolicy).then(on: .main) { records -> Future<TreeNode?> in
let date = Date()
self.expireDate = records.compactMap {$0.expireDate as Date?}.filter {$0 > date}.min()
self.managedObjectsObserver = NCManagedObjectObserver(managedObjects: records) { [weak self] (_,_) in
guard let strongSelf = self else {return}
strongSelf.updateWork?.cancel()
strongSelf.updateWork = DispatchWorkItem {
self?.delayedUpdate()
self?.updateWork = nil
}
DispatchQueue.main.async(execute: strongSelf.updateWork!)
}
return progress.progress.perform { self.updateContent() }
}.then(on: .main) { _ in
self.didFinishLoading()
}.catch(on: .main) { error in
self.didFailLoading(error: error)
}.finally(on: .main) {
progress.finish()
self.isLoading = false
}
//
// self.reload(cachePolicy: cachePolicy) { [weak self] records in
// guard let strongSelf = self else {
// progress.finish()
// return
// }
//
// let date = Date()
// strongSelf.expireDate = records.compactMap {$0.expireDate as Date?}.filter {$0 > date}.min()
//
// progress.progress.perform {
// strongSelf.updateContent {
// progress.finish()
// strongSelf.isLoading = false
// strongSelf.didFinishLoading()
// }
// }
// strongSelf.managedObjectsObserver = NCManagedObjectObserver(managedObjects: records) { [weak self] (_,_) in
// guard let strongSelf = self else {return}
// strongSelf.updateWork?.cancel()
// strongSelf.updateWork = DispatchWorkItem {
// self?.delayedUpdate()
// self?.updateWork = nil
// }
// DispatchQueue.main.async(execute: strongSelf.updateWork!)
// }
// }
}
}
}
extension NCAPIController where Self: NCTreeViewController {
func reloadIfNeeded() {
if treeController?.content == nil || (expireDate ?? Date.distantFuture) < Date() {
reload()
}
}
}
|
1cf66224e83e00a3615e33e2ad67204a
| 28.767442 | 159 | 0.732129 | false | false | false | false |
noppoMan/aws-sdk-swift
|
refs/heads/main
|
Sources/Soto/Services/Kendra/Kendra_Error.swift
|
apache-2.0
|
1
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import SotoCore
/// Error enum for Kendra
public struct KendraErrorType: AWSErrorType {
enum Code: String {
case accessDeniedException = "AccessDeniedException"
case conflictException = "ConflictException"
case internalServerException = "InternalServerException"
case resourceAlreadyExistException = "ResourceAlreadyExistException"
case resourceInUseException = "ResourceInUseException"
case resourceNotFoundException = "ResourceNotFoundException"
case resourceUnavailableException = "ResourceUnavailableException"
case serviceQuotaExceededException = "ServiceQuotaExceededException"
case throttlingException = "ThrottlingException"
case validationException = "ValidationException"
}
private let error: Code
public let context: AWSErrorContext?
/// initialize Kendra
public init?(errorCode: String, context: AWSErrorContext) {
guard let error = Code(rawValue: errorCode) else { return nil }
self.error = error
self.context = context
}
internal init(_ error: Code) {
self.error = error
self.context = nil
}
/// return error code string
public var errorCode: String { self.error.rawValue }
public static var accessDeniedException: Self { .init(.accessDeniedException) }
public static var conflictException: Self { .init(.conflictException) }
public static var internalServerException: Self { .init(.internalServerException) }
public static var resourceAlreadyExistException: Self { .init(.resourceAlreadyExistException) }
public static var resourceInUseException: Self { .init(.resourceInUseException) }
public static var resourceNotFoundException: Self { .init(.resourceNotFoundException) }
public static var resourceUnavailableException: Self { .init(.resourceUnavailableException) }
public static var serviceQuotaExceededException: Self { .init(.serviceQuotaExceededException) }
public static var throttlingException: Self { .init(.throttlingException) }
public static var validationException: Self { .init(.validationException) }
}
extension KendraErrorType: Equatable {
public static func == (lhs: KendraErrorType, rhs: KendraErrorType) -> Bool {
lhs.error == rhs.error
}
}
extension KendraErrorType: CustomStringConvertible {
public var description: String {
return "\(self.error.rawValue): \(self.message ?? "")"
}
}
|
2b871d09db514326ea31c896d387b0a6
| 40.405405 | 117 | 0.692559 | false | false | false | false |
barteljan/VISPER
|
refs/heads/master
|
Example/VISPER-Wireframe-Tests/DefaultRouterTests.swift
|
mit
|
1
|
import UIKit
import XCTest
@testable import VISPER_Core
@testable import VISPER_Wireframe
class DefaultRouterTests: XCTestCase {
func testAddLiteralRoute() throws{
let router = DefaultRouter()
let pattern = "/das/ist/ein/test/"
try router.add(routePattern: pattern)
guard router.routeDefinitions.count == 1 else {
XCTFail("There should be exactly one route definition")
return
}
let routeDefinition = router.routeDefinitions[0]
guard routeDefinition.components.count == 4 else {
XCTFail("There should be 4 route components")
return
}
XCTAssertEqual(pattern, routeDefinition.routePattern)
XCTAssertNil(routeDefinition.components[0].name)
XCTAssertEqual(routeDefinition.components[0].string,"das")
XCTAssertEqual(routeDefinition.components[0].type,RouteDefinition.Component.ComponentType.literal)
XCTAssertNil(routeDefinition.components[1].name)
XCTAssertEqual(routeDefinition.components[1].string,"ist")
XCTAssertEqual(routeDefinition.components[1].type,RouteDefinition.Component.ComponentType.literal)
XCTAssertNil(routeDefinition.components[2].name)
XCTAssertEqual(routeDefinition.components[2].string,"ein")
XCTAssertEqual(routeDefinition.components[2].type,RouteDefinition.Component.ComponentType.literal)
XCTAssertNil(routeDefinition.components[3].name)
XCTAssertEqual(routeDefinition.components[3].string,"test")
XCTAssertEqual(routeDefinition.components[3].type,RouteDefinition.Component.ComponentType.literal)
}
func testAddVariableRoute() throws {
let router = DefaultRouter()
let pattern = "/das/ist/:var1/test/"
try router.add(routePattern:pattern)
guard router.routeDefinitions.count == 1 else {
XCTFail("There should be exactly one route definition")
return
}
let routeDefinition = router.routeDefinitions[0]
guard routeDefinition.components.count == 4 else {
XCTFail("There should be 4 route components")
return
}
XCTAssertEqual(pattern, routeDefinition.routePattern)
XCTAssertNil(routeDefinition.components[0].name)
XCTAssertEqual(routeDefinition.components[0].string,"das")
XCTAssertEqual(routeDefinition.components[0].type,RouteDefinition.Component.ComponentType.literal)
XCTAssertNil(routeDefinition.components[1].name)
XCTAssertEqual(routeDefinition.components[1].string,"ist")
XCTAssertEqual(routeDefinition.components[1].type,RouteDefinition.Component.ComponentType.literal)
XCTAssertEqual(routeDefinition.components[2].name,"var1")
XCTAssertNil(routeDefinition.components[2].string)
XCTAssertEqual(routeDefinition.components[2].type,RouteDefinition.Component.ComponentType.variable)
XCTAssertNil(routeDefinition.components[3].name)
XCTAssertEqual(routeDefinition.components[3].string,"test")
XCTAssertEqual(routeDefinition.components[3].type,RouteDefinition.Component.ComponentType.literal)
}
func testAddWildcardRoute() throws {
let router = DefaultRouter()
let pattern = "/das/ist/ein/*"
try router.add(routePattern: pattern)
guard router.routeDefinitions.count == 1 else {
XCTFail("There should be exactly one route definition")
return
}
let routeDefinition = router.routeDefinitions[0]
guard routeDefinition.components.count == 4 else {
XCTFail("There should be 4 route components")
return
}
XCTAssertEqual(pattern, routeDefinition.routePattern)
XCTAssertNil(routeDefinition.components[0].name)
XCTAssertEqual(routeDefinition.components[0].string,"das")
XCTAssertEqual(routeDefinition.components[0].type,RouteDefinition.Component.ComponentType.literal)
XCTAssertNil(routeDefinition.components[1].name)
XCTAssertEqual(routeDefinition.components[1].string,"ist")
XCTAssertEqual(routeDefinition.components[1].type,RouteDefinition.Component.ComponentType.literal)
XCTAssertNil(routeDefinition.components[2].name)
XCTAssertEqual(routeDefinition.components[2].string,"ein")
XCTAssertEqual(routeDefinition.components[2].type,RouteDefinition.Component.ComponentType.literal)
XCTAssertNil(routeDefinition.components[3].name)
XCTAssertNil(routeDefinition.components[3].string)
XCTAssertEqual(routeDefinition.components[3].type,RouteDefinition.Component.ComponentType.wildcard)
}
func testAddWrongWildcardRoute() throws {
let router = DefaultRouter()
do {
try router.add(routePattern: "/das/ist/*/Test")
XCTFail("Add Route should throw an exception in that case")
} catch DefautRouterError.wildcardNotAtTheEndOfPattern {
XCTAssert(true)
}
}
func testCorrectRouteWithLiteral() throws {
let router = DefaultRouter()
let pattern = "/das/ist/ein/test/"
try router.add(routePattern: pattern)
let url = URL(string: pattern)!
if let result = try router.route(url:url) {
XCTAssertEqual(result.routePattern, pattern)
XCTAssert(result.parameters.count == 4)
XCTAssertEqual(result.parameters[DefaultRouter.parametersRoutePatternKey] as! String?, pattern)
XCTAssertEqual(result.parameters[DefaultRouter.parametersJLRoutePatternKey] as! String?, pattern)
XCTAssertEqual(result.parameters[DefaultRouter.parametersRouteURLKey] as! URL?, url)
XCTAssertEqual(result.parameters[DefaultRouter.parametersJLRouteURLKey] as! URL?, url)
} else {
XCTFail("router should give an result")
}
}
func testWrongRouteWithLiteral() throws {
let router = DefaultRouter()
let pattern = "/das/ist/ein/test/"
try router.add(routePattern: pattern)
let url = URL(string: "/das/hier/ist/falsch")!
let result = try router.route(url:url)
XCTAssertNil(result)
}
func testWrongRouteWithToLongLiteral() throws {
let router = DefaultRouter()
let pattern = "/das/ist/ein/test/"
try router.add(routePattern: pattern)
let url = URL(string: "/das/ist/ein/test/aber/einer/der/zu/Lang/ist")!
let result = try router.route(url:url)
XCTAssertNil(result)
}
func testWrongRouteWithToShortLiteral() throws {
let router = DefaultRouter()
let pattern = "/das/ist/ein/test/"
try router.add(routePattern: pattern)
let url = URL(string: "/das/ist/ein")!
let result = try router.route(url:url)
XCTAssertNil(result)
}
func testCorrectRouteWithVar() throws {
let router = DefaultRouter()
let pattern = "/das/ist/:var1/test/"
try router.add(routePattern: pattern)
let url = URL(string: "/das/ist/ein/test/")!
if let result = try router.route(url:url) {
XCTAssertEqual(result.routePattern, pattern)
XCTAssert(result.parameters.count == 5)
XCTAssertEqual(result.parameters[DefaultRouter.parametersRoutePatternKey] as! String?, pattern)
XCTAssertEqual(result.parameters[DefaultRouter.parametersJLRoutePatternKey] as! String?, pattern)
XCTAssertEqual(result.parameters[DefaultRouter.parametersRouteURLKey] as! URL?, url)
XCTAssertEqual(result.parameters[DefaultRouter.parametersJLRouteURLKey] as! URL?, url)
XCTAssertEqual(result.parameters["var1"] as! String?, "ein")
} else {
XCTFail("router should give an result")
}
}
func testWrongRouteWithToLongVar() throws {
let router = DefaultRouter()
let pattern = "/das/ist/:var1/test/"
try router.add(routePattern: pattern)
let url = URL(string: "/das/ist/ein/test/aber/einer/der/zu/Lang/ist")!
let result = try router.route(url:url)
XCTAssertNil(result)
}
func testWrongRouteWithToShortVar() throws {
let router = DefaultRouter()
let pattern = "/das/ist/:var1/test/"
try router.add(routePattern: pattern)
let url = URL(string: "/das/ist/ein")!
let result = try router.route(url:url)
XCTAssertNil(result)
}
func testCorrectRouteWithWildcard() throws {
let router = DefaultRouter()
let pattern = "/das/ist/ein/*"
try router.add(routePattern: pattern)
let url = URL(string: "/das/ist/ein/test")!
if let result = try router.route(url:url) {
XCTAssertEqual(result.routePattern, pattern)
XCTAssert(result.parameters.count == 5)
XCTAssertEqual(result.parameters[DefaultRouter.parametersRoutePatternKey] as! String?, pattern)
XCTAssertEqual(result.parameters[DefaultRouter.parametersJLRoutePatternKey] as! String?, pattern)
XCTAssertEqual(result.parameters[DefaultRouter.parametersRouteURLKey] as! URL?, url)
XCTAssertEqual(result.parameters[DefaultRouter.parametersJLRouteURLKey] as! URL?, url)
if let wildcardParams = result.parameters[DefaultRouter.parametersWildcardKey] as? [String]{
if wildcardParams.count == 1 {
XCTAssertEqual(wildcardParams[0], "test")
} else {
XCTFail("wildcard parameter shoult be an array of count 1")
}
} else {
XCTFail("parameters do not contain wildcard key")
}
//XCTAssertEqual(result.parameters["*"] as! [String : String]?, "ein")
} else {
XCTFail("router should give an result")
}
}
func testCorrectRouteWithLongWildcard() throws {
let router = DefaultRouter()
let pattern = "/das/ist/ein/*"
try router.add(routePattern: pattern)
let url = URL(string: "/das/ist/ein/test/der/lang/ist")!
if let result = try router.route(url:url) {
XCTAssertEqual(result.routePattern, pattern)
XCTAssert(result.parameters.count == 5)
XCTAssertEqual(result.parameters[DefaultRouter.parametersRoutePatternKey] as! String?, pattern)
XCTAssertEqual(result.parameters[DefaultRouter.parametersJLRoutePatternKey] as! String?, pattern)
XCTAssertEqual(result.parameters[DefaultRouter.parametersRouteURLKey] as! URL?, url)
XCTAssertEqual(result.parameters[DefaultRouter.parametersJLRouteURLKey] as! URL?, url)
if let wildcardParams = result.parameters[DefaultRouter.parametersWildcardKey] as? [String]{
if wildcardParams.count == 4 {
XCTAssertEqual(wildcardParams[0], "test")
XCTAssertEqual(wildcardParams[1], "der")
XCTAssertEqual(wildcardParams[2], "lang")
XCTAssertEqual(wildcardParams[3], "ist")
} else {
XCTFail("wildcard parameter shoult be an array of count 4")
}
} else {
XCTFail("parameters do not contain wildcard key")
}
//XCTAssertEqual(result.parameters["*"] as! [String : String]?, "ein")
} else {
XCTFail("router should give an result")
}
}
func testWrongToShortRouteWithWildcard() throws {
let router = DefaultRouter()
let pattern = "/das/ist/ein/*/"
try router.add(routePattern: pattern)
let url = URL(string: "/das/ist/ein")!
let result = try router.route(url:url)
XCTAssertNil(result)
}
func testResolveLastAddedRouteFirst() throws {
let router = DefaultRouter()
let pattern1 = "/das/ist/ein/:var1"
try router.add(routePattern:pattern1)
let pattern2 = "/das/ist/ein/:var2"
try router.add(routePattern:pattern2)
let url = URL(string: "/das/ist/ein/test/")!
if let result = try router.route(url:url) {
XCTAssertEqual(result.routePattern, pattern2)
XCTAssert(result.parameters.count == 5)
XCTAssertEqual(result.parameters[DefaultRouter.parametersRoutePatternKey] as! String?, pattern2)
XCTAssertEqual(result.parameters[DefaultRouter.parametersJLRoutePatternKey] as! String?, pattern2)
XCTAssertEqual(result.parameters[DefaultRouter.parametersRouteURLKey] as! URL?, url)
XCTAssertEqual(result.parameters[DefaultRouter.parametersJLRouteURLKey] as! URL?, url)
XCTAssertEqual(result.parameters["var2"] as! String?, "test")
} else {
XCTFail("router should give an result")
}
}
func testParamsAreMerged() throws {
let router = DefaultRouter()
let pattern1 = "/das/ist/ein/:var1"
try router.add(routePattern:pattern1)
let url = URL(string: "/das/ist/ein/test/")!
if let result = try router.route(url:url, parameters: ["id" : "55"]) {
XCTAssertEqual(result.routePattern, pattern1)
XCTAssert(result.parameters.count == 6)
XCTAssertEqual(result.parameters[DefaultRouter.parametersRoutePatternKey] as! String?, pattern1)
XCTAssertEqual(result.parameters[DefaultRouter.parametersJLRoutePatternKey] as! String?, pattern1)
XCTAssertEqual(result.parameters[DefaultRouter.parametersRouteURLKey] as! URL?, url)
XCTAssertEqual(result.parameters[DefaultRouter.parametersJLRouteURLKey] as! URL?, url)
XCTAssertEqual(result.parameters["var1"] as? String, "test")
XCTAssertEqual(result.parameters["id"] as? String, "55")
} else {
XCTFail("router should give an result")
}
}
func testExternalParamsOverwriteParamsExtractedFromTheRouteMerged() throws {
let router = DefaultRouter()
let pattern1 = "/das/ist/ein/:var1"
try router.add(routePattern:pattern1)
let url = URL(string: "/das/ist/ein/test/")!
if let result = try router.route(url:url, parameters: ["var1" : "55"]) {
XCTAssertEqual(result.routePattern, pattern1)
XCTAssert(result.parameters.count == 5)
XCTAssertEqual(result.parameters[DefaultRouter.parametersRoutePatternKey] as! String?, pattern1)
XCTAssertEqual(result.parameters[DefaultRouter.parametersJLRoutePatternKey] as! String?, pattern1)
XCTAssertEqual(result.parameters[DefaultRouter.parametersRouteURLKey] as! URL?, url)
XCTAssertEqual(result.parameters[DefaultRouter.parametersJLRouteURLKey] as! URL?, url)
XCTAssertEqual(result.parameters["var1"] as? String, "55")
} else {
XCTFail("router should give an result")
}
}
}
|
55418e8a149b9d377bdf7b2f343e86cd
| 38.01467 | 110 | 0.617723 | false | true | false | false |
vincent-cheny/DailyRecord
|
refs/heads/master
|
DailyRecord/TemplateViewController.swift
|
gpl-2.0
|
1
|
//
// TemplateViewController.swift
// DailyRecord
//
// Created by ChenYong on 16/2/12.
// Copyright © 2016年 LazyPanda. All rights reserved.
//
import UIKit
import RealmSwift
class TemplateViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var templateFilterBtn: UIBarButtonItem!
@IBOutlet weak var templateTableView: UITableView!
typealias sendValueClosure = (type: String, content: String)->Void
var myClosure: sendValueClosure?
var templateType = ""
let realm = try! Realm()
var recordTemplates = try! Realm().objects(RecordTemplate).sorted("id")
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let backItem = UIBarButtonItem()
backItem.title = ""
self.navigationItem.backBarButtonItem = backItem
templateTableView.delegate = self
templateTableView.dataSource = self
// 解决底部多余行问题
templateTableView.tableFooterView = UIView(frame: CGRectZero)
templateType = templateFilterBtn.title!
updateRecordTemplates(templateFilterBtn.title!)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.navigationBarHidden = false;
templateTableView.reloadData()
}
func initWithClosure(closure: sendValueClosure){
myClosure = closure
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let templateCell = tableView.dequeueReusableCellWithIdentifier("templateCell", forIndexPath: indexPath)
let template = recordTemplates[indexPath.row]
let imageView = templateCell.viewWithTag(1) as! UIImageView
let title = templateCell.viewWithTag(2) as! UILabel
let type = templateCell.viewWithTag(3) as! UILabel
let content = templateCell.viewWithTag(4) as! UILabel
title.text = template.title
type.text = template.type
content.text = template.content
switch template.type {
case "黑业":
imageView.image = UIImage(named: "blackdot")
title.textColor = UIColor.blackColor()
type.textColor = UIColor.blackColor()
case "白业":
imageView.image = UIImage(named: "whitedot")
title.textColor = UIColor.whiteColor()
type.textColor = UIColor.whiteColor()
case "黑业对治":
imageView.image = UIImage(named: "greendot")
title.textColor = UIColor.greenColor()
type.textColor = UIColor.greenColor()
case "白业对治":
imageView.image = UIImage(named: "reddot")
title.textColor = UIColor.redColor()
type.textColor = UIColor.redColor()
default:
break
}
// 解决左对齐问题
templateCell.layoutMargins = UIEdgeInsetsZero
templateCell.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(longPressCell(_:))))
return templateCell
}
func longPressCell(recognizer: UIGestureRecognizer) {
if recognizer.state == .Began {
let indexPath = templateTableView.indexPathForRowAtPoint(recognizer.locationInView(templateTableView))
let alert = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "编辑", style: UIAlertActionStyle.Default, handler: { (UIAlertAction) -> Void in
self.navigateTemplate(indexPath!)
}))
alert.addAction(UIAlertAction(title: "取消", style: UIAlertActionStyle.Default, handler: nil))
alert.addAction(UIAlertAction(title: "删除", style: UIAlertActionStyle.Destructive, handler: { (UIAlertAction) -> Void in
try! self.realm.write {
self.realm.delete(self.recordTemplates[indexPath!.row])
}
self.templateTableView.reloadData()
}))
self.presentViewController(alert, animated: true, completion: nil)
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return recordTemplates.count
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// 模拟闪动效果
tableView.deselectRowAtIndexPath(indexPath, animated: true)
if self.myClosure != nil {
let template = recordTemplates[indexPath.row]
if template.type == templateType {
myClosure!(type: template.type, content: template.content)
navigationController?.popViewControllerAnimated(true)
} else {
let alert = UIAlertController(title: "请选择" + templateType, message: "", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "确定", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
} else {
navigateTemplate(indexPath)
}
}
func navigateTemplate(indexPath: NSIndexPath) {
let addTemplateViewController = storyboard?.instantiateViewControllerWithIdentifier("AddTemplateViewController") as! AddTemplateViewController
addTemplateViewController.templateId = recordTemplates[indexPath.row].id
navigationController?.pushViewController(addTemplateViewController, animated: true)
}
@IBAction func templateFilter(sender: AnyObject) {
let alert = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.Alert)
filterData(alert, filter: "全部")
filterData(alert, filter: "黑业")
filterData(alert, filter: "黑业对治")
filterData(alert, filter: "白业")
filterData(alert, filter: "白业对治")
self.presentViewController(alert, animated: true, completion: nil)
}
func filterData(alert: UIAlertController, filter: String) {
alert.addAction(UIAlertAction(title: filter, style: UIAlertActionStyle.Default, handler: { (UIAlertAction) -> Void in
self.updateRecordTemplates(filter)
self.templateTableView.reloadData()
}))
}
func updateRecordTemplates(filter: String) {
self.templateFilterBtn.title = filter
if filter == "全部" {
self.recordTemplates = self.realm.objects(RecordTemplate).sorted("id")
} else {
self.recordTemplates = self.realm.objects(RecordTemplate).filter("type = %@", filter).sorted("id")
}
}
}
|
27cda4783831cbd9639275c358a790a1
| 41.981366 | 150 | 0.659199 | false | false | false | false |
aestusLabs/ASChatApp
|
refs/heads/master
|
ChatButton.swift
|
mit
|
1
|
//
// ChatButton.swift
// ChatAppOrigionalFiles
//
// Created by Ian Kohlert on 2017-07-19.
// Copyright © 2017 aestusLabs. All rights reserved.
//
import Foundation
import UIKit
class ChatButton: UIButton {
var buttonTag: WidgetTagNames = .error
let gradient = CAGradientLayer()
override init (frame: CGRect) {
super.init(frame: frame)
self.layer.shadowColor = UIColor.lightGray.cgColor
self.layer.shadowOpacity = 0.25
self.layer.shadowOffset = CGSize(width: 2, height: 4)
self.layer.shadowRadius = 4
// gradient.frame = self.bounds
//
// let red = UIColor(red: 1.0, green: 0.28627451, blue: 0.568627451, alpha: 1.0)
// let orange = UIColor(red: 1.0, green: 0.462745098, blue: 0.462745098, alpha: 1.0)
// gradient.colors = [red.cgColor, orange.cgColor]
//
// gradient.startPoint = CGPoint.zero
// gradient.endPoint = CGPoint(x: 1, y: 1)
// self.layer.insertSublayer(gradient, at: 0)
// self.layer.borderColor = appColours.getMainAppColour().cgColor
// self.layer.borderWidth = 1
self.backgroundColor = appColours.getMainAppColour() //UIColor.white
self.layer.cornerRadius = 18
self.setTitleColor(UIColor.white, for: .normal)
self.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: UIFontWeightBold)
}
required init(coder aDecoder: NSCoder) {
fatalError("This class does not support NSCoding")
}
}
func createChatButton(text: String, tag: WidgetTagNames) -> ChatButton{
let button = ChatButton(frame: CGRect(x: 0, y: 0, width: 250, height: 40))
button.setTitle(text, for: .normal)
button.buttonTag = tag
return button
}
|
a044a08d1f868a7eabd85eda184d4c25
| 30.732143 | 91 | 0.639842 | false | false | false | false |
logansease/SeaseAssist
|
refs/heads/master
|
Pod/Classes/UITextField+BottomBorder.swift
|
mit
|
1
|
//
// UITextField+BottomBorder.swift
// SeaseAssist
//
// Created by lsease on 5/16/17.
// Copyright © 2017 Logan Sease. All rights reserved.
//
import UIKit
@objc public extension UITextField {
@objc func setBottomBorder(color: UIColor = UIColor(hex: "A5A5A5")) {
self.borderStyle = .none
self.layer.backgroundColor = UIColor.white.cgColor
self.layer.masksToBounds = false
self.layer.shadowColor = color.cgColor
self.layer.shadowOffset = CGSize(width: 0.0, height: 1.0)
self.layer.shadowOpacity = 0.5
self.layer.shadowRadius = 0.0
}
}
|
13c0916745c7db22e5deb39ac208010f
| 26.909091 | 72 | 0.656352 | false | false | false | false |
WaterReporter/WaterReporter-iOS
|
refs/heads/master
|
WaterReporter/WaterReporter/Endpoints.swift
|
agpl-3.0
|
1
|
//
// Endpoints.swift
// WaterReporter
//
// Created by Viable Industries on 7/25/16.
// Copyright © 2016 Viable Industries, L.L.C. All rights reserved.
//
import Foundation
struct Endpoints {
static let GET_MANY_REPORTS = "https://api.waterreporter.org/v2/data/report"
static let POST_REPORT = "https://api.waterreporter.org/v2/data/report"
static let GET_MANY_REPORT_LIKES = "https://api.waterreporter.org/v2/data/like"
static let POST_LIKE = "https://api.waterreporter.org/v2/data/like"
static let DELETE_LIKE = "https://api.waterreporter.org/v2/data/like"
static let GET_MANY_USER = "https://api.waterreporter.org/v2/data/user"
static let POST_AUTH_REMOTE = "https://api.waterreporter.org/v2/auth/remote"
static let GET_AUTH_AUTHORIZE = "https://www.waterreporter.org/authorize"
static let GET_USER_ME = "https://api.waterreporter.org/v2/data/me"
static let POST_USER_REGISTER = "https://api.waterreporter.org/v2/user/register"
static let GET_USER_PROFILE = "https://api.waterreporter.org/v2/data/user/"
static let GET_USER_SNAPSHOT = "https://api.waterreporter.org/v2/data/snapshot/user/"
static let POST_USER_PROFILE = "https://api.waterreporter.org/v2/data/user/"
static let POST_PASSWORD_RESET = "https://api.waterreporter.org/v2/reset"
static let POST_IMAGE = "https://api.waterreporter.org/v2/media/image"
static let GET_MANY_ORGANIZATIONS = "https://api.waterreporter.org/v2/data/organization"
static let GET_MANY_REPORT_COMMENTS = "https://api.waterreporter.org/v2/data/comment"
static let POST_COMMENT = "https://api.waterreporter.org/v2/data/comment"
static let GET_MANY_HASHTAGS = "https://api.waterreporter.org/v2/data/hashtag"
static let GET_MANY_TERRITORY = "https://api.waterreporter.org/v2/data/territory"
static let GET_MANY_HUC8WATERSHEDS = "https://api.waterreporter.org/v2/data/huc-8"
static let TRENDING_GROUP = "https://api.waterreporter.org/v2/data/trending/group"
static let TRENDING_HASHTAG = "https://api.waterreporter.org/v2/data/trending/hashtag"
static let TRENDING_PEOPLE = "https://api.waterreporter.org/v2/data/trending/people"
static let TRENDING_TERRITORY = "https://api.waterreporter.org/v2/data/trending/territory"
static let TERRITORY = "https://huc.waterreporter.org/8/"
//
//
//
var apiUrl: String! = "https://api.waterreporter.org/v2/data"
func getManyReportComments(reportId: AnyObject) -> String {
let _endpoint = apiUrl,
_reportId = String(reportId)
return _endpoint + "/report/" + _reportId + "/comments"
}
}
|
32a88113581c2c89616effe93fda7fa3
| 41 | 94 | 0.69308 | false | false | false | false |
rbaladron/SwiftProgramaParaiOS
|
refs/heads/master
|
Ejercicios/precedenciaDeOperadores.playground/Contents.swift
|
mit
|
1
|
//: Playground - noun: a place where people can play
import UIKit
var numeroDeVidas = 5
numeroDeVidas++
numeroDeVidas
numeroDeVidas += 1
++numeroDeVidas
--numeroDeVidas
-numeroDeVidas
var esDeDia = true
!esDeDia
let numero : Int = 874 % 10
300 - 201 * 9 % 6 / 8
201 * 9
1809 % 6
var infinito = !true
var contador = 9
contador = contador++
var puntos = 15 - 7
++puntos
var inicial = 200
var final = -(--inicial)
print( final )
let pesos = 10
let dolares = 17.15
let conversion :Double = Double(pesos) * dolares
let a = 5
var f = 2
let z = 3
print(" Resultado : \( a % ++f * z)")
|
8dc40630a203540695e8dd2fb2442fd2
| 11.913043 | 52 | 0.662732 | false | false | false | false |
tadasz/MistikA
|
refs/heads/master
|
MistikA/Classes/FindPalepeViewController.swift
|
mit
|
1
|
//
// FindPalepeViewController.swift
// MistikA
//
// Created by Tadas Ziemys on 11/07/14.
// Copyright (c) 2014 Tadas Ziemys. All rights reserved.
//
import UIKit
import MapKit
class FindPalepeViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var pictureView: UIImageView?
@IBOutlet weak var accuracyLabel: UILabel?
var locationManager = CLLocationManager()
var region = CLBeaconRegion(proximityUUID: NSUUID(UUIDString: "78E408FD-48DA-4325-9123-0AEA40925EFF")!, identifier: "com.identifier")
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
locationManager.delegate = self
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
locationManager.startRangingBeaconsInRegion(region)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// #pragma 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 locationManager(manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], inRegion region: CLBeaconRegion) {
if !beacons.isEmpty {
var beacon = beacons[0] as! CLBeacon
let accuracy: Double = beacon.accuracy
pictureView!.alpha = CGFloat(1.0 / accuracy)
accuracyLabel!.text = "\(beacon.accuracy)"
if beacon.proximity == CLProximity.Immediate {
locationManager.stopMonitoringForRegion(region)
UIAlertView(title: "Rrrrr...", message: "kaip tu mane radai? rrr....", delegate: self, cancelButtonTitle: "rrrr")
}
}
}
}
|
872531835cab007a4aabdb2ce300e872
| 30.208333 | 137 | 0.646195 | false | false | false | false |
apple/swift-format
|
refs/heads/main
|
Tests/SwiftFormatPrettyPrintTests/BinaryOperatorExprTests.swift
|
apache-2.0
|
1
|
final class BinaryOperatorExprTests: PrettyPrintTestCase {
func testNonRangeFormationOperatorsAreSurroundedByBreaks() {
let input =
"""
x=1+8-9 ^*^ 5*4/10
"""
let expected80 =
"""
x = 1 + 8 - 9 ^*^ 5 * 4 / 10
"""
assertPrettyPrintEqual(input: input, expected: expected80, linelength: 80)
let expected10 =
"""
x =
1 + 8
- 9
^*^ 5
* 4 / 10
"""
assertPrettyPrintEqual(input: input, expected: expected10, linelength: 10)
}
func testRangeFormationOperatorsAreCompactedWhenPossible() {
let input =
"""
x = 1...100
x = 1..<100
x = (1++)...(-100)
x = 1 ... 100
x = 1 ..< 100
x = (1++) ... (-100)
"""
let expected =
"""
x = 1...100
x = 1..<100
x = (1++)...(-100)
x = 1...100
x = 1..<100
x = (1++)...(-100)
"""
assertPrettyPrintEqual(input: input, expected: expected, linelength: 80)
}
func testRangeFormationOperatorsAreNotCompactedWhenFollowingAPostfixOperator() {
let input =
"""
x = 1++ ... 100
x = 1-- ..< 100
x = 1++ ... 100
x = 1-- ..< 100
"""
let expected80 =
"""
x = 1++ ... 100
x = 1-- ..< 100
x = 1++ ... 100
x = 1-- ..< 100
"""
assertPrettyPrintEqual(input: input, expected: expected80, linelength: 80)
let expected10 =
"""
x =
1++
... 100
x =
1--
..< 100
x =
1++
... 100
x =
1--
..< 100
"""
assertPrettyPrintEqual(input: input, expected: expected10, linelength: 10)
}
func testRangeFormationOperatorsAreNotCompactedWhenPrecedingAPrefixOperator() {
let input =
"""
x = 1 ... -100
x = 1 ..< -100
x = 1 ... √100
x = 1 ..< √100
"""
let expected80 =
"""
x = 1 ... -100
x = 1 ..< -100
x = 1 ... √100
x = 1 ..< √100
"""
assertPrettyPrintEqual(input: input, expected: expected80, linelength: 80)
let expected10 =
"""
x =
1
... -100
x =
1
..< -100
x =
1
... √100
x =
1
..< √100
"""
assertPrettyPrintEqual(input: input, expected: expected10, linelength: 10)
}
func testRangeFormationOperatorsAreNotCompactedWhenUnaryOperatorsAreOnEachSide() {
let input =
"""
x = 1++ ... -100
x = 1-- ..< -100
x = 1++ ... √100
x = 1-- ..< √100
"""
let expected80 =
"""
x = 1++ ... -100
x = 1-- ..< -100
x = 1++ ... √100
x = 1-- ..< √100
"""
assertPrettyPrintEqual(input: input, expected: expected80, linelength: 80)
let expected10 =
"""
x =
1++
... -100
x =
1--
..< -100
x =
1++
... √100
x =
1--
..< √100
"""
assertPrettyPrintEqual(input: input, expected: expected10, linelength: 10)
}
func testRangeFormationOperatorsAreNotCompactedWhenPrecedingPrefixDot() {
let input =
"""
x = .first ... .last
x = .first ..< .last
x = .first ... .last
x = .first ..< .last
"""
let expected80 =
"""
x = .first ... .last
x = .first ..< .last
x = .first ... .last
x = .first ..< .last
"""
assertPrettyPrintEqual(input: input, expected: expected80, linelength: 80)
let expected10 =
"""
x =
.first
... .last
x =
.first
..< .last
x =
.first
... .last
x =
.first
..< .last
"""
assertPrettyPrintEqual(input: input, expected: expected10, linelength: 10)
}
}
|
f645b956dc651a433738cb7ca580b377
| 17.300469 | 84 | 0.43843 | false | false | false | false |
elpassion/el-space-ios
|
refs/heads/master
|
ELSpace/Commons/Extensions/UIColor/UIColor_Hex.swift
|
gpl-3.0
|
1
|
import UIKit
extension UIColor {
convenience init?(hexRed red: Int, green: Int, blue: Int, alpha: Int = 255) {
guard red >= 0 && red <= 255 else { return nil }
guard green >= 0 && green <= 255 else { return nil }
guard blue >= 0 && blue <= 255 else { return nil }
self.init(red: CGFloat(red) / 255.0,
green: CGFloat(green) / 255.0,
blue: CGFloat(blue) / 255.0,
alpha: CGFloat(alpha) / 255.0)
}
convenience init?(hexString: String) {
let hex = hexString.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
var int = UInt32()
Scanner(string: hex).scanHexInt32(&int)
let red, green, blue, alpha: UInt32
switch hex.count {
case 3: // RGB (12-bit)
(alpha, red, green, blue) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
case 6: // RGB (24-bit)
(alpha, red, green, blue) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
case 8: // ARGB (32-bit)
(alpha, red, green, blue) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
default:
return nil
}
self.init(hexRed: Int(red), green: Int(green), blue: Int(blue), alpha: Int(alpha))
}
}
|
2ac43799296228d793da1cd8c8ddc438
| 37.382353 | 103 | 0.520307 | false | false | false | false |
jcfausto/transit-app
|
refs/heads/master
|
TransitApp/TransitApp/RouteSegmentButton.swift
|
mit
|
1
|
//
// RouteSegmentButtom.swift
// TransitApp
//
// Created by Julio Cesar Fausto on 27/02/16.
// Copyright © 2016 Julio Cesar Fausto. All rights reserved.
//
import Foundation
import UIKit
import SVGKit
/**
This is an UIButton capable of retrieve an SVG from some URL, convert it
to an image and assign it as its own image for the normal state.
It is dependable on the SVGKit framework
*/
@IBDesignable
class RouteSegmentButton: UIButton {
// MARK: Properties
/**
The shape's icon url. If presente, this icon
will be drawed into the button
*/
@IBInspectable var svgIconUrl: NSURL?
/**
The shape's color
*/
@IBInspectable var fillColor: UIColor?
/**
This button is designed primarily to be placed inside a view that
will contain a collection of this buttons. This property can store
a index refecence indicating in wich index it resides inside a collection
*/
@IBInspectable var index: Int = 0
/**
The SVG cache manager
*/
let cache = SVGIconCache()
func retrieveSvgFromCache(stringUrl: NSURL) -> NSData? {
if let fileName = stringUrl.lastPathComponent {
return cache.retrieveSVG(fileName)
} else {
return nil
}
}
// MARK: Custom Draw
override func drawRect(rect: CGRect) {
if let svgIconUrl = self.svgIconUrl {
//This must be done in background because of the relationship with the SVGCache that sometimes
//will perform a file read from the disk and if this occurs in the main thread the UI will block
//until the file finishes loading
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
let svgData = self.retrieveSvgFromCache(svgIconUrl)
if let svgData = svgData {
self.drawSvg(svgData, rect: rect)
} else {
self.loadAndDrawSvgForTheFirstTime(svgIconUrl, rect: rect)
}
}
}
}
// MARK: SVG Drawing
func loadAndDrawSvgForTheFirstTime(svgIconUrl: NSURL, rect: CGRect) {
if let svgIconUrl: NSURL = svgIconUrl {
let request = NSURLRequest(URL: svgIconUrl)
//This is asynchronous. When the download completes, the sgv image will be converted and drawed into the button
let getSvgResourceTask = NSURLSession.sharedSession().dataTaskWithRequest(request){ data, response, error in
if let svgData = data as NSData? {
if let fileName = svgIconUrl.lastPathComponent {
self.cache.saveSVG(svgData, fileName: fileName)
}
self.drawSvg(svgData, rect: rect)
}
}
getSvgResourceTask.resume()
}
}
func drawSvg(svgData: NSData, rect: CGRect) {
let svgSource = SVGKSource(inputSteam: NSInputStream(data: svgData))
let svgParsed = SVGKParser.parseSourceUsingDefaultSVGKParser(svgSource)
let svgImage = SVGKImage(parsedSVG: svgParsed, fromSource: svgSource)
//Fill the SVG sublayers with the segment color
let svgImageView = SVGKLayeredImageView(SVGKImage: svgImage)
let layer = svgImageView.layer
self.changeFillColorRecursively(layer.sublayers!, color: self.fillColor!)
if let image = svgImage.UIImage {
//Creates a context with the same size of the button's frame
UIGraphicsBeginImageContextWithOptions(CGSize(width: rect.size.width, height: rect.size.height), false, 0)
//Get the contexts that we just created
let context = UIGraphicsGetCurrentContext()
//Setting the paths and configs.
CGContextSetFillColorWithColor(context, UIColor.whiteColor().CGColor)
CGContextSetStrokeColorWithColor(context, UIColor.blackColor().CGColor)
//Draw the image in the button's rect
image.drawInRect(rect)
//Tell the context to draw
CGContextDrawPath(context, .FillStroke)
//Get the image drawed into the context
let img = UIGraphicsGetImageFromCurrentImageContext()
//Ends the context
UIGraphicsEndImageContext()
//Sets the image into the buttom asynchronously
dispatch_async(dispatch_get_main_queue(), {
self.setImage(img, forState: .Normal)
});
}
}
// MARK: SVG color fill
//It was necessary to use this workarround to fill the layers with the segment color
//https://github.com/SVGKit/SVGKit/issues/98
func changeFillColorRecursively(sublayers: [CALayer], color: UIColor) {
for layer in sublayers {
if let l = layer as? CAShapeLayer {
l.fillColor = color.CGColor
}
if let l: CALayer = layer, sub = l.sublayers {
changeFillColorRecursively(sub, color: color)
}
}
}
}
|
0d40f71819d31041ad44ccbbef12465b
| 32.170732 | 123 | 0.584007 | false | false | false | false |
meetkei/KeiSwiftFramework
|
refs/heads/master
|
KeiSwiftFramework/Date/NSDate+Format.swift
|
mit
|
1
|
//
// NSDate+Format.swift
//
// Copyright (c) 2016 Keun young Kim <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
private let privateFormatter = DateFormatter()
public extension NSDate {
public func toString(_ format: String = "yyyyMMdd") -> String {
privateFormatter.dateFormat = format
return privateFormatter.string(from: self as Date)
}
public func toLocalizedString(_ format: String, locale: Locale = Locale.current, timeZone: TimeZone = TimeZone.current) -> String {
let currentLocale = privateFormatter.locale
let currentTimeZone = privateFormatter.timeZone
privateFormatter.locale = locale
privateFormatter.timeZone = timeZone
privateFormatter.dateFormat = format
let result = privateFormatter.string(from: self as Date)
privateFormatter.locale = currentLocale
privateFormatter.timeZone = currentTimeZone
return result
}
public func toStyledString(_ style: DateFormatter.Style) -> String {
privateFormatter.dateStyle = style
return privateFormatter.string(from: self as Date)
}
public func toStyledString(dateStyle dStyle: DateFormatter.Style, timeStyle tStyle: DateFormatter.Style) -> String {
privateFormatter.dateStyle = dStyle
privateFormatter.timeStyle = tStyle
return privateFormatter.string(from: self as Date)
}
}
|
09de039ab14c4464bfddb553be3dec7c
| 37.606061 | 135 | 0.708399 | false | false | false | false |
CharlesVu/Smart-iPad
|
refs/heads/master
|
MKHome/Settings/CityChooserViewController.swift
|
mit
|
1
|
//
// CityChooserTableViewController.swift
// MKHome
//
// Created by Charles Vu on 24/12/2016.
// Copyright © 2016 charles. All rights reserved.
//
import Foundation
import UIKit
import MapKit
import Persistance
class CityChooserViewController: UIViewController {
@IBOutlet var searchBar: UISearchBar?
@IBOutlet var tableView: UITableView?
@IBOutlet var spinner: UIActivityIndicatorView?
fileprivate let appSettings = NationalRail.AppData.sharedInstance
fileprivate var searchResults: [CLPlacemark] = []
fileprivate let geocoder = CLGeocoder()
func lookup(name: String, completion: @escaping (Error?, [CLPlacemark]?) -> Void) {
geocoder.cancelGeocode()
spinner?.startAnimating()
geocoder.geocodeAddressString(name) { (placemarks, error) in
self.spinner?.stopAnimating()
if error != nil {
completion(error, nil)
} else {
completion(nil, placemarks)
}
}
}
}
extension CityChooserViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let placemark = searchResults[indexPath.row]
if let name = placemark.name,
let coordinate = placemark.location?.coordinate {
UserSettings.sharedInstance.weather.addCity(WeatherCity(name: name,
longitude: coordinate.longitude,
latitude: coordinate.latitude))
}
_ = self.navigationController?.popViewController(animated: true)
}
}
extension CityChooserViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return searchResults.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let placemark = searchResults[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "CityCell")!
cell.textLabel?.text = placemark.name! + ", " + placemark.country!
if UIDevice.current.userInterfaceIdiom == .pad {
cell.preservesSuperviewLayoutMargins = false
cell.layoutMargins = .zero
cell.separatorInset = .zero
}
return cell
}
}
extension CityChooserViewController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchText != "" {
lookup(name: searchText, completion: { (_, placemarks) in
if let placemarks = placemarks {
self.searchResults = placemarks
} else {
self.searchResults.removeAll()
}
self.tableView?.reloadData()
})
} else {
searchResults = []
self.tableView?.reloadData()
}
}
}
|
514c03fb26aa6022ce5f3d9d6764f6d7
| 31.847826 | 100 | 0.615156 | false | false | false | false |
jduquennoy/Log4swift
|
refs/heads/master
|
Log4swiftTests/RotationPolicy/DateRotationPolicyTest.swift
|
apache-2.0
|
1
|
//
// DateRotationPolicyTest.swift
// log4swiftTests
//
// Created by Jérôme Duquennoy on 24/08/2018.
// Copyright © 2018 jerome. All rights reserved.
//
import Foundation
import XCTest
@testable import Log4swift
class DateRotationPolicyTest: XCTestCase {
func testRotationIsRequestedWhenAgeExceedsLimit() throws {
let filePath = try self.createTemporaryFilePath(fileExtension: "log")
let policy = DateRotationPolicy(maxFileAge: 10)
let fileCreationInterval = -1 * (policy.maxFileAge + 1)
FileManager.default.createFile(atPath: filePath, contents: nil, attributes: [FileAttributeKey.creationDate: Date(timeIntervalSinceNow: fileCreationInterval)])
policy.appenderDidOpenFile(atPath: filePath)
// Execute & validate
XCTAssertTrue(policy.shouldRotate())
}
func testRotationIsNotRequestedWhenFileAgeDoesNotExceedLimit() throws {
let filePath = try self.createTemporaryFilePath(fileExtension: "log")
let policy = DateRotationPolicy(maxFileAge: 10)
let fileCreationInterval = -1 * (policy.maxFileAge - 1)
FileManager.default.createFile(atPath: filePath, contents: nil, attributes: [FileAttributeKey.creationDate: Date(timeIntervalSinceNow: fileCreationInterval)])
policy.appenderDidOpenFile(atPath: filePath)
// Execute & validate
XCTAssertFalse(policy.shouldRotate())
}
func testRotationIsNotRequestedIfNoFileWasOpened() {
let policy = DateRotationPolicy(maxFileAge: 10)
// Execute & validate
XCTAssertFalse(policy.shouldRotate())
}
func testRotationIsNotRequestedIfNonExistingFileWasOpened() {
let policy = DateRotationPolicy(maxFileAge: 10)
// Execute & validate
policy.appenderDidOpenFile(atPath: "/File/that/does/not/exist.log")
XCTAssertFalse(policy.shouldRotate())
}
func testFileDateDefaultsToNowIfFileDoesNotExist() {
let policy = DateRotationPolicy(maxFileAge: 1)
// Execute & validate
policy.appenderDidOpenFile(atPath: "/File/that/does/not/exist.log")
XCTAssertFalse(policy.shouldRotate())
Thread.sleep(forTimeInterval: 1.5)
XCTAssertTrue(policy.shouldRotate())
}
}
|
e4b36d5bbc2c800f1ddd17571da2c32f
| 33.709677 | 162 | 0.745818 | false | true | false | false |
testpress/ios-app
|
refs/heads/master
|
ios-app/Model/ExamQuestion.swift
|
mit
|
1
|
//
// ExamQuestion.swift
// ios-app
//
// Created by Karthik on 12/05/20.
// Copyright © 2020 Testpress. All rights reserved.
//
import ObjectMapper
class ExamQuestion: DBModel {
@objc dynamic var id = 0
@objc dynamic var marks = ""
@objc dynamic var negativeMarks = ""
@objc dynamic var order = -1
@objc dynamic var examId = 8989
@objc dynamic var question: AttemptQuestion? = nil
@objc dynamic var questionId: Int = -1
override func mapping(map: Map) {
id <- map["id"]
marks <- map["marks"]
negativeMarks <- map["negative_marks"]
order <- map["order"]
examId <- map["exam_id"]
questionId <- map["question_id"]
}
override class func primaryKey() -> String? {
return "id"
}
}
|
4bcaf41970fc68495837d817998cc4be
| 23.75 | 54 | 0.592172 | false | false | false | false |
saeta/penguin
|
refs/heads/main
|
Sources/PenguinPipeline/Pipeline/PipelineWorkerThread.swift
|
apache-2.0
|
1
|
// Copyright 2020 Penguin Authors
//
// 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
class PipelineWorkerThread: Thread {
static var startedThreadCount: Int32 = 0
static var runningThreadCount: Int32 = 0
static var lock = NSLock()
public init(name: String) {
super.init()
self.name = name
}
/// This function must be overridden!
func body() {
preconditionFailure("No body in thread \(name!).")
}
override final func main() {
PipelineWorkerThread.lock.lock()
PipelineWorkerThread.startedThreadCount += 1
PipelineWorkerThread.runningThreadCount += 1
PipelineWorkerThread.lock.unlock()
condition.lock()
state = .started
condition.broadcast()
condition.unlock()
// Do the work
body()
PipelineWorkerThread.lock.lock()
PipelineWorkerThread.runningThreadCount -= 1
PipelineWorkerThread.lock.unlock()
assert(isFinished == false, "isFinished is not false??? \(self)")
condition.lock()
defer { condition.unlock() }
state = .finished
condition.broadcast() // Wake up everyone who has tried to join against this thread.
}
/// Blocks until the worker thread has guaranteed to have started.
func waitUntilStarted() {
condition.lock()
defer { condition.unlock() }
while state == .initialized {
condition.wait()
}
}
/// Blocks until the body has finished executing.
func join() {
condition.lock()
defer { condition.unlock() }
while state != .finished {
condition.wait()
}
}
enum State {
case initialized
case started
case finished
}
private var state: State = .initialized
private var condition = NSCondition()
}
extension PipelineIterator {
/// Determines if all worker threads started by Pipeline iterators process-wide have been stopped.
///
/// This is used during testing to ensure there are no resource leaks.
public static func _allThreadsStopped() -> Bool {
// print("Running thread count: \(PipelineWorkerThread.runningThreadCount); started: \(PipelineWorkerThread.startedThreadCount).")
PipelineWorkerThread.lock.lock()
defer { PipelineWorkerThread.lock.unlock() }
return PipelineWorkerThread.runningThreadCount == 0
}
}
|
0ae55d08e9f071280b2eb9c9b56a2fc3
| 28.37234 | 134 | 0.70192 | false | false | false | false |
google/android-auto-companion-ios
|
refs/heads/main
|
Tests/AndroidAutoConnectedDeviceTransportTests/TransportSessionTest.swift
|
apache-2.0
|
1
|
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import AndroidAutoConnectedDeviceTransportFakes
import AndroidAutoLogger
import XCTest
@testable import AndroidAutoConnectedDeviceTransport
/// Unit tests for TransportSessionTest.
class TransportSessionTest: XCTestCase {
private var peripheralProvider: FakePeripheralProvider!
private var delegate: FakeTransportSessionDelegate!
private var session: TransportSession<FakePeripheralProvider>!
override func setUp() {
super.setUp()
peripheralProvider = FakePeripheralProvider()
delegate = FakeTransportSessionDelegate()
session = TransportSession(provider: peripheralProvider, delegate: delegate)
}
override func tearDown() {
session = nil
delegate = nil
peripheralProvider = nil
super.tearDown()
}
func testDiscoversAssociatedPeripherals() {
session.scanForPeripherals(mode: .reconnection) { _, _ in }
let firstPeripheral = FakePeripheral()
peripheralProvider.postPeripheral(firstPeripheral)
XCTAssertEqual(session.peripherals.count, 1)
let secondPeripheral = FakePeripheral()
peripheralProvider.postPeripheral(secondPeripheral)
XCTAssertEqual(session.peripherals.count, 2)
XCTAssertTrue(session.peripherals.contains(firstPeripheral))
XCTAssertTrue(session.peripherals.contains(secondPeripheral))
XCTAssertEqual(session.discoveredPeripherals.count, 2)
XCTAssertTrue(session.discoveredPeripherals.contains(firstPeripheral))
XCTAssertTrue(session.discoveredPeripherals.contains(secondPeripheral))
XCTAssertEqual(delegate.discoveredAssociatedPeripherals.count, 2)
XCTAssertTrue(
delegate.discoveredAssociatedPeripherals.contains(where: {
$0 === firstPeripheral
}))
XCTAssertTrue(
delegate.discoveredAssociatedPeripherals.contains(where: {
$0 === secondPeripheral
}))
XCTAssertEqual(delegate.discoveredUnassociatedPeripherals.count, 0)
}
func testDiscoversUnassociatedPeripherals() {
session.scanForPeripherals(mode: .association) { _, _ in }
let firstPeripheral = FakePeripheral()
peripheralProvider.postPeripheral(firstPeripheral)
XCTAssertEqual(session.peripherals.count, 1)
let secondPeripheral = FakePeripheral()
peripheralProvider.postPeripheral(secondPeripheral)
XCTAssertEqual(session.peripherals.count, 2)
XCTAssertTrue(session.peripherals.contains(firstPeripheral))
XCTAssertTrue(session.peripherals.contains(secondPeripheral))
XCTAssertEqual(session.discoveredPeripherals.count, 2)
XCTAssertTrue(session.discoveredPeripherals.contains(firstPeripheral))
XCTAssertTrue(session.discoveredPeripherals.contains(secondPeripheral))
XCTAssertEqual(delegate.discoveredUnassociatedPeripherals.count, 2)
XCTAssertTrue(
delegate.discoveredUnassociatedPeripherals.contains(where: {
$0 === firstPeripheral
}))
XCTAssertTrue(
delegate.discoveredUnassociatedPeripherals.contains(where: {
$0 === secondPeripheral
}))
XCTAssertEqual(delegate.discoveredAssociatedPeripherals.count, 0)
}
func testPropagatesStateChange() {
session.scanForPeripherals(mode: .reconnection) { _, _ in }
let peripheral = FakePeripheral()
peripheralProvider.postPeripheral(peripheral)
peripheral.status = .connecting
XCTAssertEqual(delegate.connectingPeripherals.count, 1)
}
}
private class FakeTransportSessionDelegate: TransportSessionDelegate {
var discoveredAssociatedPeripherals: [AnyTransportPeripheral] = []
var discoveredUnassociatedPeripherals: [AnyTransportPeripheral] = []
var connectingPeripherals: [AnyTransportPeripheral] = []
func session(
_: AnyTransportSession, didDiscover peripheral: AnyTransportPeripheral, mode: PeripheralScanMode
) {
switch mode {
case .association:
discoveredUnassociatedPeripherals.append(peripheral)
case .reconnection:
discoveredAssociatedPeripherals.append(peripheral)
}
}
func session(
_: AnyTransportSession, peripheral: AnyTransportPeripheral,
didChangeStateTo state: PeripheralStatus
) {
if case .connecting = state {
connectingPeripherals.append(peripheral)
}
}
}
|
12a4144c9961e9a88678066fb744490c
| 33.904412 | 100 | 0.765747 | false | true | false | false |
thatseeyou/iOSSDKExamples
|
refs/heads/master
|
Pages/NSData from HTTP.xcplaygroundpage/Contents.swift
|
mit
|
1
|
/*:
# HTTP 응답을 Data로 받아오기
*/
import Foundation
let url = NSURL(string: "https://api.whitehouse.gov/v1/petitions.json?limit=30")
let data: NSData! = try? NSData(contentsOfURL: url!, options: [])
//print(data)
if let dataValue = data {
var dataString = NSString(data: dataValue, encoding:NSUTF8StringEncoding)
print(dataString)
}
|
f1e5812382c5ffa067fe3f02d6d57a2d
| 16.35 | 80 | 0.694524 | false | false | false | false |
hathway/JSONRequest
|
refs/heads/master
|
JSONRequest/JSONRequestAuthChallengeHandler.swift
|
mit
|
1
|
//
// JSONRequestAuthChallengeHandler.swift
// JSONRequest
//
// Created by Yevhenii Hutorov on 04.11.2019.
// Copyright © 2019 Hathway. All rights reserved.
//
import Foundation
public struct JSONRequestAuthChallengeResult {
public let disposition: URLSession.AuthChallengeDisposition
public let credential: URLCredential?
public init(disposition: URLSession.AuthChallengeDisposition, credential: URLCredential? = nil) {
self.disposition = disposition
self.credential = credential
}
}
public protocol JSONRequestAuthChallengeHandler {
func handle(_ session: URLSession, challenge: URLAuthenticationChallenge) -> JSONRequestAuthChallengeResult
}
class JSONRequestSessionDelegate: NSObject, URLSessionDelegate {
var authChallengeHandler: JSONRequestAuthChallengeHandler?
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
let result = authChallengeHandler?.handle(session, challenge: challenge)
let disposition = result?.disposition ?? .performDefaultHandling
completionHandler(disposition, result?.credential)
}
}
|
a9fc3433689f5004014f056ca626f64f
| 37.34375 | 186 | 0.774246 | false | false | false | false |
eflyjason/astro-daily
|
refs/heads/master
|
Astro Daily - APP/Astro Daily/AboutViewController.swift
|
apache-2.0
|
1
|
//
// AboutViewController.swift
// Astro Daily
//
// Created by Arefly on 22/1/2015.
// Copyright (c) 2015年 Arefly. All rights reserved.
//
import Foundation
import UIKit
import CoreData
class AboutViewController: UIViewController { //设置视图
@IBOutlet var versionLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
var version = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as String
var build = NSBundle.mainBundle().objectForInfoDictionaryKey(kCFBundleVersionKey as NSString) as String
versionLabel.numberOfLines = 0; // Enable \n break line
versionLabel.hidden = false; // Disable Hidden
versionLabel.text = "V " + version + " (Build " + build + ")"
}
}
|
173dc3e0c24860296d7f21e164ecfe29
| 29.75 | 111 | 0.626744 | false | false | false | false |
kclowes/HackingWithSwift
|
refs/heads/master
|
Project7/Project7/DetailViewController.swift
|
mit
|
1
|
//
// DetailViewController.swift
// Project7
//
// Created by Keri Clowes on 3/25/16.
// Copyright © 2016 Keri Clowes. All rights reserved.
//
import UIKit
import WebKit
class DetailViewController: UIViewController {
var webView: WKWebView!
var detailItem: [String: String]!
override func loadView() {
webView = WKWebView()
view = webView
}
override func viewDidLoad() {
super.viewDidLoad()
guard detailItem != nil else { return }
if let body = detailItem["body"] {
var html = "<html>"
html += "<head>"
html += "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">"
html += "<style> body { font-size: 150%; } </style>"
html += "</head>"
html += "<body>"
html += body
html += "</body>"
html += "</html>"
webView.loadHTMLString(html, baseURL: nil)
}
}
}
|
3b87b6180ffc15475d67bc7b98665b10
| 22.078947 | 88 | 0.596351 | false | false | false | false |
artsy/eidolon
|
refs/heads/master
|
KioskTests/Bid Fulfillment/ConfirmYourBidPINViewControllerTests.swift
|
mit
|
3
|
import Quick
import Nimble
@testable
import Kiosk
import Moya
import RxSwift
import Nimble_Snapshots
class ConfirmYourBidPINViewControllerTests: QuickSpec {
override func spec() {
it("looks right by default") {
let subject = testConfirmYourBidPINViewController()
subject.loadViewProgrammatically()
expect(subject) == snapshot()
}
it("reacts to keypad inputs with the string") {
let customKeySubject = PublishSubject<String>()
let subject = testConfirmYourBidPINViewController()
subject.pin = customKeySubject.asObservable()
subject.loadViewProgrammatically()
customKeySubject.onNext("2344");
expect(subject.pinTextField.text) == "2344"
}
it("reacts to keypad inputs with the string") {
let customKeySubject = PublishSubject<String>()
let subject = testConfirmYourBidPINViewController()
subject.pin = customKeySubject
subject.loadViewProgrammatically()
customKeySubject.onNext("2");
expect(subject.pinTextField.text) == "2"
}
it("reacts to keypad inputs with the string") {
let customKeySubject = PublishSubject<String>()
let subject = testConfirmYourBidPINViewController()
subject.pin = customKeySubject;
subject.loadViewProgrammatically()
customKeySubject.onNext("222");
expect(subject.pinTextField.text) == "222"
}
}
}
func testConfirmYourBidPINViewController() -> ConfirmYourBidPINViewController {
let controller = ConfirmYourBidPINViewController.instantiateFromStoryboard(fulfillmentStoryboard).wrapInFulfillmentNav() as! ConfirmYourBidPINViewController
controller.provider = Networking.newStubbingNetworking()
return controller
}
|
c64613fd0bc51ccd656584a0c54a895b
| 31.482759 | 160 | 0.667197 | false | true | false | false |
kristopherjohnson/bitsybasic
|
refs/heads/master
|
finchbasic/main.swift
|
mit
|
1
|
/*
Copyright (c) 2014, 2015 Kristopher Johnson
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import Foundation
func runInterpreter() {
let io = StandardIO()
let interpreter = Interpreter(interpreterIO: io)
interpreter.runUntilEndOfInput()
}
// Put -DUSE_INTERPRETER_THREAD=1 in Build Settings
// to run the interpreter in another thread.
//
// This demonstrates that we get EXC_BAD_ACCESS when
// running the interpreter in another thread. Do not
// use this for production code.
//
// See http://www.openradar.me/19353741
#if USE_INTERPRETER_THREAD
final class InterpreterThread: NSThread {
let completionSemaphore = dispatch_semaphore_create(0)
override func main() {
runInterpreter()
dispatch_semaphore_signal(self.completionSemaphore)
}
}
let thread = InterpreterThread()
thread.start()
// Main thread waits for the other thread to finish
dispatch_semaphore_wait(thread.completionSemaphore, DISPATCH_TIME_FOREVER)
#else
// Normal case is to run the interpreter in the
// main thread
runInterpreter()
#endif
|
cfc712ce7a7f18ca432d2c3f66adaac7
| 32.460317 | 78 | 0.748577 | false | false | false | false |
P0ed/Magikombat
|
refs/heads/master
|
Magikombat/Engine/Engine.swift
|
mit
|
1
|
import Foundation
class Engine {
let world = World()
var state = GameState()
var hero = Actor()
init(level: Level) {
setup(level)
}
func setup(level: Level) {
level.forEach { node in
let platform = node.platform
world.createStaticBody(platform.position.asVector(), size: platform.size.asVector())
}
hero.body = world.createDynamicBody(Position(x: 10, y: 10).asVector(), size: Size(width: 1, height: 2).asVector())
}
func handleInput(input: Input) {
hero.handleInput(input)
}
func simulatePhysics(input: Input) -> GameState {
handleInput(input)
world.step()
state.hero.position = hero.body!.position
return state
}
}
|
8ea6727564ba1285d52f3d4bce073edb
| 16.918919 | 116 | 0.686275 | false | false | false | false |
appnexus/mobile-sdk-ios
|
refs/heads/master
|
examples/Swift/SimpleIntegration/SimpleIntegrationSwift/NativeAd/NativeAdViewController.swift
|
apache-2.0
|
1
|
/* Copyright 2020 APPNEXUS INC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import UIKit
import AppNexusSDK
class NativeAdViewController: UIViewController , ANNativeAdRequestDelegate , ANNativeAdDelegate {
var nativeAdRequest: ANNativeAdRequest?
var nativeAdResponse: ANNativeAdResponse?
var anNativeAdView: ANNativeAdView?
var indicator = UIActivityIndicatorView()
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Native Ad"
// Do any additional setup after loading the view.
nativeAdRequest = ANNativeAdRequest()
nativeAdRequest!.placementId = "17058950"
nativeAdRequest!.shouldLoadIconImage = true
nativeAdRequest!.shouldLoadMainImage = true
nativeAdRequest!.delegate = self
nativeAdRequest!.loadAd()
}
func adRequest(_ request: ANNativeAdRequest, didReceive response: ANNativeAdResponse) {
self.nativeAdResponse = response
let adNib = UINib(nibName: "ANNativeAdView", bundle: Bundle.main)
let array = adNib.instantiate(withOwner: self, options: nil)
anNativeAdView = array.first as? ANNativeAdView
anNativeAdView?.titleLabel.text = nativeAdResponse?.title
anNativeAdView?.bodyLabel.text = nativeAdResponse?.body
anNativeAdView?.iconImageView.image = nativeAdResponse?.iconImage
anNativeAdView?.mainImageView.image = nativeAdResponse?.mainImage
anNativeAdView?.sponsoredLabel.text = nativeAdResponse?.sponsoredBy
anNativeAdView?.callToActionButton.setTitle(nativeAdResponse?.callToAction, for: .normal)
nativeAdResponse?.delegate = self
nativeAdResponse?.clickThroughAction = ANClickThroughAction.openSDKBrowser
view.addSubview(anNativeAdView!)
do {
try nativeAdResponse?.registerView(forTracking: anNativeAdView!, withRootViewController: self, clickableViews: [self.anNativeAdView?.callToActionButton! as Any, self.anNativeAdView?.mainImageView! as Any])
} catch {
print("Failed to registerView for Tracking")
}
}
func adRequest(_ request: ANNativeAdRequest, didFailToLoadWithError error: Error, with adResponseInfo: ANAdResponseInfo?) {
print("Ad request Failed With Error")
}
// MARK: - ANNativeAdDelegate
func adDidLogImpression(_ response: Any) {
print("adDidLogImpression")
}
func adWillExpire(_ response: Any) {
print("adWillExpire")
}
func adDidExpire(_ response: Any) {
print("adDidExpire")
}
func adWasClicked(_ response: Any) {
print("adWasClicked")
}
func adWillPresent(_ response: Any) {
print("adWillPresent")
}
func adDidPresent(_ response: Any) {
print("adDidPresent")
}
func adWillClose(_ response: Any) {
print("adWillClose")
}
func adDidClose(_ response: Any) {
print("adDidClose")
}
func adWillLeaveApplication(_ response: Any) {
print("adWillLeaveApplication")
}
@IBAction func hideAds(_ sender: Any) {
self.anNativeAdView?.removeFromSuperview()
}
}
|
1c3fee72751a2df450dc13dd18599700
| 32.5 | 217 | 0.677505 | false | false | false | false |
congncif/SiFUtilities
|
refs/heads/master
|
Example/Pods/Boardy/Boardy/Core/BoardType/DedicatedBoard.swift
|
mit
|
1
|
//
// DedicatedBoard.swift
// Boardy
//
// Created by NGUYEN CHI CONG on 3/18/20.
//
import Foundation
// MARK: - AdaptableBoard
public protocol AdaptableBoard {
associatedtype InputType
var inputAdapters: [(Any?) -> InputType?] { get }
}
extension AdaptableBoard {
public func convertOptionToInput(_ option: Any?) -> InputType? {
var input: InputType?
for adapter in validAdapters {
input = adapter(option)
if input != nil { break }
}
return input
}
public var inputAdapters: [(Any?) -> InputType?] { [] }
var validAdapters: [(Any?) -> InputType?] {
let defaultAdapter: (Any?) -> InputType? = { $0 as? InputType }
return inputAdapters + [defaultAdapter]
}
}
// MARK: - DedicatedBoard
public protocol DedicatedBoard: AdaptableBoard, ActivatableBoard {
func activate(withInput input: InputType?)
}
extension DedicatedBoard {
public func activate(withOption option: Any?) {
activate(withInput: convertOptionToInput(option))
}
}
// MARK: - GuaranteedBoard
public protocol GuaranteedBoard: AdaptableBoard, ActivatableBoard {
func activate(withGuaranteedInput input: InputType)
var silentInputWhiteList: [(_ input: Any?) -> Bool] { get }
}
extension GuaranteedBoard {
private func isSilent(input: Any?) -> Bool {
let listCheckers = [isSilentData] + silentInputWhiteList
for checker in listCheckers {
if checker(input) { return true }
}
return false
}
public var silentInputWhiteList: [(_ input: Any?) -> Bool] { [] }
public func activate(withOption option: Any?) {
guard let input = convertOptionToInput(option) else {
guard isSilent(input: option) else {
assertionFailure("\(String(describing: self))\n🔥 Cannot convert input from \(String(describing: option)) to type \(InputType.self)")
return
}
return
}
activate(withGuaranteedInput: input)
}
}
// MARK: - Board sending a type safe Output data
public protocol GuaranteedOutputSendingBoard: IdentifiableBoard {
associatedtype OutputType
}
extension GuaranteedOutputSendingBoard {
public func sendOutput(_ data: OutputType) {
#if DEBUG
if isSilentData(data) {
print("\(String(describing: self))\n🔥 Sending a special Data Type might lead unexpected behaviours!\n👉 You should wrap \(data) in custom Output Type.")
}
#endif
sendToMotherboard(data: data)
}
}
|
2e739a67019159e795f0757d7ac9e798
| 26.351064 | 163 | 0.641774 | false | false | false | false |
dPackumar/FlexiCollectionViewLayout
|
refs/heads/master
|
Example/swift/FlexiCollectionViewLayout/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// FlexiCollectionViewLayout
//
// Created by Deepak Kumar on 11/13/16.
// Copyright © 2016 Deepak Kumar. All rights reserved.
//
import UIKit
import FlexiCollectionViewLayout
internal let cellReuseIdentifier = "HKCellReuseID"
/**
Example project to get started with FlexiCollectionViewLayout
*/
final class ViewController: UICollectionViewController {
fileprivate let hongKongPhotos = [UIImage(named: "beach"), UIImage(named: "boat"),UIImage(named: "brucelee"),UIImage(named: "dragonboat"),UIImage(named: "icc"),UIImage(named: "icclightshow"),UIImage(named: "ifc"),UIImage(named: "island"),UIImage(named: "lantau"),UIImage(named: "oceanpark"),UIImage(named: "orange"),UIImage(named: "panda"),UIImage(named: "sunset"),UIImage(named: "thepeak"),UIImage(named: "tram")]
fileprivate let interItemSpacing: CGFloat = 2
fileprivate let edgeInsets = UIEdgeInsets.zero
override func viewDidLoad() {
super.viewDidLoad()
let layout = FlexiCollectionViewLayout()
collectionView?.collectionViewLayout = layout
registerSupplementaryViews()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
private func registerSupplementaryViews() {
collectionView?.register(UINib(nibName: "HeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "HeaderReuseID")
collectionView?.register(UINib(nibName: "FooterView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "FooterReuseID")
}
//MARK: Helpers
fileprivate func cellWidth() -> CGFloat {
return (self.collectionView!.bounds.size.width - (interItemSpacing * 2) - edgeInsets.left - edgeInsets.right ) / 3
}
}
//MARK: UICollectionViewDatasource
extension ViewController {
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 3
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
switch section {
case 0:
return 28
case 1:
return 20
default:
return 24
}
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellReuseIdentifier, for: indexPath) as! HKCell
cell.imageView.image = hongKongPhotos[indexPath.item % hongKongPhotos.count]
cell.infoLabel.text = "Image \(indexPath.row)"
return cell
}
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
if kind == UICollectionElementKindSectionHeader {
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "HeaderReuseID", for: indexPath) as! HeaderView
headerView.headerLabel.text = "Section \(indexPath.section)"
return headerView
} else if kind == UICollectionElementKindSectionFooter {
let footerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "FooterReuseID", for: indexPath) as! FooterView
footerView.footerLabel.text = "Footer \(indexPath.section)"
return footerView
}
return UICollectionReusableView()
}
}
//MARK: FlexiCollectionViewLayoutDelegate
extension ViewController: FlexiCollectionViewLayoutDelegate {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: FlexiCollectionViewLayout, sizeForFlexiItemAt indexPath: IndexPath) -> ItemSizeAttributes {
let size = CGSize(width: cellWidth(), height: 100)
switch indexPath.row {
case 0:
return ItemSizeAttributes(itemSize: size, layoutSize: .large, widthFactor: 2, heightFactor: 2)
case 1:
return ItemSizeAttributes(itemSize: size, layoutSize: .regular, widthFactor: 1, heightFactor: 1)
case 2:
return ItemSizeAttributes(itemSize: size, layoutSize: .regular, widthFactor: 1, heightFactor: 1)
case 3:
return ItemSizeAttributes(itemSize: size, layoutSize: .large, widthFactor: 3, heightFactor: 1)
case 4:
return ItemSizeAttributes(itemSize: size, layoutSize: .large, widthFactor: 1, heightFactor: 3)
case 5:
return ItemSizeAttributes(itemSize: size, layoutSize: .regular, widthFactor: 1, heightFactor: 1)
case 6:
return ItemSizeAttributes(itemSize: size, layoutSize: .regular, widthFactor: 1, heightFactor: 1)
case 7:
return ItemSizeAttributes(itemSize: size, layoutSize: .large, widthFactor: 2, heightFactor: 1)
case 8:
return ItemSizeAttributes(itemSize: size, layoutSize: .regular, widthFactor: 1, heightFactor: 1)
case 9:
return ItemSizeAttributes(itemSize: size, layoutSize: .regular, widthFactor: 1, heightFactor: 1)
case 10:
return ItemSizeAttributes(itemSize: size, layoutSize: .large, widthFactor: 1, heightFactor: 2)
case 11:
return ItemSizeAttributes(itemSize: size, layoutSize: .large, widthFactor: 2, heightFactor: 2)
default:
return ItemSizeAttributes(itemSize: size, layoutSize: .regular, widthFactor: 1, heightFactor: 1)
}
/**
if indexPath.item % 6 == 0 {
return ItemSizeAttributes(itemSize: size, layoutSize: .large, widthFactor: 2, heightFactor: 2)
}
return ItemSizeAttributes(itemSize: size, layoutSize: .regular, widthFactor: 1, heightFactor: 1)
*/
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return edgeInsets
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return interItemSpacing
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, heightForFooterInSection section: Int) -> CGFloat {
return 45
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, heightForHeaderInSection section: Int) -> CGFloat {
return 45
}
}
|
6931e84b8ff82b2ee6d8dce0017caf46
| 46.573427 | 418 | 0.702631 | false | false | false | false |
narner/AudioKit
|
refs/heads/master
|
Examples/iOS/SongProcessor/SongProcessor/View Controllers/PitchShifterViewController.swift
|
mit
|
1
|
//
// PitchShifterViewController.swift
// SongProcessor
//
// Created by Elizabeth Simonian on 10/17/16.
// Copyright © 2016 AudioKit. All rights reserved.
//
import AudioKit
import AudioKitUI
import UIKit
class PitchShifterViewController: UIViewController {
@IBOutlet private weak var pitchSlider: AKSlider!
@IBOutlet private weak var mixSlider: AKSlider!
let songProcessor = SongProcessor.sharedInstance
override func viewDidLoad() {
super.viewDidLoad()
pitchSlider.range = -24 ... 24
pitchSlider.value = songProcessor.pitchShifter.shift
mixSlider.value = songProcessor.pitchMixer.balance
mixSlider.callback = updateMix
pitchSlider.callback = updatePitch
}
func updatePitch(value: Double) {
songProcessor.pitchShifter.shift = value
}
func updateMix(value: Double) {
songProcessor.pitchMixer.balance = value
}
}
|
1f6bdd6e0878703674c061220c6c71a0
| 21.658537 | 60 | 0.70183 | false | false | false | false |
3DprintFIT/octoprint-ios-client
|
refs/heads/dev
|
OctoPhone/View Related/Detail/View/JobStateCell.swift
|
mit
|
1
|
//
// JobStateCell.swift
// OctoPhone
//
// Created by Josef Dolezal on 01/05/2017.
// Copyright © 2017 Josef Dolezal. All rights reserved.
//
import UIKit
import SnapKit
import ReactiveSwift
/// Cell with job state
class JobStateCell: UICollectionViewCell, TypedCell {
/// Reuse identifier of cell
static let identifier = "JobStateCell"
// MARK: Public API
/// Label for job state
let stateLabel: UILabel = {
let label = UILabel()
label.font = UIFont.preferredFont(forTextStyle: .headline)
label.textAlignment = .center
return label
}()
// MARK: Private properties
// MARK: Initializers
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(stateLabel)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Cell lifecycle
override func layoutSubviews() {
super.layoutSubviews()
stateLabel.snp.makeConstraints { make in
make.edges.equalToSuperview()
}
}
// MARK: Internal logic
}
|
168c3f319c1c4f49cf11514d604434c8
| 19.25 | 66 | 0.637566 | false | false | false | false |
ps2/rileylink_ios
|
refs/heads/dev
|
OmniKitUI/Views/SetupCompleteView.swift
|
mit
|
1
|
//
// SetupCompleteView.swift
// OmniKit
//
// Created by Pete Schwamb on 3/2/21.
// Copyright © 2021 LoopKit Authors. All rights reserved.
//
import SwiftUI
import LoopKitUI
struct SetupCompleteView: View {
@Environment(\.verticalSizeClass) var verticalSizeClass
@Environment(\.appName) private var appName
private var onSaveScheduledExpirationReminder: ((_ selectedDate: Date?, _ completion: @escaping (_ error: Error?) -> Void) -> Void)?
private var didFinish: () -> Void
private var didRequestDeactivation: () -> Void
private var dateFormatter: DateFormatter
@State private var scheduledReminderDate: Date?
@State private var scheduleReminderDateEditViewIsShown: Bool = false
var allowedDates: [Date]
init(scheduledReminderDate: Date?, dateFormatter: DateFormatter, allowedDates: [Date], onSaveScheduledExpirationReminder: ((_ selectedDate: Date?, _ completion: @escaping (_ error: Error?) -> Void) -> Void)?, didFinish: @escaping () -> Void, didRequestDeactivation: @escaping () -> Void)
{
self._scheduledReminderDate = State(initialValue: scheduledReminderDate)
self.dateFormatter = dateFormatter
self.allowedDates = allowedDates
self.onSaveScheduledExpirationReminder = onSaveScheduledExpirationReminder
self.didFinish = didFinish
self.didRequestDeactivation = didRequestDeactivation
}
var body: some View {
GuidePage(content: {
VStack {
LeadingImage("Pod")
Text(String(format: LocalizedString("Your Pod is ready for use.\n\n%1$@ will remind you to change your pod before it expires. You can change this to a time convenient for you.", comment: "Format string for instructions for setup complete view. (1: app name)"), appName))
.fixedSize(horizontal: false, vertical: true)
Divider()
VStack(alignment: .leading) {
Text("Scheduled Reminder")
Divider()
NavigationLink(
destination: ScheduledExpirationReminderEditView(
scheduledExpirationReminderDate: scheduledReminderDate,
allowedDates: allowedDates,
dateFormatter: dateFormatter,
onSave: { (newDate, completion) in
onSaveScheduledExpirationReminder?(newDate) { (error) in
if error == nil {
scheduledReminderDate = newDate
}
completion(error)
}
},
onFinish: { scheduleReminderDateEditViewIsShown = false }),
isActive: $scheduleReminderDateEditViewIsShown)
{
RoundedCardValueRow(
label: LocalizedString("Time", comment: "Label for expiration reminder row"),
value: scheduledReminderDateString(scheduledReminderDate),
highlightValue: false
)
}
}
}
.padding(.bottom, 8)
.accessibility(sortPriority: 1)
}) {
Button(action: {
didFinish()
}) {
Text(LocalizedString("Finish Setup", comment: "Action button title to continue at Setup Complete"))
.actionButtonStyle(.primary)
}
.padding()
.background(Color(UIColor.systemBackground))
.zIndex(1)
}
.animation(.default)
.navigationBarTitle("Setup Complete", displayMode: .automatic)
}
private func scheduledReminderDateString(_ scheduledDate: Date?) -> String {
if let scheduledDate = scheduledDate {
return dateFormatter.string(from: scheduledDate)
} else {
return LocalizedString("No Reminder", comment: "Value text for no expiration reminder")
}
}
}
struct SetupCompleteView_Previews: PreviewProvider {
static var previews: some View {
SetupCompleteView(
scheduledReminderDate: Date(),
dateFormatter: DateFormatter(),
allowedDates: [Date()],
onSaveScheduledExpirationReminder: { (date, completion) in
},
didFinish: {
},
didRequestDeactivation: {
}
)
}
}
|
5dc7ffc7add5c77c068f47eb6f49c792
| 40.150442 | 291 | 0.563871 | false | false | false | false |
klesh/cnodejs-swift
|
refs/heads/master
|
CNode/Options/MessagesCell.swift
|
apache-2.0
|
1
|
//
// MessagesCell.swift
// CNode
//
// Created by Klesh Wong on 1/11/16.
// Copyright © 2016 Klesh Wong. All rights reserved.
//
import UIKit
import SwiftyJSON
protocol MessagesCellDelegate : class {
func avatarTapped(author: String, cell: MessagesCell)
}
class MessagesCell : UITableViewCell {
@IBOutlet weak var theAvatar: UIButton!
@IBOutlet weak var theAuthor: UILabel!
@IBOutlet weak var theType: UILabel!
@IBOutlet weak var theElapse: UILabel!
@IBOutlet weak var theReply: UIWebView!
@IBOutlet weak var theContent: CNWebView!
@IBOutlet weak var theTopic: UILabel!
weak var delegate: MessagesCellDelegate?
override func awakeFromNib() {
super.awakeFromNib()
Utils.circleUp(theAvatar)
}
func bind(message: JSON) {
theAvatar.kf_setImageWithURL(Utils.toURL(message["author"]["avatar_url"].string), forState: .Normal)
theAuthor.text = message["author"]["loginname"].string
theTopic.text = message["topic"]["title"].string
let hasReply = nil != message["reply"]["id"].string
if message["type"].stringValue == "at" {
if hasReply {
theType.text = "在回复中@了你"
} else {
theType.text = "在主题中@了你"
}
} else {
theType.text = "回复了您的话题"
}
if hasReply {
theElapse.text = Utils.relativeTillNow(message["reply"]["create_at"].stringValue.toDateFromISO8601())
theContent.loadHTMLAsPageOnce(message["reply"]["content"].stringValue, baseURL: ApiClient.BASE_URL)
} else {
theElapse.text = Utils.relativeTillNow(message["topic"]["last_reply_at"].stringValue.toDateFromISO8601())
theContent.hidden = true
}
let textColor = message["has_read"].boolValue ? UIColor.darkGrayColor() : UIColor.darkTextColor()
theAuthor.textColor = textColor
theType.textColor = textColor
theElapse.textColor = textColor
theTopic.textColor = textColor
}
@IBAction func avatarDidTapped(sender: AnyObject) {
if let d = delegate {
d.avatarTapped(theAuthor.text!, cell: self)
}
}
}
|
29ba5134e4e5468df047685de14df765
| 31.271429 | 117 | 0.616202 | false | false | false | false |
KDE/krita
|
refs/heads/master
|
krita/integration/quicklookng/ThumbnailProvider.swift
|
gpl-3.0
|
1
|
/*
* This file is part of Krita
*
* Copyright (c) 2020 L. E. Segovia <[email protected]>
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*/
import AppKit
import QuickLookThumbnailing
class ThumbnailProvider: QLThumbnailProvider {
override func provideThumbnail(for request: QLFileThumbnailRequest, _ handler: @escaping (QLThumbnailReply?, Error?) -> Void) {
// There are three ways to provide a thumbnail through a QLThumbnailReply. Only one of them should be used.
// First way: Draw the thumbnail into the current context, set up with UIKit's coordinate system.
/* handler(QLThumbnailReply(contextSize: request.maximumSize, currentContextDrawing: { () -> Bool in
// Draw the thumbnail here.
// Return true if the thumbnail was successfully drawn inside this block.
return true
}), nil) */
// Second way: Draw the thumbnail into a context passed to your block, set up with Core Graphics's coordinate system.
handler(QLThumbnailReply(contextSize: request.maximumSize, drawing: { (context: CGContext) -> Bool in
// Draw the thumbnail here.
var appPlist = UnzipTask(request.fileURL.path, "preview.png")
// Not made with Krita. Find ORA thumbnail instead.
if (appPlist == nil || appPlist!.isEmpty) {
appPlist =
UnzipTask(request.fileURL.path, "Thumbnails/thumbnail.png");
}
if (appPlist != nil && !appPlist!.isEmpty) {
let appIcon = NSImage.init(data: appPlist!);
let rep = appIcon!.representations.first!;
var renderRect = NSMakeRect(0.0, 0.0, CGFloat(rep.pixelsWide), CGFloat(rep.pixelsHigh));
let cgImage = appIcon?.cgImage(forProposedRect: &renderRect, context: nil, hints: nil);
context.draw(cgImage!, in: renderRect);
} else {
return false;
}
// Return true if the thumbnail was successfully drawn inside this block.
return true
}), nil)
// Third way: Set an image file URL.
/* handler(QLThumbnailReply(imageFileURL: Bundle.main.url(forResource: "fileThumbnail", withExtension: "jpg")!), nil) */
}
}
|
e601b942b2f5640e8bdbcd21b7dc7b17
| 39 | 131 | 0.65473 | false | false | false | false |
chai2010/ptyy
|
refs/heads/master
|
ios-app/yjyy-swift/DataEngin.swift
|
bsd-3-clause
|
1
|
// Copyright 2016 <chaishushan{AT}gmail.com>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
import UIKit
extension String {
subscript (i: Int) -> Character {
return self[self.startIndex.advancedBy(i)]
}
subscript (i: Int) -> String {
return String(self[i] as Character)
}
subscript (r: Range<Int>) -> String {
let start = startIndex.advancedBy(r.startIndex)
let end = start.advancedBy(r.endIndex - r.startIndex)
return self[Range(start ..< end)]
}
}
// 导入Go语言函数
@_silgen_name("YjyySearch")
func GoYjyySearch(query:UnsafePointer<CChar>, limits:Int32) -> UnsafeMutablePointer<CChar>
class DataEngin {
let cache = LRUCache<String, [String]>(capacity: 16)
let cacheV2 = LRUCache<String, [[String]]>(capacity: 16)
// 失败的查询(对于非正则只要包含, 则必然是失败的)
// 正则的特例: .*?|
let failedQueryCache = LRUCache<String, Bool>(capacity: 64)
// 判断是非是失败的查询
private func assertFailedQuery(query:String) -> Bool {
// 1. 如果完全包含, 则必然是失败的查询
if self.failedQueryCache[query] != nil {
return true
}
// 2. 查看是否是失败集合的子集
for (key, _) in self.failedQueryCache.Map() {
if query.rangeOfString(key) != nil{
return true
}
}
// 不确定是否失败
return false
}
// 注册失败的查询
private func addFailedQuery(query:String) {
// 正则的特例: .*?|
for c in query.characters {
for x in ".*?|。*?|".characters {
if c == x {
return
}
}
}
if self.assertFailedQuery(query) {
return
}
self.failedQueryCache[query] = true
}
func SearchV2(rawQuery:String) -> [[String]] {
// 删除空白
let query = rawQuery.stringByTrimmingCharactersInSet(
NSCharacterSet.whitespaceAndNewlineCharacterSet()
)
// 已经缓存成功的查询
if let result = self.cacheV2[query] {
return result
}
var resultMap = [String: [String]]()
let letters : NSString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ#"
for i in 0..<letters.length {
let c = letters.characterAtIndex(i)
resultMap[String(UnicodeScalar(c))] = []
}
// 执行查询
var resultTemp = [String]()
// 如果不确定是失败的查询, 则进行查询操作
if !self.assertFailedQuery(query) {
resultTemp = self.Search(query)
}
// 处理查询结果
for s in resultTemp {
if !s.isEmpty {
let key = self.getFistLetter(s)
resultMap[key]!.append(s)
}
}
var resultList = [[String]]()
for i in 0..<letters.length {
let c = letters.characterAtIndex(i)
resultList.append(resultMap[String(UnicodeScalar(c))]!)
}
// 缓存成功和失败的查询
if resultTemp.isEmpty {
self.addFailedQuery(query)
} else {
self.cacheV2[query] = resultList
}
return resultList
}
func Search(query:String) -> [String] {
if let result = self.cache[query] {
return result
}
let p = GoYjyySearch(query, limits: 0)
let s = String.fromCString(p)!
p.dealloc(1)
let result = s.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet())
self.cache[query] = result
return result
}
// 拼音首字母, [A-Z]#
func getFistLetter(str: String)-> String {
if str.isEmpty {
return "#"
}
// 多音字: 长沙/涡阳/厦门
if str[0] == "长" {
return "C"
}
if str[0] == "涡" {
return "G"
}
if str[0] == "厦" {
return "X"
}
let mutStr = NSMutableString(string: str) as CFMutableString
// 取得带音调拼音
if CFStringTransform(mutStr, nil,kCFStringTransformMandarinLatin, false) {
// 取得不带音调拼音
if CFStringTransform(mutStr, nil, kCFStringTransformStripDiacritics, false) {
let pinyin = (mutStr as String).uppercaseString
if pinyin.characters.count > 0 {
if pinyin[0] >= "A" && pinyin[0] <= "Z"{
return pinyin[0]
}
}
}
}
return "#"
}
}
|
a6feaf5079ca5125597ec78fb27304f7
| 20.211765 | 91 | 0.653078 | false | false | false | false |
wayfindrltd/wayfindr-demo-ios
|
refs/heads/master
|
Wayfindr Demo/Classes/Controller/Developer/MissingKeyRoutesTableViewController.swift
|
mit
|
1
|
//
// MissingKeyRoutes.swift
// Wayfindr Demo
//
// Created by Wayfindr on 18/11/2015.
// Copyright (c) 2016 Wayfindr (http://www.wayfindr.net)
//
// 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 SwiftGraph
import SVProgressHUD
/// Table view for displaying any missing key routes (i.e. those between platforms and exits).
final class MissingKeyRoutesTableViewController: UITableViewController {
// MARK: - Properties
/// Reuse identifier for the table cells.
fileprivate let reuseIdentifier = "RouteCell"
/// Model representation of entire venue.
fileprivate let venue: WAYVenue
/// Whether the controller is still computing missing routes.
fileprivate var parsingData = true
/// Array of all the currently missing routes (or a congratulations message if there are none).
fileprivate var missingRoutes = [String]()
// MARK: - Intiailizers / Deinitializers
/**
Initializes a `MissingKeyRoutesTableViewController`.
- parameter venue: Model representation of entire venue.
*/
init(venue: WAYVenue) {
self.venue = venue
super.init(style: .plain)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: reuseIdentifier)
tableView.estimatedRowHeight = WAYConstants.WAYSizes.EstimatedCellHeight
tableView.rowHeight = UITableView.automaticDimension
title = WAYStrings.MissingKeyRoutes.MissingRoutes
SVProgressHUD.show()
DispatchQueue.global(qos: DispatchQoS.QoSClass.background).async(execute: { [weak self] in
self?.determineMissingRoutes()
self?.parsingData = false
DispatchQueue.main.async(execute: {
SVProgressHUD.dismiss()
self?.tableView.reloadData()
})
})
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
SVProgressHUD.dismiss()
}
// MARK: - Setup
/**
Calculates all the missing key routes (those between platforms and exits) and adds them to the `missingRoutes` array.
*/
fileprivate func determineMissingRoutes() {
let venueGraph = venue.destinationGraph
// Routes starting at a platform
for startPlatform in venue.platforms {
let startNode = startPlatform.exitNode
for platform in venue.platforms {
if startPlatform.name == platform.name { continue }
let destinationNode = platform.entranceNode
if !venueGraph.canRoute(startNode, toNode: destinationNode) {
let newMissingRoute = "Platform \(startPlatform.name) to Platform \(platform.name)"
missingRoutes.append(newMissingRoute)
}
} // Next platform
for exit in venue.exits {
let destinationNode = exit.entranceNode
if !venueGraph.canRoute(startNode, toNode: destinationNode) {
let newMissingRoute = "Platform \(startPlatform.name) to Exit \(exit.name)"
missingRoutes.append(newMissingRoute)
}
} // Next exit
} // Next startPlatform
// Routes starting at an exit
for startExit in venue.exits {
let startNode = startExit.exitNode
for platform in venue.platforms {
let destinationNode = platform.entranceNode
if !venueGraph.canRoute(startNode, toNode: destinationNode) {
let newMissingRoute = "Entrance \(startExit.name) to Platform \(platform.name)"
missingRoutes.append(newMissingRoute)
}
} // Next platform
for exit in venue.exits {
if startExit.name == exit.name { continue }
let destinationNode = exit.entranceNode
if !venueGraph.canRoute(startNode, toNode: destinationNode) {
let newMissingRoute = "Entrance \(startExit.name) to Exit \(exit.name)"
missingRoutes.append(newMissingRoute)
}
} // Next exit
} // Next startExit
if missingRoutes.isEmpty {
missingRoutes.append(WAYStrings.MissingKeyRoutes.Congratulations)
}
}
// MARK: - UITableViewDatasource
override func numberOfSections(in tableView: UITableView) -> Int {
return parsingData ? 0 : 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return missingRoutes.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath)
cell.textLabel?.text = missingRoutes[indexPath.row]
cell.textLabel?.numberOfLines = 0
cell.textLabel?.lineBreakMode = .byWordWrapping
return cell
}
// MARK: - UITableViewDelegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
}
|
82a72984d49cc7283091c7fd5745fd72
| 34.671875 | 123 | 0.620675 | false | false | false | false |
Wei-Xia/TVMLKitchen
|
refs/heads/swift2.2
|
Sources/Recipes/CatalogRecipe.swift
|
mit
|
1
|
//
// CatalogRecipe.swift
// TVMLKitchen
//
// Created by toshi0383 on 3/19/16.
// Copyright © 2016 toshi0383. All rights reserved.
//
import Foundation
// MARK: Content and Section
public struct Section {
struct Content {
let title: String
let thumbnailURL: String
let actionID: String?
let templateFileName: String?
let width: Int
let height: Int
}
public typealias ContentTuple = (title: String, thumbnailURL: String,
actionID: String?, templateFileName: String?, width: Int, height: Int)
let title: String
let contents: [Content]
public init(title: String, args: [ContentTuple]) {
self.title = title
self.contents = args.map(Content.init)
}
public init(title: String, args: ContentTuple...) {
self.title = title
self.contents = args.map(Content.init)
}
}
extension Section: CustomStringConvertible {
public var description: String {
var xml = ""
xml += "<listItemLockup>"
xml += "<title class=\"kitchen_highlight_bg\" >\(title)</title>"
xml += "<decorationLabel class=\"kitchen_highlight_bg\" >\(contents.count)</decorationLabel>"
xml += "<relatedContent>"
xml += "<grid>"
xml += "<section>"
xml += contents.map{ content in
var xml = ""
if let actionID = content.actionID {
xml += "<lockup actionID=\"\(actionID)\" >"
} else if let templateFileName = content.templateFileName {
xml += "<lockup template=\"\(templateFileName)\" >"
}
xml += "<img src=\"\(content.thumbnailURL)\" "
xml += "width=\"\(content.width)\" height=\"\(content.height)\" />"
xml += "<title class=\"kitchen_no_highlight_bg\">\(content.title)</title>"
xml += "</lockup>"
return xml
}.joinWithSeparator("")
xml += "</section>"
xml += "</grid>"
xml += "</relatedContent>"
xml += "</listItemLockup>"
return xml
}
}
public struct CatalogRecipe: TemplateRecipeType {
let banner: String
let sections: [Section]
public var theme = BlackTheme()
public var presentationType: PresentationType
public init(banner: String, sections: [Section],
presentationType: PresentationType = .Default) {
self.banner = banner
self.sections = sections
self.presentationType = presentationType
}
public var template: String {
var xml = ""
xml += "<catalogTemplate>"
/// Top Banner
xml += "<banner>"
xml += "<title>\(banner)</title>"
xml += "</banner>"
/// Section and Contents
xml += "<list>"
xml += "<section>"
xml += "<header>"
xml += "<title></title>"
xml += "</header>"
xml += sections.map{"\($0)"}.joinWithSeparator("")
xml += "</section>"
xml += "</list>"
xml += "</catalogTemplate>"
return xml
}
}
|
e724017b155648810eccd9fbe575edef
| 27.570093 | 101 | 0.554792 | false | false | false | false |
KeepGoing2016/Swift-
|
refs/heads/master
|
DUZB_XMJ/DUZB_XMJ/Classes/Home/View/IconCollectionViewCell.swift
|
apache-2.0
|
1
|
//
// IconCollectionViewCell.swift
// DUZB_XMJ
//
// Created by user on 16/12/28.
// Copyright © 2016年 XMJ. All rights reserved.
//
import UIKit
import Alamofire
class IconCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var iconImg: UIImageView!
@IBOutlet weak var iconL: UILabel!
var dataM:CellGroupModel?{
didSet{
iconL.text = dataM?.tag_name
// guard let iconUrl = URL(string:(dataM?.icon_url)!) else {
// return
// }
// iconImg.kf.setImage(with: iconUrl, placeholder: UIImage(named: "home_more_btn"))
if let iconUrl = URL(string: dataM?.icon_url ?? "") {
iconImg.kf.setImage(with: iconUrl, placeholder: UIImage(named: "home_more_btn"))
}else{
iconImg.image = UIImage(named: "home_more_btn")
}
}
}
override func layoutSubviews() {
super.layoutSubviews()
iconImg.layer.cornerRadius = 22
iconImg.layer.masksToBounds = true
}
override func awakeFromNib() {
super.awakeFromNib()
}
}
|
5e876ae4441ac865d7f6a90ef0ca12f2
| 26.365854 | 96 | 0.582888 | false | false | false | false |
nutletor/Start_Swift
|
refs/heads/master
|
SwiftNotesPlayground/2_02 Basic Operators.playground/Contents.swift
|
mit
|
2
|
//: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
//基本运算符(Basic Operators)
//术语
//运算符有一元、二元和三元运算符。
//• 一元运算符对单一操作对象操作(如 -a )。一元运算符分前置运算符和后置运算符,前置运算符需紧跟在操 作对象之前(如 !b ),后置运算符需紧跟在操作对象之后(如 i++ )。
//• 二元运算符操作两个操作对象(如 2 + 3 ),是中置的,因为它们出现在两个操作对象之间。
//• 三元运算符操作三个操作对象,和 C 语言一样,Swift 只有一个三元运算符,就是三目运算符( a ? b : c)。
//受运算符影响的值叫操作数,在表达式 1 + 2 中,加号 + 是二元运算符,它的两个操作数是值 1 和 2 。
//赋值运算符
//如果赋值的右边是一个多元组,它的元素可以马上被分解成多个常量或变量:
let (x, y) = (1, 2)
// 现在 x 等于 1, y 等于 2
//与 C 和 OC 不同,Swift 的赋值操作并不返回任何值。
// if x = y {
// 此句错误, 因为 x = y 并不返回任何值
// }
//这个特性使你无法把( == )错写成( = ),由于 if x = y 是错误代码,Swift帮你避免此类错误的的发生。
//算术运算符
//Swift 中所有数值类型都支持了基本的四则运算:
//• 加法(+)
//• 减法(-)
//• 乘法(*)
//• 除法(/)
//与 C 语言和 OC 不同的是,Swift 中算术运算符( + , - , * , / , % 等)会 检测并不允许值溢出,以此来避免保存变量时由于变量大于或小于其类型所能承载的范围时导致的异常结果。但是你可以使用 Swift 的溢出运算符来实现溢出运算(如 a &+ b )
//加法运算符也可用于 String 的拼接:
"hello, " + "world"
//求余运算符
//求余运算( a % b )是计算 b 的多少倍刚刚好可以容入 a ,返回多出来的那部分(余数)。
//注意:求余运算( % )在其他语言也叫取模运算。然而严格说来,我们看该运算符对负数的操作结果,"求余"比"取 模"更合适些。
9 % 4
-9 % 4
9 % -4
//在对负数 b 求余时, b 的符号会被忽略。这意味着 a % b 和 a % -b 的结果是相同的。
//浮点数求余计算
//不同于 C 和 OC,Swift 中是可以对浮点数进行求余的。
8 % 2.5
//结果是一个 Double 值 0.5
//自增和自减运算
//对变量本身加1或减1的自增( ++ )和自减( -- )的缩略算符,操作对象可以是整形和浮点型。
//++i是i = i + 1的简写;--i是i = i - 1的简写
//运算符即可修改了i的值也可以返回i的值
//当 ++ 前置的时候,先自増再返回;当 ++ 后置的时候,先返回再自增。
//一元负号运算符
//数值的正负号可以使用前缀 - (即一元负号)来切换:
let three = 3
let minusThree = -three // minusThree 等于 -3
let plusThree = -minusThree // plusThree 等于 3, 或 "负负3"
//一元正号运算符
//一元正号( + )不做任何改变地返回操作数的值:
let minusSix = -6
let alsoMinusSix = +minusSix // alsoMinusSix 等于 -6
//组合赋值运算符(Compound Assignment Operators)
var a = 1
a += 2 // a 现在是 3
//注意:复合赋值运算没有返回值, let b = a += 2 这类代码是错误
//比较运算符
//所有标准 C 语言中的比较运算都可以在 Swift 中使用:
//• 等于( a == b )
//• 不等于( a != b )
//• 大于( a > b )
//• 小于( a < b )
//• 大于等于( a >= b )
//• 小于等于( a <= b )
//注意: Swift 也提供恒等 === 和不恒等 !== 来判断两个对象是否引用同一个对象实例。
//每个比较运算都返回了一个标识表达式是否成立的布尔值
//三目运算符(Ternary Conditional Operator)
//三目运算符的特殊在于它是有三个操作数的运算符,它的原型是 问题 ? 答案1 : 答案2
//如果 问题 成立,返回 答案1 的结果; 如果不成立,返回 答案2 的结果。
//空合运算符(Nil Coalescing Operator)
//空合运算符(a ?? b)将对可选类型 a 进行空判断,如果 a 包含一个值就进行解封,否则就返回一个默认值 b
//该运算符有两个条件:
//• 表达式 a 必须是Optional类型
//• 默认值 b 的类型必须要和 a 存储值的类型保持一致
//空合运算符是对以下代码的简短表达方法:
//a != nil ? a! : b
//注意: 如果 a 为非空值( non-nil ),那么值 b 将不会被估值。这也就是所谓的短路求值。
//区间运算符
//闭区间运算符
//闭区间运算符( a...b )定义一个包含从 a 到 b (包括 a 和 b )的所有值的区间, b 必须大于等于 a
for index in 1...5 {
print("\(index) * 5 = \(index * 5)")
}
// 1 * 5 = 5
// 2 * 5 = 10
// 3 * 5 = 15
// 4 * 5 = 20
// 5 * 5 = 25
//半开区间运算符
//半开区间( a..<b )定义一个从 a 到 b 但不包括 b 的区间
let names = ["Anna", "Alex", "Brian", "Jack"]
let count = names.count
for i in 0..<count {
print("第 \(i + 1) 个人叫 \(names[i])") }
// 第 1 个人叫 Anna // 第 2 个人叫 Alex // 第 3 个人叫 Brian // 第 4 个人叫 Jack
//逻辑运算
//逻辑运算的操作对象是逻辑布尔值。Swift 支持基于 C 语言的三个标准逻辑运算。
// • 逻辑非(!a)
// • 逻辑与( a && b )
// • 逻辑或( a || b )
//注意:逻辑或、逻辑与的短路计算
//逻辑运算符组合计算
// if enteredDoorCode && passedRetinaScan || hasDoorKey || knowsOverridePassword {
// print("Welcome!")
//} else {
// print("ACCESS DENIED")
//}
//无论怎样, && 和 || 始终只能操作两个值。所以这实际是三个简单逻辑连续操作的结果。
//注意: Swift 逻辑操作符 && 和 || 是左结合的,这意味着拥有多元逻辑操作符的复合表达式优先计算最左边的子表达式。
//为了一个复杂表达式更容易读懂,在合适的地方使用括号()来明确优先级是很有效的
|
9f992d6af604c42ead71ef2fa123f9a8
| 21.328767 | 140 | 0.621166 | false | false | false | false |
Chriskuei/Bon-for-Mac
|
refs/heads/master
|
Bon/BonConfig.swift
|
mit
|
1
|
//
// BonConfig.swift
// Bon
//
// Created by Chris on 16/4/19.
// Copyright © 2016年 Chris. All rights reserved.
//
import Cocoa
import Foundation
class BonConfig {
static let appGroupID: String = "group.chriskuei.Bon"
static let BonFont: String = "Avenir Book"
//static let ScreenWidth: CGFloat = UIScreen.mainScreen().bounds.width
//static let ScreenHeight: CGFloat = UIScreen.mainScreen().bounds.height
struct BonNotification {
static let GetOnlineInfo = "GetOnlineInfo"
static let ShowLoginView = "ShowLoginView"
static let HideLoginView = "ShowLoginView"
}
}
|
bdafa166f33eb47866d5325b1fb0ea6e
| 23.538462 | 76 | 0.673469 | false | true | false | false |
bm842/Brokers
|
refs/heads/master
|
Sources/PlaybackOrder.swift
|
mit
|
2
|
/*
The MIT License (MIT)
Copyright (c) 2016 Bertrand Marlier
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE
*/
import Foundation
public class PlaybackOrder: GenericOrder, Order
{
public func modify(change parameters: [OrderParameter], completion: @escaping (RequestStatus) -> ())
{
let playbackInstrument = instrument as! PlaybackInstrument
guard let tick = playbackInstrument.currentTick else
{
completion(PlaybackStatus.noTick)
return
}
for param in parameters
{
switch param
{
case .stopLoss(let price): self.stopLoss = price
case .takeProfit(let price): self.takeProfit = price
case .entry(let price): self.entry = price!
case .expiry(let time): self.expiry = time! // expiry is mandatory in working orders
}
}
modify(atTime: tick.time, parameters: parameters)
completion(PlaybackStatus.success)
}
public override func cancel(_ completion: @escaping (RequestStatus) -> ())
{
let playbackInstrument = instrument as! PlaybackInstrument
guard let tick = playbackInstrument.currentTick else
{
completion(PlaybackStatus.noTick)
return
}
super.cancel(completion)
genericInstrument.notify(tradeEvent: .orderClosed(info: OrderClosure(orderId: id, time: tick.time, reason: .cancelled)))
completion(PlaybackStatus.success)
}
}
|
b2768a1a33fec95219248b355953606a
| 34.739726 | 128 | 0.669222 | false | false | false | false |
Shun87/OpenAdblock
|
refs/heads/master
|
Open Adblock/Open Adblock/RulesViewController.swift
|
apache-2.0
|
5
|
//
// RulesViewController.swift
// Open Adblock
//
// Created by Saagar Jha on 8/14/15.
// Copyright © 2015 OpenAdblock. All rights reserved.
//
import UIKit
class RulesViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
let cellIdentifer = "rule"
@IBOutlet weak var rulesTableView: UITableView! {
didSet {
rulesTableView.delegate = self
}
}
var rules: [String]!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
rules = Adblocker.sharedInstance.ruleNames
navigationController?.setToolbarHidden(false, animated: false)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//print(rules)
//return 0
return rules.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifer) as UITableViewCell!
cell.textLabel?.text = rules[indexPath.row]
return cell
}
/*
// 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.
}
*/
}
|
b5a47be562f58559a5fa43055aea9745
| 27.983871 | 109 | 0.670006 | false | false | false | false |
MadArkitekt/Swift_Tutorials_And_Demos
|
refs/heads/master
|
CustomSwiftUI/techEdGradientPreview/GradientView.swift
|
gpl-2.0
|
1
|
//
// GradientView.swift
// CustomSwiftUI
//
// Created by Edward Salter on 9/19/14.
// Copyright (c) 2014 Edward Salter. All rights reserved.
//
import UIKit
import QuartzCore
@IBDesignable class GradientView: UIView {
@IBInspectable var startColor: UIColor = UIColor.whiteColor() {
didSet{
setupView()
}
}
@IBInspectable var endColor: UIColor = UIColor.blackColor() {
didSet{
setupView()
}
}
@IBInspectable var isHorizontal: Bool = false {
didSet{
setupView()
}
}
@IBInspectable var roundness: CGFloat = 0.0 {
didSet{
setupView()
}
}
//MARK: Overrides
override class func layerClass()->AnyClass {
return CAGradientLayer.self
}
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
//MARK: Framework Funcs
private func setupView() {
let colors:Array<AnyObject> = [startColor.CGColor, endColor.CGColor]
gradientLayer.colors = colors
gradientLayer.cornerRadius = roundness
gradientLayer.startPoint = CGPoint(x:0, y:0)
if (isHorizontal) {
gradientLayer.endPoint = CGPoint(x:1, y:0)
}else{
gradientLayer.endPoint = CGPoint(x:0, y:1)
}
self.setNeedsDisplay()
}
//MARK: Main Layer = CAGradientLayer
var gradientLayer: CAGradientLayer {
return layer as CAGradientLayer
}
}
|
3d1069cdff47ae99fcd82ee27818f46c
| 22.428571 | 76 | 0.581098 | false | false | false | false |
hovansuit/FoodAndFitness
|
refs/heads/master
|
FoodAndFitness/Controllers/TrackingDetail/TrackingDetailController.swift
|
mit
|
1
|
//
// TrackingDetailController.swift
// FoodAndFitness
//
// Created by Mylo Ho on 5/29/17.
// Copyright © 2017 SuHoVan. All rights reserved.
//
import MapKit
import UIKit
import CoreLocation
class TrackingDetailController: BaseViewController {
@IBOutlet fileprivate(set) weak var mapView: MKMapView!
@IBOutlet fileprivate(set) weak var activeLabel: UILabel!
@IBOutlet fileprivate(set) weak var durationLabel: UILabel!
@IBOutlet fileprivate(set) weak var distanceLabel: UILabel!
var viewModel: TrackingDetailViewModel!
struct Data {
var active: String
var duration: String
var distance: String
}
var data: Data? {
didSet {
guard let data = data else { return }
activeLabel.text = data.active
durationLabel.text = data.duration
distanceLabel.text = data.distance
}
}
override func setupUI() {
super.setupUI()
title = Strings.tracking
configureMapView()
configInfor()
}
private func configureMapView() {
mapView.delegate = self
mapView.add(MKPolyline(coordinates: viewModel.coordinatesForMap(), count: viewModel.coordinatesForMap().count))
}
private func configInfor() {
data = viewModel.data()
}
@IBAction func save(_ sender: Any) {
self.viewModel.save(completion: { [weak self](result) in
guard let this = self else { return }
switch result {
case .success(_):
this.navigationController?.popViewController(animated: true)
case .failure(let error):
error.show()
}
})
}
@IBAction func cancel(_ sender: Any) {
navigationController?.popViewController(animated: true)
}
}
// MARK: - MKMapViewDelegate
extension TrackingDetailController: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let renderer = MKPolylineRenderer(overlay: overlay)
renderer.strokeColor = UIColor.blue
renderer.lineWidth = 2
return renderer
}
}
|
24c1d84bb4f33cbe9f9084371ac7dcc6
| 27.103896 | 119 | 0.636322 | false | true | false | false |
ReactorKit/ReactorKit
|
refs/heads/master
|
Sources/ReactorKit/IdentityEquatable.swift
|
mit
|
1
|
//
// IdentityEquatable.swift
// ReactorKit
//
// Created by Suyeol Jeon on 2019/10/17.
//
public protocol IdentityEquatable: AnyObject, Equatable {}
extension IdentityEquatable {
public static func == (lhs: Self, rhs: Self) -> Bool {
lhs === rhs
}
}
|
8c7d492f5532e9544e6ebbe88d0f457c
| 17.857143 | 58 | 0.666667 | false | false | false | false |
ArchimboldiMao/remotex-iOS
|
refs/heads/master
|
remotex-iOS/Constants.swift
|
apache-2.0
|
2
|
//
// Constants.swift
// remotex-iOS
//
// Created by archimboldi on 10/05/2017.
// Copyright © 2017 me.archimboldi. All rights reserved.
//
import UIKit
struct Constants {
struct AppLayout {
static let LogoForegroundColor: UIColor = UIColor.init(red: 0.31, green: 0.74, blue: 1.0, alpha: 1.0)
}
struct NavigationBarLayout {
static let StatusBarBackgroundColor: UIColor = UIColor.init(red: 0.98, green: 0.98, blue: 0.98, alpha: 0.95)
}
struct TableLayout {
static let BackgroundColor: UIColor = UIColor.init(red: 0.98, green: 0.98, blue: 0.98, alpha: 1.0)
}
struct CellLayout {
static let TitleFontSize: CGFloat = 18.0
static let TitleForegroundColor: UIColor = UIColor.init(red: 0.2, green: 0.2, blue: 0.2, alpha: 1.0)
static let PriceFontSize: CGFloat = 16.0
static let TagFontSize: CGFloat = 14.0
static let TagForegroundColor: UIColor = UIColor.init(red: 0.4, green: 0.4, blue: 0.4, alpha: 1.0)
static let TagBackgroundColor: UIColor = UIColor.init(red: 0.96, green: 0.96, blue: 0.96, alpha: 1.0)
static let AbstractFontSize: CGFloat = 16.0
static let AbstractForegroundColor: UIColor = TitleForegroundColor
static let DateFontSize: CGFloat = 14.0
static let DateForegroundColor: UIColor = UIColor.init(red: 0.4, green: 0.4, blue: 0.4, alpha: 1.0)
static let PriceForegroundColor: UIColor = UIColor.init(red: 0.4, green: 0.4, blue: 0.4, alpha: 1.0)
}
struct AboutLayout {
static let TitleFontSize: CGFloat = 25.0
static let SloganFontSize: CGFloat = 19.0
static let DescriptionFontSize: CGFloat = 16.0
static let VersionFontSize: CGFloat = 12.0
}
struct ShareContext {
static let TitleText = "RemoteX 远程工作空间 -- 快乐工作 认真生活"
static let AppStoreLinkURL = NSURL.init(string: "https://itunes.apple.com/app/id1236035785")!
static let LogoImage = UIImage(named: "logo")!
}
struct AppStore {
static let TitleText = "App Store"
static let ReviewURL = URL(string: "itms-apps://itunes.apple.com/app/id1236035785?action=write-review")!
}
struct MessageDescription {
static let NoInternetConnection = "网络连接超时。"
}
}
|
467ca499653945bfc14db7b4cf024db2
| 35.484375 | 116 | 0.639829 | false | false | false | false |
bencochran/KaleidoscopeLang
|
refs/heads/master
|
KaleidoscopeLang/Parser.swift
|
bsd-3-clause
|
1
|
//
// Parser.swift
// KaleidoscopeLang
//
// Created by Ben Cochran on 11/8/15.
// Copyright © 2015 Ben Cochran. All rights reserved.
//
import Madness
import Prelude
import Either
internal typealias ValueExpressionParser = Parser<[Token], ValueExpression>.Function
internal typealias TopLevelExpressionParser = Parser<[Token], TopLevelExpression>.Function
internal typealias ExpressionParser = Parser<[Token], Expression>.Function
// MARK: Token unwrappers
private let identifier: Parser<[Token], String>.Function = attempt { $0.identifier }
private let double: Parser<[Token], Double>.Function = attempt { $0.number }
// MARK: Value expressions
private let valueExpression: ValueExpressionParser = fix { valueExpression in
/// variable ::= Identifier
let variable: ValueExpressionParser = VariableExpression.init <^> identifier
/// number ::= Number
let number: ValueExpressionParser = NumberExpression.init <^> double
/// parenExpression ::= "(" valueExpression ")"
let parenExpression = %(.Character("(")) *> valueExpression <* %(.Character(")"))
/// callargs ::= "(" valueExpression* ")"
let callargs = %(.Character("(")) *> many(valueExpression) <* %(.Character(")"))
/// call ::= Identifier callargs
let call: ValueExpressionParser = curry(CallExpression.init) <^> identifier <*> callargs
/// primary
/// ::= call
/// ::= variable
/// ::= number
/// ::= parenExpression
let primary = call <|> variable <|> number <|> parenExpression
/// infixOperator
/// ::= "+"
/// ::= "-"
/// ::= "*"
/// ::= "/"
let infixOperator: Parser<[Token], Token>.Function = oneOf([
.Character("+"),
.Character("-"),
.Character("*"),
.Character("/")
])
/// infixRight ::= infixOperator primary
let infixRight = curry(pair) <^> infixOperator <*> primary
/// infix ::= primary infixRight*
let repackedInfix = curry(map(id, ArraySlice.init)) <^> primary <*> many(infixRight)
let infix: ValueExpressionParser = collapsePackedInfix <^> repackedInfix
/// valueExpression
/// ::= infix
/// ::= primary
return infix <|> primary
}
// MARK: Top-level expressions
/// prototypeArgs ::= "(" Identifier* ")"
private let prototypeArgs = %(.Character("(")) *> many(identifier) <* %(.Character(")"))
/// prototype ::= Identifier prototypeArgs
private let prototype = curry(PrototypeExpression.init) <^> identifier <*> prototypeArgs
/// definition ::= "def" prototype expression
private let definition: TopLevelExpressionParser = %(Token.Def) *> (curry(FunctionExpression.init) <^> prototype <*> valueExpression)
/// external ::= "extern" prototype
private let external: TopLevelExpressionParser = id <^> ( %(Token.Extern) *> prototype )
/// top
/// ::= definition
/// ::= external
private let top = definition <|> external
/// topLevelExpression ::= top EndOfStatement
internal let topLevelExpression = top <* %(.EndOfStatement)
/// expression
/// ::= topLevelExpression
/// ::= valueExpression
internal let expression = topLevelExpression <|> valueExpression
// MARK: Public
/// Parse a series of tokens into a value expression
public func parseValueExpression(tokens: [Token]) -> Either<Error, ValueExpression> {
return parse(valueExpression, input: tokens).mapLeft(Error.treeError(tokens))
}
/// Lex and parse a string into a value expression
public func parseValueExpression(string: String) -> Either<Error, ValueExpression> {
return lex(string) >>- parseValueExpression
}
/// Parse a series of tokens into a top-level expression
public func parseTopLevelExpression(tokens: [Token]) -> Either<Error, TopLevelExpression> {
return parse(topLevelExpression, input: tokens).mapLeft(Error.treeError(tokens))
}
/// Lex and parse a string into a top-level expression
public func parseTopLevelExpression(string: String) -> Either<Error, TopLevelExpression> {
return lex(string) >>- parseTopLevelExpression
}
/// Parse a series of tokens into a value or top-level expression
public func parse(tokens: [Token]) -> Either<Error, Expression> {
return parse(expression, input: tokens).mapLeft(Error.treeError(tokens)).map(collapseExpression)
}
/// Lex and parse a string into a value or top-level expression
public func parse(string: String) -> Either<Error, Expression> {
return lex(string) >>- parse
}
// MARK: Private
private func collapseExpression(expression: Either<TopLevelExpression, ValueExpression>) -> Expression {
return expression.either(ifLeft: id, ifRight: id)
}
// MARK: Infix Helpers
private func collapsePackedInfix(binop: (ValueExpression, ArraySlice<(Token, ValueExpression)>)) -> ValueExpression {
// Recursion base
guard let rightHalf = binop.1.first else { return binop.0 }
let code = rightHalf.0.character!
let rest = (rightHalf.1, binop.1.dropFirst())
let left = binop.0
return BinaryOperatorExpression(code: code, left: left, right: collapsePackedInfix(rest))
}
|
f7b3b558ca2ec0c1d501569917530671
| 33.653061 | 133 | 0.678053 | false | false | false | false |
fdanise/loadingButton
|
refs/heads/master
|
ExtensionUIButton.swift
|
mit
|
1
|
//
// ExtensionUIButton.swift
//
// Created by Ferdinando Danise on 07/09/17.
// Copyright © 2017 Ferdinando Danise. All rights reserved.
//
import UIKit
extension UIButton {
func startLoading(color: UIColor) {
let shapeOuter = shapeLayerOuter(color: color)
let shapeInner = shapeLayerInner(color: color)
shapeOuter.add(animationOuter(), forKey: nil)
shapeInner.add(animationInner(), forKey: nil)
self.layer.addSublayer(shapeOuter)
self.layer.addSublayer(shapeInner)
}
func stopLoading(){
UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseOut, animations: {
self.alpha = 0
}) { (true) in
self.layer.removeFromSuperlayer()
}
}
private func shapeLayerOuter(color: UIColor) -> CAShapeLayer{
let circleOut = UIBezierPath(arcCenter: CGPoint(x: self.bounds.midX, y: self.bounds.midY),
radius: CGFloat(self.bounds.height * 0.4),
startAngle: CGFloat(0),
endAngle:CGFloat(Double.pi * 2),
clockwise: true)
let shapeLayerOut = CAShapeLayer()
shapeLayerOut.path = circleOut.cgPath
shapeLayerOut.fillColor = UIColor.clear.cgColor
shapeLayerOut.strokeColor = color.cgColor
shapeLayerOut.strokeStart = 0.1
shapeLayerOut.strokeEnd = 1
shapeLayerOut.lineWidth = 3.5
shapeLayerOut.lineCap = "round"
shapeLayerOut.frame = self.bounds
return shapeLayerOut
}
private func shapeLayerInner(color: UIColor) -> CAShapeLayer{
let circleIn = UIBezierPath(arcCenter: CGPoint(x: self.bounds.midX, y: self.bounds.midY),
radius: CGFloat(self.bounds.height * 0.2),
startAngle: CGFloat(0),
endAngle: CGFloat(Double.pi * 2),
clockwise: false)
let shapeLayerIn = CAShapeLayer()
shapeLayerIn.path = circleIn.cgPath
shapeLayerIn.fillColor = UIColor.clear.cgColor
shapeLayerIn.strokeColor = color.cgColor
shapeLayerIn.strokeStart = 0.1
shapeLayerIn.strokeEnd = 1
shapeLayerIn.lineWidth = 3.2
shapeLayerIn.lineCap = "round"
shapeLayerIn.frame = self.bounds
return shapeLayerIn
}
private func animationOuter() -> CABasicAnimation{
let animationOut = CABasicAnimation(keyPath: "transform.rotation")
animationOut.fromValue = 0
animationOut.toValue = Double.pi * 2
animationOut.duration = 1
animationOut.repeatCount = Float.infinity
return animationOut
}
private func animationInner() -> CABasicAnimation {
let animationIn = CABasicAnimation(keyPath: "transform.rotation")
animationIn.fromValue = 0
animationIn.toValue = -(Double.pi * 2)
animationIn.duration = 1
animationIn.repeatCount = Float.infinity
return animationIn
}
}
|
c16dd1a2138d63731d53995964620237
| 31.782178 | 98 | 0.57022 | false | false | false | false |
the-blue-alliance/the-blue-alliance-ios
|
refs/heads/master
|
the-blue-alliance-ios/View Elements/Settings/Notifications/NotificationStatusTableViewCell.swift
|
mit
|
1
|
import Foundation
import UIKit
class NotificationStatusTableViewCell: UITableViewCell {
var viewModel: NotificationStatusCellViewModel? {
didSet {
configureCell()
}
}
// MARK: - Reusable
static var nib: UINib? {
return UINib(nibName: String(describing: self), bundle: nil)
}
// MARK: - Interface Builder
@IBOutlet private weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet private weak var statusImageView: UIImageView!
@IBOutlet private weak var titleLabel: UILabel!
// MARK: - Private Methods
private func configureCell() {
guard let viewModel = viewModel else {
return
}
titleLabel.alpha = 1.0
titleLabel.text = viewModel.title
statusImageView.image = nil
activityIndicator.isHidden = true
selectionStyle = .none
isUserInteractionEnabled = false
accessoryType = .none
switch viewModel.notificationStatus {
case .unknown:
titleLabel.alpha = 0.5
case .loading:
activityIndicator.isHidden = false
activityIndicator.startAnimating()
case .valid:
statusImageView.image = UIImage(systemName: "checkmark.circle.fill")
statusImageView.tintColor = UIColor.primaryBlue
case .invalid:
selectionStyle = .default
accessoryType = .disclosureIndicator
isUserInteractionEnabled = true
statusImageView.image = UIImage(systemName: "xmark.circle.fill")
statusImageView.tintColor = UIColor.systemRed
}
}
}
|
21098f50f30b79a627d4f5531faa38c0
| 27.431034 | 80 | 0.635537 | false | false | false | false |
Authman2/Pix
|
refs/heads/master
|
Pix/ProfilePage.swift
|
gpl-3.0
|
1
|
//
// ProfilePage.swift
// Pix
//
// Created by Adeola Uthman on 12/23/16.
// Copyright © 2016 Adeola Uthman. All rights reserved.
//
import UIKit
import Foundation
import SnapKit
import Firebase
import PullToRefreshSwift
import OneSignal
import IGListKit
class ProfilePage: ProfileDisplayPage, IGListAdapterDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
/********************************
*
* VARIABLES
*
********************************/
/* The adapter. */
lazy var adapter: IGListAdapter = {
return IGListAdapter(updater: IGListAdapterUpdater(), viewController: self, workingRangeSize: 1);
}();
/* The collection view. */
let collectionView: IGListCollectionView = {
let layout = IGListGridCollectionViewLayout();
let view = IGListCollectionView(frame: CGRect.zero, collectionViewLayout: layout);
view.alwaysBounceVertical = true;
return view;
}();
/* The image view that displays the profile picture. */
let profilePicture: CircleImageView = {
let i = CircleImageView();
i.translatesAutoresizingMaskIntoConstraints = false;
i.isUserInteractionEnabled = true;
i.backgroundColor = UIColor.gray;
return i;
}();
/* A label to display whether or not this user is private. */
let privateLabel: UILabel = {
let a = UILabel();
a.translatesAutoresizingMaskIntoConstraints = false;
a.isUserInteractionEnabled = false;
a.font = UIFont(name: a.font.fontName, size: 15);
a.numberOfLines = 0;
a.textColor = UIColor(red: 21/255, green: 180/255, blue: 133/255, alpha: 1).lighter();
a.textAlignment = .center;
a.isHidden = true;
return a;
}();
/* Label that shows the user's name. */
let nameLabel: UILabel = {
let n = UILabel();
n.translatesAutoresizingMaskIntoConstraints = false;
n.isUserInteractionEnabled = false;
n.font = UIFont(name: n.font.fontName, size: 20);
n.textColor = UIColor.black;
n.textAlignment = .center;
return n;
}();
/* Label that shows the number of followers this user has. */
let followersLabel: UILabel = {
let n = UILabel();
n.translatesAutoresizingMaskIntoConstraints = false;
n.isUserInteractionEnabled = false;
n.font = UIFont(name: n.font.fontName, size: 15);
n.textColor = UIColor.black;
n.textAlignment = .center;
return n;
}();
/* Label that shows the number of people this user is following. */
let followingLabel: UILabel = {
let n = UILabel();
n.translatesAutoresizingMaskIntoConstraints = false;
n.isUserInteractionEnabled = false;
n.font = UIFont(name: n.font.fontName, size: 15);
n.textColor = UIColor.black;
n.textAlignment = .center;
return n;
}();
/* The button used for editing the profile. */
var editProfileButton: UIBarButtonItem!;
/* Image picker */
let imgPicker = UIImagePickerController();
var canChangeProfilePic = false;
var tap: UITapGestureRecognizer!;
/* Firebase reference. */
let fireRef: FIRDatabaseReference = FIRDatabase.database().reference();
/********************************
*
* METHODS
*
********************************/
override func viewDidLoad() {
super.viewDidLoad();
view.backgroundColor = UIColor(red: 239/255, green: 255/255, blue:245/255, alpha: 1);
navigationController?.navigationBar.isHidden = false;
navigationItem.hidesBackButton = true;
navigationItem.title = "Profile";
viewcontrollerName = "Profile";
setupCollectionView();
view.addSubview(collectionView)
/* Setup/Layout the view. */
view.addSubview(privateLabel);
view.addSubview(profilePicture);
view.addSubview(nameLabel);
view.addSubview(followersLabel);
view.addSubview(followingLabel);
profilePicture.snp.makeConstraints { (maker: ConstraintMaker) in
maker.centerX.equalTo(view.snp.centerX);
maker.bottom.equalTo(view.snp.centerY).offset(-100);
maker.width.equalTo(90);
maker.height.equalTo(90);
}
privateLabel.snp.makeConstraints { (maker: ConstraintMaker) in
maker.centerX.equalTo(view.snp.centerX);
maker.bottom.equalTo(profilePicture.snp.top).offset(-10);
maker.width.equalTo(view.width);
maker.height.equalTo(50);
}
nameLabel.snp.makeConstraints { (maker: ConstraintMaker) in
maker.centerX.equalTo(view.snp.centerX);
maker.width.equalTo(view.width);
maker.height.equalTo(25);
maker.top.equalTo(profilePicture.snp.bottom).offset(20);
}
followersLabel.snp.makeConstraints { (maker: ConstraintMaker) in
maker.centerX.equalTo(view.snp.centerX);
maker.width.equalTo(view.width);
maker.height.equalTo(20);
maker.top.equalTo(nameLabel.snp.bottom).offset(10);
}
followingLabel.snp.makeConstraints { (maker: ConstraintMaker) in
maker.centerX.equalTo(view.snp.centerX);
maker.width.equalTo(view.width);
maker.height.equalTo(20);
maker.top.equalTo(followersLabel.snp.bottom).offset(5);
}
collectionView.snp.makeConstraints({ (maker: ConstraintMaker) in
maker.width.equalTo(view.frame.width);
maker.centerX.equalTo(view);
maker.top.equalTo(followingLabel.snp.bottom).offset(10);
maker.bottom.equalTo(view.snp.bottom);
})
/* Add the pull to refresh function. */
var options = PullToRefreshOption();
options.fixedSectionHeader = false;
collectionView.addPullRefresh(options: options, refreshCompletion: { (Void) in
//self.adapter.performUpdates(animated: true, completion: nil);
self.adapter.reloadData(completion: { (b: Bool) in
self.reloadLabels();
self.collectionView.stopPullRefreshEver();
})
});
/* Bar button item. */
editProfileButton = UIBarButtonItem(title: "Edit", style: .plain, target: self, action: #selector(editProfile));
editProfileButton.tintColor = .white;
navigationItem.rightBarButtonItem = editProfileButton;
/* Profile pic image picker. */
imgPicker.delegate = self;
imgPicker.sourceType = .photoLibrary;
tap = UITapGestureRecognizer(target: self, action: #selector(uploadProfilePic));
profilePicture.addGestureRecognizer(tap);
} // End of viewDidLoad().
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated);
lastProfile = self;
self.adapter.reloadData(completion: nil);
editProfileButton.isEnabled = true;
editProfileButton.tintColor = .white;
self.reloadLabels();
profilePicture.addGestureRecognizer(tap);
} // End of viewDidAppear().
func reloadLabels() {
if let cUser = Networking.currentUser {
nameLabel.text = "\(cUser.firstName) \(cUser.lastName)";
followersLabel.text = "Followers: \(cUser.followers.count)";
followingLabel.text = "Following: \(cUser.following.count)";
profilePicture.image = cUser.profilepic;
privateLabel.text = "\(cUser.username) is private. Send a follow request to see their photos.";
privateLabel.isHidden = true;
collectionView.isHidden = false;
profilePicture.image = cUser.profilepic;
}
}
@objc func logout() {
do {
try FIRAuth.auth()?.signOut();
Networking.currentUser = nil;
feedPage.followingUsers.removeAll();
feedPage.postFeed.removeAll();
explorePage.listOfUsers.removeAll();
explorePage.listOfUsers_fb.removeAllObjects();
let _ = navigationController?.popToRootViewController(animated: true);
self.debug(message: "Signed out!");
self.debug(message: "Logged out!");
} catch {
self.debug(message: "There was a problem signing out.");
}
}
@objc func editProfile() {
navigationController?.pushViewController(EditProfilePage(), animated: true);
}
/********************************
*
* IMAGE PICKER
*
********************************/
@objc func uploadProfilePic() {
show(imgPicker, sender: self);
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let photo = info[UIImagePickerControllerOriginalImage] as? UIImage {
// Set the picture on the image view and also on the actual user object.
profilePicture.image = photo;
let id = Networking.currentUser!.profilePicName;
Networking.currentUser!.profilepic = photo;
// Delete the old picture from firebase, and replace it with the new one, but keep the same id.
let storageRef = FIRStorageReference().child("\(Networking.currentUser!.uid)/\(id!).jpg");
storageRef.delete { error in
// If there's an error.
if let error = error {
self.debug(message: "There was an error deleting the image: \(error)");
} else {
// Save the new image.
let data = UIImageJPEGRepresentation(photo, 100) as NSData?;
let _ = storageRef.put(data! as Data, metadata: nil) { (metaData, error) in
if (error == nil) {
let post = Post(photo: photo, caption: "", Uploader: Networking.currentUser!, ID: id!);
post.isProfilePicture = true;
let postObj = post.toDictionary();
Networking.saveObject(object: postObj, path: "Photos/\(Networking.currentUser!.uid)/\(id!)", success: {
}, failure: { (err: Error) in
});
// self.fireRef.child("Photos").child("\(Networking.currentUser!.uid)").child("\(id!)").setValue(postObj);
self.debug(message: "Old profile picture was removed; replace with new one.");
} else {
print(error.debugDescription);
}
}
}
}
// Dismiss view controller.
imgPicker.dismiss(animated: true, completion: nil);
}
}
/********************************
*
* COLLECTION VIEW
*
********************************/
func setupCollectionView() {
collectionView.register(ProfilePageCell.self, forCellWithReuseIdentifier: "Cell");
collectionView.backgroundColor = view.backgroundColor;
adapter.collectionView = collectionView;
adapter.dataSource = self;
}
func objects(for listAdapter: IGListAdapter) -> [IGListDiffable] {
if let cUser = Networking.currentUser {
return cUser.posts;
} else {
return [];
}
}
func listAdapter(_ listAdapter: IGListAdapter, sectionControllerFor object: Any) -> IGListSectionController {
return ProfileSectionController(vc: self);
}
func emptyView(for listAdapter: IGListAdapter) -> UIView? {
return EmptyPhotoView(place: .top);
}
}
|
101c46d6bb716e603e60ad8774779c74
| 31.551282 | 133 | 0.549508 | false | false | false | false |
LoopKit/LoopKit
|
refs/heads/dev
|
LoopKit/SettingsStore.swift
|
mit
|
1
|
//
// SettingsStore.swift
// LoopKit
//
// Created by Darin Krauss on 10/14/19.
// Copyright © 2019 LoopKit Authors. All rights reserved.
//
import os.log
import Foundation
import CoreData
import HealthKit
public protocol SettingsStoreDelegate: AnyObject {
/**
Informs the delegate that the settings store has updated settings data.
- Parameter settingsStore: The settings store that has updated settings data.
*/
func settingsStoreHasUpdatedSettingsData(_ settingsStore: SettingsStore)
}
public class SettingsStore {
public weak var delegate: SettingsStoreDelegate?
public private(set) var latestSettings: StoredSettings? {
get {
return lockedLatestSettings.value
}
set {
lockedLatestSettings.value = newValue
}
}
private let lockedLatestSettings: Locked<StoredSettings?>
private let store: PersistenceController
private let expireAfter: TimeInterval
private let dataAccessQueue = DispatchQueue(label: "com.loopkit.SettingsStore.dataAccessQueue", qos: .utility)
private let log = OSLog(category: "SettingsStore")
public init(store: PersistenceController, expireAfter: TimeInterval) {
self.store = store
self.expireAfter = expireAfter
self.lockedLatestSettings = Locked(nil)
dataAccessQueue.sync {
self.store.managedObjectContext.performAndWait {
let storedRequest: NSFetchRequest<SettingsObject> = SettingsObject.fetchRequest()
storedRequest.sortDescriptors = [NSSortDescriptor(key: "modificationCounter", ascending: false)]
storedRequest.fetchLimit = 1
do {
let stored = try self.store.managedObjectContext.fetch(storedRequest)
self.latestSettings = stored.first.flatMap { self.decodeSettings(fromData: $0.data) }
} catch let error {
self.log.error("Error fetching latest settings: %@", String(describing: error))
return
}
}
}
}
func storeSettings(_ settings: StoredSettings) async {
await withCheckedContinuation { continuation in
storeSettings(settings) { (_) in
continuation.resume()
}
}
}
public func storeSettings(_ settings: StoredSettings, completion: @escaping (Error?) -> Void) {
dataAccessQueue.async {
var error: Error?
if let data = self.encodeSettings(settings) {
self.store.managedObjectContext.performAndWait {
let object = SettingsObject(context: self.store.managedObjectContext)
object.data = data
object.date = settings.date
error = self.store.save()
}
}
self.latestSettings = settings
self.purgeExpiredSettings()
completion(error)
}
}
public var expireDate: Date {
return Date(timeIntervalSinceNow: -expireAfter)
}
private func purgeExpiredSettings() {
guard let latestSettings = latestSettings else {
return
}
guard expireDate < latestSettings.date else {
return
}
purgeSettingsObjects(before: expireDate)
}
public func purgeSettings(before date: Date, completion: @escaping (Error?) -> Void) {
dataAccessQueue.async {
self.purgeSettingsObjects(before: date, completion: completion)
}
}
private func purgeSettingsObjects(before date: Date, completion: ((Error?) -> Void)? = nil) {
dispatchPrecondition(condition: .onQueue(dataAccessQueue))
var purgeError: Error?
store.managedObjectContext.performAndWait {
do {
let count = try self.store.managedObjectContext.purgeObjects(of: SettingsObject.self, matching: NSPredicate(format: "date < %@", date as NSDate))
if count > 0 {
self.log.default("Purged %d SettingsObjects", count)
}
} catch let error {
self.log.error("Unable to purge SettingsObjects: %{public}@", String(describing: error))
purgeError = error
}
}
if let purgeError = purgeError {
completion?(purgeError)
return
}
delegate?.settingsStoreHasUpdatedSettingsData(self)
completion?(nil)
}
private static var encoder: PropertyListEncoder = {
let encoder = PropertyListEncoder()
encoder.outputFormat = .binary
return encoder
}()
private func encodeSettings(_ settings: StoredSettings) -> Data? {
do {
return try Self.encoder.encode(settings)
} catch let error {
self.log.error("Error encoding StoredSettings: %@", String(describing: error))
return nil
}
}
private static var decoder = PropertyListDecoder()
private func decodeSettings(fromData data: Data) -> StoredSettings? {
do {
return try Self.decoder.decode(StoredSettings.self, from: data)
} catch let error {
self.log.error("Error decoding StoredSettings: %@", String(describing: error))
return nil
}
}
}
extension SettingsStore {
public struct QueryAnchor: Equatable, RawRepresentable {
public typealias RawValue = [String: Any]
internal var modificationCounter: Int64
public init() {
self.modificationCounter = 0
}
public init?(rawValue: RawValue) {
guard let modificationCounter = rawValue["modificationCounter"] as? Int64 else {
return nil
}
self.modificationCounter = modificationCounter
}
public var rawValue: RawValue {
var rawValue: RawValue = [:]
rawValue["modificationCounter"] = modificationCounter
return rawValue
}
}
public enum SettingsQueryResult {
case success(QueryAnchor, [StoredSettings])
case failure(Error)
}
public func executeSettingsQuery(fromQueryAnchor queryAnchor: QueryAnchor?, limit: Int, completion: @escaping (SettingsQueryResult) -> Void) {
dataAccessQueue.async {
var queryAnchor = queryAnchor ?? QueryAnchor()
var queryResult = [StoredSettingsData]()
var queryError: Error?
guard limit > 0 else {
completion(.success(queryAnchor, []))
return
}
self.store.managedObjectContext.performAndWait {
let storedRequest: NSFetchRequest<SettingsObject> = SettingsObject.fetchRequest()
storedRequest.predicate = NSPredicate(format: "modificationCounter > %d", queryAnchor.modificationCounter)
storedRequest.sortDescriptors = [NSSortDescriptor(key: "modificationCounter", ascending: true)]
storedRequest.fetchLimit = limit
do {
let stored = try self.store.managedObjectContext.fetch(storedRequest)
if let modificationCounter = stored.max(by: { $0.modificationCounter < $1.modificationCounter })?.modificationCounter {
queryAnchor.modificationCounter = modificationCounter
}
queryResult.append(contentsOf: stored.compactMap { StoredSettingsData(date: $0.date, data: $0.data) })
} catch let error {
queryError = error
return
}
}
if let queryError = queryError {
completion(.failure(queryError))
return
}
// Decoding a large number of settings can be very CPU intensive and may take considerable wall clock time.
// Do not block SettingsStore dataAccessQueue. Perform work and callback in global utility queue.
DispatchQueue.global(qos: .utility).async {
completion(.success(queryAnchor, queryResult.compactMap { self.decodeSettings(fromData: $0.data) }))
}
}
}
}
public struct StoredSettingsData {
public let date: Date
public let data: Data
public init(date: Date, data: Data) {
self.date = date
self.data = data
}
}
public struct StoredSettings: Equatable {
public let date: Date
public var controllerTimeZone: TimeZone
public let dosingEnabled: Bool
public let glucoseTargetRangeSchedule: GlucoseRangeSchedule?
public let preMealTargetRange: ClosedRange<HKQuantity>?
public let workoutTargetRange: ClosedRange<HKQuantity>?
public let overridePresets: [TemporaryScheduleOverridePreset]?
public let scheduleOverride: TemporaryScheduleOverride?
public let preMealOverride: TemporaryScheduleOverride?
public let maximumBasalRatePerHour: Double?
public let maximumBolus: Double?
public let suspendThreshold: GlucoseThreshold?
public let deviceToken: String?
public let insulinType: InsulinType?
public let defaultRapidActingModel: StoredInsulinModel?
public let basalRateSchedule: BasalRateSchedule?
public let insulinSensitivitySchedule: InsulinSensitivitySchedule?
public let carbRatioSchedule: CarbRatioSchedule?
public var notificationSettings: NotificationSettings?
public let controllerDevice: ControllerDevice?
public let cgmDevice: HKDevice?
public let pumpDevice: HKDevice?
// This is the user's display preference glucose unit. TODO: Rename?
public let bloodGlucoseUnit: HKUnit?
public let automaticDosingStrategy: AutomaticDosingStrategy
public let syncIdentifier: UUID
public init(date: Date = Date(),
controllerTimeZone: TimeZone = TimeZone.current,
dosingEnabled: Bool = false,
glucoseTargetRangeSchedule: GlucoseRangeSchedule? = nil,
preMealTargetRange: ClosedRange<HKQuantity>? = nil,
workoutTargetRange: ClosedRange<HKQuantity>? = nil,
overridePresets: [TemporaryScheduleOverridePreset]? = nil,
scheduleOverride: TemporaryScheduleOverride? = nil,
preMealOverride: TemporaryScheduleOverride? = nil,
maximumBasalRatePerHour: Double? = nil,
maximumBolus: Double? = nil,
suspendThreshold: GlucoseThreshold? = nil,
deviceToken: String? = nil,
insulinType: InsulinType? = nil,
defaultRapidActingModel: StoredInsulinModel? = nil,
basalRateSchedule: BasalRateSchedule? = nil,
insulinSensitivitySchedule: InsulinSensitivitySchedule? = nil,
carbRatioSchedule: CarbRatioSchedule? = nil,
notificationSettings: NotificationSettings? = nil,
controllerDevice: ControllerDevice? = nil,
cgmDevice: HKDevice? = nil,
pumpDevice: HKDevice? = nil,
bloodGlucoseUnit: HKUnit? = nil,
automaticDosingStrategy: AutomaticDosingStrategy = .tempBasalOnly,
syncIdentifier: UUID = UUID()) {
self.date = date
self.controllerTimeZone = controllerTimeZone
self.dosingEnabled = dosingEnabled
self.glucoseTargetRangeSchedule = glucoseTargetRangeSchedule
self.preMealTargetRange = preMealTargetRange
self.workoutTargetRange = workoutTargetRange
self.overridePresets = overridePresets
self.scheduleOverride = scheduleOverride
self.preMealOverride = preMealOverride
self.maximumBasalRatePerHour = maximumBasalRatePerHour
self.maximumBolus = maximumBolus
self.suspendThreshold = suspendThreshold
self.deviceToken = deviceToken
self.insulinType = insulinType
self.defaultRapidActingModel = defaultRapidActingModel
self.basalRateSchedule = basalRateSchedule
self.insulinSensitivitySchedule = insulinSensitivitySchedule
self.carbRatioSchedule = carbRatioSchedule
self.notificationSettings = notificationSettings
self.controllerDevice = controllerDevice
self.cgmDevice = cgmDevice
self.pumpDevice = pumpDevice
self.bloodGlucoseUnit = bloodGlucoseUnit
self.automaticDosingStrategy = automaticDosingStrategy
self.syncIdentifier = syncIdentifier
}
}
extension StoredSettings: Codable {
fileprivate static let codingGlucoseUnit = HKUnit.milligramsPerDeciliter
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let bloodGlucoseUnit = HKUnit(from: try container.decode(String.self, forKey: .bloodGlucoseUnit))
self.init(date: try container.decode(Date.self, forKey: .date),
controllerTimeZone: try container.decode(TimeZone.self, forKey: .controllerTimeZone),
dosingEnabled: try container.decode(Bool.self, forKey: .dosingEnabled),
glucoseTargetRangeSchedule: try container.decodeIfPresent(GlucoseRangeSchedule.self, forKey: .glucoseTargetRangeSchedule),
preMealTargetRange: try container.decodeIfPresent(DoubleRange.self, forKey: .preMealTargetRange)?.quantityRange(for: bloodGlucoseUnit),
workoutTargetRange: try container.decodeIfPresent(DoubleRange.self, forKey: .workoutTargetRange)?.quantityRange(for: bloodGlucoseUnit),
overridePresets: try container.decodeIfPresent([TemporaryScheduleOverridePreset].self, forKey: .overridePresets),
scheduleOverride: try container.decodeIfPresent(TemporaryScheduleOverride.self, forKey: .scheduleOverride),
preMealOverride: try container.decodeIfPresent(TemporaryScheduleOverride.self, forKey: .preMealOverride),
maximumBasalRatePerHour: try container.decodeIfPresent(Double.self, forKey: .maximumBasalRatePerHour),
maximumBolus: try container.decodeIfPresent(Double.self, forKey: .maximumBolus),
suspendThreshold: try container.decodeIfPresent(GlucoseThreshold.self, forKey: .suspendThreshold),
deviceToken: try container.decodeIfPresent(String.self, forKey: .deviceToken),
insulinType: try container.decodeIfPresent(InsulinType.self, forKey: .insulinType),
defaultRapidActingModel: try container.decodeIfPresent(StoredInsulinModel.self, forKey: .defaultRapidActingModel),
basalRateSchedule: try container.decodeIfPresent(BasalRateSchedule.self, forKey: .basalRateSchedule),
insulinSensitivitySchedule: try container.decodeIfPresent(InsulinSensitivitySchedule.self, forKey: .insulinSensitivitySchedule),
carbRatioSchedule: try container.decodeIfPresent(CarbRatioSchedule.self, forKey: .carbRatioSchedule),
notificationSettings: try container.decodeIfPresent(NotificationSettings.self, forKey: .notificationSettings),
controllerDevice: try container.decodeIfPresent(ControllerDevice.self, forKey: .controllerDevice),
cgmDevice: try container.decodeIfPresent(CodableDevice.self, forKey: .cgmDevice)?.device,
pumpDevice: try container.decodeIfPresent(CodableDevice.self, forKey: .pumpDevice)?.device,
bloodGlucoseUnit: bloodGlucoseUnit,
automaticDosingStrategy: try container.decodeIfPresent(AutomaticDosingStrategy.self, forKey: .automaticDosingStrategy) ?? .tempBasalOnly,
syncIdentifier: try container.decode(UUID.self, forKey: .syncIdentifier))
}
public func encode(to encoder: Encoder) throws {
let bloodGlucoseUnit = self.bloodGlucoseUnit ?? StoredSettings.codingGlucoseUnit
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(date, forKey: .date)
try container.encode(controllerTimeZone, forKey: .controllerTimeZone)
try container.encode(dosingEnabled, forKey: .dosingEnabled)
try container.encodeIfPresent(glucoseTargetRangeSchedule, forKey: .glucoseTargetRangeSchedule)
try container.encodeIfPresent(preMealTargetRange?.doubleRange(for: bloodGlucoseUnit), forKey: .preMealTargetRange)
try container.encodeIfPresent(workoutTargetRange?.doubleRange(for: bloodGlucoseUnit), forKey: .workoutTargetRange)
try container.encodeIfPresent(overridePresets, forKey: .overridePresets)
try container.encodeIfPresent(scheduleOverride, forKey: .scheduleOverride)
try container.encodeIfPresent(preMealOverride, forKey: .preMealOverride)
try container.encodeIfPresent(maximumBasalRatePerHour, forKey: .maximumBasalRatePerHour)
try container.encodeIfPresent(maximumBolus, forKey: .maximumBolus)
try container.encodeIfPresent(suspendThreshold, forKey: .suspendThreshold)
try container.encodeIfPresent(insulinType, forKey: .insulinType)
try container.encodeIfPresent(deviceToken, forKey: .deviceToken)
try container.encodeIfPresent(defaultRapidActingModel, forKey: .defaultRapidActingModel)
try container.encodeIfPresent(basalRateSchedule, forKey: .basalRateSchedule)
try container.encodeIfPresent(insulinSensitivitySchedule, forKey: .insulinSensitivitySchedule)
try container.encodeIfPresent(carbRatioSchedule, forKey: .carbRatioSchedule)
try container.encodeIfPresent(notificationSettings, forKey: .notificationSettings)
try container.encodeIfPresent(controllerDevice, forKey: .controllerDevice)
try container.encodeIfPresent(cgmDevice.map { CodableDevice($0) }, forKey: .cgmDevice)
try container.encodeIfPresent(pumpDevice.map { CodableDevice($0) }, forKey: .pumpDevice)
try container.encode(bloodGlucoseUnit.unitString, forKey: .bloodGlucoseUnit)
try container.encode(automaticDosingStrategy, forKey: .automaticDosingStrategy)
try container.encode(syncIdentifier, forKey: .syncIdentifier)
}
public struct ControllerDevice: Codable, Equatable {
public let name: String
public let systemName: String
public let systemVersion: String
public let model: String
public let modelIdentifier: String
public init(name: String, systemName: String, systemVersion: String, model: String, modelIdentifier: String) {
self.name = name
self.systemName = systemName
self.systemVersion = systemVersion
self.model = model
self.modelIdentifier = modelIdentifier
}
}
private enum CodingKeys: String, CodingKey {
case date
case controllerTimeZone
case dosingEnabled
case glucoseTargetRangeSchedule
case preMealTargetRange
case workoutTargetRange
case overridePresets
case scheduleOverride
case preMealOverride
case maximumBasalRatePerHour
case maximumBolus
case suspendThreshold
case deviceToken
case insulinType
case defaultRapidActingModel
case basalRateSchedule
case insulinSensitivitySchedule
case carbRatioSchedule
case notificationSettings
case controllerDevice
case cgmDevice
case pumpDevice
case bloodGlucoseUnit
case automaticDosingStrategy
case syncIdentifier
}
}
// MARK: - Critical Event Log Export
extension SettingsStore: CriticalEventLog {
private var exportProgressUnitCountPerObject: Int64 { 11 }
private var exportFetchLimit: Int { Int(criticalEventLogExportProgressUnitCountPerFetch / exportProgressUnitCountPerObject) }
public var exportName: String { "Settings.json" }
public func exportProgressTotalUnitCount(startDate: Date, endDate: Date? = nil) -> Result<Int64, Error> {
var result: Result<Int64, Error>?
self.store.managedObjectContext.performAndWait {
do {
let request: NSFetchRequest<SettingsObject> = SettingsObject.fetchRequest()
request.predicate = self.exportDatePredicate(startDate: startDate, endDate: endDate)
let objectCount = try self.store.managedObjectContext.count(for: request)
result = .success(Int64(objectCount) * exportProgressUnitCountPerObject)
} catch let error {
result = .failure(error)
}
}
return result!
}
public func export(startDate: Date, endDate: Date, to stream: OutputStream, progress: Progress) -> Error? {
let encoder = JSONStreamEncoder(stream: stream)
var modificationCounter: Int64 = 0
var fetching = true
var error: Error?
while fetching && error == nil {
self.store.managedObjectContext.performAndWait {
do {
guard !progress.isCancelled else {
throw CriticalEventLogError.cancelled
}
let request: NSFetchRequest<SettingsObject> = SettingsObject.fetchRequest()
request.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [NSPredicate(format: "modificationCounter > %d", modificationCounter),
self.exportDatePredicate(startDate: startDate, endDate: endDate)])
request.sortDescriptors = [NSSortDescriptor(key: "modificationCounter", ascending: true)]
request.fetchLimit = self.exportFetchLimit
let objects = try self.store.managedObjectContext.fetch(request)
if objects.isEmpty {
fetching = false
return
}
try encoder.encode(objects)
modificationCounter = objects.last!.modificationCounter
progress.completedUnitCount += Int64(objects.count) * exportProgressUnitCountPerObject
} catch let fetchError {
error = fetchError
}
}
}
if let closeError = encoder.close(), error == nil {
error = closeError
}
return error
}
private func exportDatePredicate(startDate: Date, endDate: Date? = nil) -> NSPredicate {
var predicate = NSPredicate(format: "date >= %@", startDate as NSDate)
if let endDate = endDate {
predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [predicate, NSPredicate(format: "date < %@", endDate as NSDate)])
}
return predicate
}
}
// MARK: - Core Data (Bulk) - TEST ONLY
extension SettingsStore {
public func addStoredSettings(settings: [StoredSettings], completion: @escaping (Error?) -> Void) {
guard !settings.isEmpty else {
completion(nil)
return
}
dataAccessQueue.async {
var error: Error?
self.store.managedObjectContext.performAndWait {
for setting in settings {
guard let data = self.encodeSettings(setting) else {
continue
}
let object = SettingsObject(context: self.store.managedObjectContext)
object.data = data
object.date = setting.date
}
error = self.store.save()
}
guard error == nil else {
completion(error)
return
}
self.log.info("Added %d SettingsObjects", settings.count)
self.delegate?.settingsStoreHasUpdatedSettingsData(self)
completion(nil)
}
}
}
|
de25e05aa567b4dacad26e750aef2be6
| 42.658802 | 161 | 0.651646 | false | false | false | false |
r14r-work/fork_swift_intro-playgrounds
|
refs/heads/master
|
ScratchPad.playground/section-1.swift
|
mit
|
2
|
// Playground - noun: a place where people can play
import UIKit
var str: String = "Hello, playground"
// Empty Strings
var emptyString = ""
var anotherEmptyString = String()
emptyString.isEmpty
// Mutability
var catName = "Kaydee"
var greeting = "Hello"
var message = ""
message = greeting
message += " " + catName
// Immutable Strings
let constantMessage = message
// ,constantMessage += " " + catName
struct Point {
var x: Double = 0.0
var y: Double = 0.0
}
class Polyline {
var points = Array<Point>()
}
let origin = Point(x: 0.0, y: 0.0)
let line = Polyline()
class Person {
var name: String = ""
init(var name: String) {
self.name = name
}
}
let pHenryFord = Person(name: "Henry Ford")
let pHenryFonda = Person(name: "Henry Fonda")
let pInventor = pHenryFord
pInventor === pHenryFord
pInventor !== pHenryFord
pInventor === pHenryFonda
pInventor.name = "Albert Einstein"
pInventor === pHenryFord
pInventor !== pHenryFord
var a1 = [1, 2, 3]
var a2 = Int[]([1, 2, 3])
var a3 = Array<Int>([1, 2, 3])
a1 === a2
a1 == a2
a1 === a3
a1 == a3
var b1 = a1
b1
a1 === b1
a1[0] = -1
a1
b1
a1.append(4)
b1.append(4)
a1 === b1
a1 == b1
a1
b1
var c = [1, 2, 3]
let d = c.unshare()
var v = c.unshare()
|
367c99db4d9b86d61cd3d0d6b707d68d
| 11.969072 | 51 | 0.627981 | false | false | false | false |
gdamron/PaulaSynth
|
refs/heads/master
|
PaulaSynth/UserSettings.swift
|
apache-2.0
|
1
|
//
// UserSettings.swift
// AudioEngine2
//
// Created by Grant Damron on 10/4/16.
// Copyright © 2016 Grant Damron. All rights reserved.
//
import UIKit
import Foundation
class UserSettings: NSObject {
static let sharedInstance = UserSettings()
fileprivate enum Keys: String {
case LowNote = "lowNote"
case PolyOn = "polyphonyOn"
case Scale = "scale"
case Sound = "sound"
case TabHidden = "tabHidden"
}
let tabHiddenThresh = 3
var lowNote = 48 {
didSet {
dirty = true
}
}
var polyphonyOn = false {
didSet {
dirty = true
}
}
var scale = Scale.Blues {
didSet {
dirty = true
}
}
var tabHiddenCount = 0 {
didSet {
dirty = true
tabHiddenCount = min(tabHiddenCount, tabHiddenThresh)
}
}
var hideSettingsTab: Bool {
return tabHiddenCount >= tabHiddenThresh
}
var sound = SynthSound.Square
fileprivate var dirty = false
open func save() {
if (dirty) {
let defaults = UserDefaults.standard
defaults.set(lowNote, forKey: Keys.LowNote.rawValue)
defaults.set(polyphonyOn, forKey: Keys.PolyOn.rawValue)
defaults.set(scale.rawValue, forKey: Keys.Scale.rawValue)
defaults.set(sound.name, forKey: Keys.Sound.rawValue)
defaults.set(tabHiddenCount, forKey: Keys.TabHidden.rawValue)
defaults.synchronize()
dirty = false
}
}
open func load() {
let defaults = UserDefaults.standard
if defaults.object(forKey: Keys.LowNote.rawValue) != nil {
lowNote = defaults.integer(forKey: Keys.LowNote.rawValue)
}
// default value of false is acceptable
polyphonyOn = defaults.bool(forKey: Keys.PolyOn.rawValue)
// default vale of 0 is fine
tabHiddenCount = defaults.integer(forKey: Keys.TabHidden.rawValue)
if let val = defaults.string(forKey: Keys.Scale.rawValue),
let s = Scale(rawValue: val) {
scale = s
}
if let soundVal = defaults.string(forKey: Keys.Sound.rawValue) {
sound = SynthSound(key: soundVal)
}
}
}
|
65b0d5826722bdd581c7e0d61a255fbb
| 25.087912 | 74 | 0.564448 | false | false | false | false |
material-components/material-components-ios
|
refs/heads/develop
|
components/Ripple/examples/UICollectionViewWithRippleExample.swift
|
apache-2.0
|
2
|
// Copyright 2020-present the Material Components for iOS authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
import MaterialComponents.MaterialRipple
import MaterialComponents.MaterialContainerScheme
class RippleCell: UICollectionViewCell {
var rippleView: MDCRippleView!
override init(frame: CGRect) {
super.init(frame: frame)
rippleView = MDCRippleView(frame: self.contentView.bounds)
self.contentView.addSubview(rippleView)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class UICollectionViewWithRippleExample: UIViewController,
UICollectionViewDelegate,
UICollectionViewDataSource,
UICollectionViewDelegateFlowLayout,
MDCRippleTouchControllerDelegate
{
let collectionView = UICollectionView(
frame: .zero,
collectionViewLayout: UICollectionViewFlowLayout())
var rippleTouchController: MDCRippleTouchController?
@objc var containerScheme: MDCContainerScheming!
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
containerScheme = MDCContainerScheme()
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = containerScheme.colorScheme.backgroundColor
collectionView.backgroundColor = containerScheme.colorScheme.backgroundColor
collectionView.frame = view.bounds
collectionView.dataSource = self
collectionView.delegate = self
collectionView.backgroundColor = .white
collectionView.alwaysBounceVertical = true
collectionView.register(RippleCell.self, forCellWithReuseIdentifier: "Cell")
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.allowsMultipleSelection = true
view.addSubview(collectionView)
rippleTouchController = MDCRippleTouchController(view: collectionView)
rippleTouchController?.delegate = self
let guide = view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
collectionView.leftAnchor.constraint(equalTo: guide.leftAnchor),
collectionView.rightAnchor.constraint(equalTo: guide.rightAnchor),
collectionView.topAnchor.constraint(equalTo: view.topAnchor),
collectionView.bottomAnchor.constraint(equalTo: guide.bottomAnchor),
])
collectionView.contentInsetAdjustmentBehavior = .always
}
func preiOS11Constraints() {
self.view.addConstraints(
NSLayoutConstraint.constraints(
withVisualFormat: "H:|[view]|",
options: [],
metrics: nil,
views: ["view": collectionView]))
self.view.addConstraints(
NSLayoutConstraint.constraints(
withVisualFormat: "V:|[view]|",
options: [],
metrics: nil,
views: ["view": collectionView]))
}
func collectionView(
_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath
) -> UICollectionViewCell {
guard
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)
as? RippleCell
else { fatalError() }
cell.layer.borderWidth = 1
cell.layer.borderColor = UIColor.lightGray.cgColor
cell.backgroundColor = containerScheme.colorScheme.surfaceColor
return cell
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(
_ collectionView: UICollectionView,
numberOfItemsInSection section: Int
) -> Int {
return 30
}
func collectionView(
_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath
) -> CGSize {
let size = collectionView.bounds.size.width - 12
return CGSize(width: size, height: 60)
}
func collectionView(
_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
insetForSectionAt section: Int
) -> UIEdgeInsets {
return UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
}
func collectionView(
_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
minimumLineSpacingForSectionAt section: Int
) -> CGFloat {
return 8
}
func collectionView(
_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
minimumInteritemSpacingForSectionAt section: Int
) -> CGFloat {
return 8
}
func rippleTouchController(
_ rippleTouchController: MDCRippleTouchController,
rippleViewAtTouchLocation location: CGPoint
) -> MDCRippleView? {
guard let indexPath = self.collectionView.indexPathForItem(at: location) else {
return nil
}
let cell = self.collectionView.cellForItem(at: indexPath) as? RippleCell
if let cell = cell {
return cell.rippleView
}
return nil
}
}
extension UICollectionViewWithRippleExample {
@objc class func catalogMetadata() -> [String: Any] {
return [
"breadcrumbs": ["Ripple", "UICollectionView with Ripple"],
"primaryDemo": false,
"presentable": false,
]
}
}
|
81656823eb152b9e803d61f67bda140d
| 29.935135 | 96 | 0.73755 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.