repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
connienguyen/volunteers-iOS
|
VOLA/VOLA/Helpers/Util/Logger.swift
|
1
|
1623
|
import Foundation
/// Logging Wrapper.
class Logger {
/// Logs Info messages
static func info(_ message: CustomStringConvertible, function: String = #function, path: String = #file, line: Int = #line) {
Logger.write("INFO", msg: message, function: function, path: path, line: line)
}
/// Logs Warning messages
static func warn(_ message: CustomStringConvertible, function: String = #function, path: String = #file, line: Int = #line) {
Logger.write("WARN", msg: message, function: function, path: path, line: line)
}
/// Logs Error messages
static func error(_ message: CustomStringConvertible, function: String = #function, path: String = #file, line: Int = #line) {
Logger.write("ERROR", msg: message, function: function, path: path, line: line)
}
/// Logs Error messages using an error's localizedDescription
static func error(_ localizableError: Error, function: String = #function, path: String = #file, line: Int = #line) {
Logger.write("ERROR", msg: localizableError.localizedDescription, function: function, path: path, line: line)
}
static private func write(_ prefix: String, msg: CustomStringConvertible, function: String = #function, path: String = #file, line: Int = #line) {
#if DEBUG
var file = NSURL(fileURLWithPath: path).lastPathComponent!.description
file = file.substring(to: file.characters.index(of: ".")!)
let location = [file, function, line.description].joined(separator: "::")
print("[\(prefix.uppercased())] - \(location) \t\(msg)")
#endif
}
}
|
gpl-2.0
|
7cbeaadb2bb702014729d212bcfc3fa5
| 44.083333 | 150 | 0.65496 | 4.271053 | false | false | false | false |
ryanherman/intro
|
intro/AskViewController.swift
|
1
|
5021
|
//
// RightViewController.swift
// SlideMenuControllerSwift
//
// Created by Yuji Hato on 12/3/14.
//
import UIKit
import Firebase
import MobileCoreServices
import MediaPlayer
class AskViewController : UIViewController {
let ref = Firebase(url: "https://flickering-torch-4367.firebaseio.com/ask")
var base64String:NSString!
var moviePlayer : MPMoviePlayerController?
@IBOutlet weak var imageReview: UIImageView!
@IBOutlet weak var question: UITextField!
@IBOutlet weak var recordImage: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.setNavigationBarItem()
ref.observeEventType(.Value, withBlock: {
snapshot in
print("\(snapshot.key) -> \(snapshot.value)")
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func AskQuestion(sender: AnyObject) {
startCameraFromViewController(self, withDelegate: self)
/*
let questionAsked : String = question.text!
let theQuestion = ["user":"ryan","question":questionAsked]
let postRef = ref.childByAppendingPath("questions")
let post1Ref = postRef.childByAutoId()
post1Ref.setValue(theQuestion)
*/
}
@IBAction func dismissResponder(sender: AnyObject) {
self.view.endEditing(true)
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
self.view.endEditing(true)
return false
}
func video(videoPath: NSString, didFinishSavingWithError error: NSError?, contextInfo info: AnyObject) {
var title = "Success"
var message = "Video was saved"
if let saveError = error {
title = "Error"
message = "Video failed to save"
}
let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Cancel, handler: nil))
presentViewController(alert, animated: true, completion: nil)
}
}
extension AskViewController : UIImagePickerControllerDelegate
{
func startCameraFromViewController(viewController: UIViewController, withDelegate delegate: protocol<UIImagePickerControllerDelegate, UINavigationControllerDelegate>) -> Bool
{
if UIImagePickerController.isSourceTypeAvailable(.Camera) == false {
return false
}
let cameraController = UIImagePickerController()
cameraController.sourceType = .Camera
cameraController.mediaTypes = [kUTTypeMovie as String]
cameraController.allowsEditing = false
cameraController.delegate = delegate
presentViewController(cameraController, animated: true, completion: nil)
return true
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo info: [String : AnyObject]?) {
dismissViewControllerAnimated(true, completion: nil)
imageReview.image = image
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
let mediaType = info[UIImagePickerControllerMediaType] as! NSString
dismissViewControllerAnimated(true, completion: nil)
// Handle a movie capture
if mediaType == kUTTypeMovie {
let path = (info[UIImagePickerControllerMediaURL] as! NSURL).path
if UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(path!) {
UISaveVideoAtPathToSavedPhotosAlbum(path!, self, "video:didFinishSavingWithError:contextInfo:", nil)
var x: NSData? = NSData(contentsOfFile: path!)
base64String = x?.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
let postRef = ref.childByAppendingPath("questions")
let post1 = ["username": "bitz", "data": base64String]
let post1Ref = postRef.childByAutoId()
post1Ref.setValue(post1)
playVideo(path!)
}
}
}
func playVideo(fullPath: String) {
print(fullPath)
let url = NSURL.fileURLWithPath(fullPath)
moviePlayer = MPMoviePlayerController(contentURL: url)
if let player = moviePlayer {
player.view.frame = self.view.bounds
player.prepareToPlay()
player.scalingMode = .AspectFill
self.view.addSubview(player.view)
}
}
}
extension AskViewController: UINavigationControllerDelegate{
}
|
mit
|
ac7d7a7e31d9f7c013bdea9787c77a20
| 35.919118 | 182 | 0.62856 | 5.771264 | false | false | false | false |
safx/TypetalkKit
|
Example-OSX/Example-OSX/MessageViewController.swift
|
1
|
2032
|
//
// MessageViewController.swift
// TypetalkSample-OSX
//
// Created by Safx Developer on 2015/01/29.
// Copyright (c) 2015年 Safx Developers. All rights reserved.
//
import AppKit
import Cocoa
import TypetalkKit
class MessageViewController: NSViewController, NSTableViewDelegate, NSTableViewDataSource {
@IBOutlet weak var tableView: NSTableView!
fileprivate var messages: GetMessagesResponse? = nil
var detailItem: TopicWithUserInfo? = nil {
didSet {
getMessages()
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = detailItem?.topic.name
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
func getMessages() {
if let topic = detailItem {
let topicid = topic.topic.id
TypetalkAPI.send(GetMessages(topicId: topicid)) { result -> Void in
switch result {
case .success(let ms):
self.messages = ms
self.tableView.reloadData()
case .failure(let error):
print(error)
}
}
}
}
// MARK: - Table View
func numberOfRows(in tableView: NSTableView) -> Int {
return messages == nil ? 0 : messages!.posts.count
}
func tableView(_ tableView: NSTableView, viewFor viewForTableColumn: NSTableColumn?, row: Int) -> NSView? {
let cell = tableView.make(withIdentifier: "MessageCell", owner: nil) as! MessageCell
cell.model = messages!.posts[row]
return cell
}
func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
let font = NSFont(name: "Helvetica", size: 13)!
let attr: [String:AnyObject] = [NSFontAttributeName: font]
let mes = messages!.posts[row].message
let size = (mes as NSString).size(withAttributes: attr)
return max(size.height + 32, 56)
}
}
|
mit
|
b5765609854c9a51d2039a8561a0d758
| 28 | 111 | 0.595567 | 4.754098 | false | false | false | false |
pavelosipov/POSSchedulableObject
|
Examples/ConceptApp/ConceptApp/main.swift
|
1
|
3494
|
//
// main.swift
// SchedulableObjectConceptApp
//
// Created by Pavel Osipov on 26.10.16.
// Copyright © 2016 Pavel Osipov. All rights reserved.
//
import Foundation
import Dispatch
typealias Event = () -> Void
class EventQueue {
private let semaphore = DispatchSemaphore(value: 1)
private var events = [Event]()
func pushEvent(event: @escaping Event) {
semaphore.wait()
events.append(event)
semaphore.signal()
}
func resetEvents() -> [Event] {
semaphore.wait()
let currentEvents = events
events = [Event]()
semaphore.signal()
return currentEvents
}
}
class RunLoop {
let eventQueue = EventQueue()
var disposed = false
@objc func run() {
while !disposed {
for event in eventQueue.resetEvents() {
event()
}
Thread.sleep(forTimeInterval: 0.1)
}
}
}
class Scheduler {
private let runLoop = RunLoop()
private let thread: Thread
init() {
self.thread = Thread(
target: runLoop,
selector: #selector(RunLoop.run),
object: nil)
thread.start()
}
func schedule(event: @escaping Event) {
runLoop.eventQueue.pushEvent(event: event)
}
func dispose() {
runLoop.disposed = true
}
}
class SchedulableObject<T> {
let object: T
private let scheduler: Scheduler
init(object: T, scheduler: Scheduler) {
self.object = object
self.scheduler = scheduler
}
func schedule(event: @escaping (T) -> Void) {
scheduler.schedule {
event(self.object)
}
}
}
class PrintOptionsProvider {
var richFormatEnabled = false;
}
class Printer {
private let optionsProvider: PrintOptionsProvider
init(optionsProvider: PrintOptionsProvider) {
self.optionsProvider = optionsProvider
}
func doWork(what: String) {
if optionsProvider.richFormatEnabled {
print("\(Thread.current): out \(what)")
} else {
print("out \(what)")
}
}
}
class Assembly {
let backgroundScheduler = Scheduler()
let printOptionsProvider: SchedulableObject<PrintOptionsProvider>
let printer: SchedulableObject<Printer>
init() {
let optionsProvider = PrintOptionsProvider()
self.printOptionsProvider = SchedulableObject<PrintOptionsProvider>(
object: optionsProvider,
scheduler: backgroundScheduler);
self.printer = SchedulableObject<Printer>(
object: Printer(optionsProvider: optionsProvider),
scheduler: backgroundScheduler)
}
}
let assembly = Assembly()
while true {
guard let value = readLine(strippingNewline: true) else {
continue
}
if (value == "q") {
assembly.backgroundScheduler.dispose()
break;
}
assembly.printOptionsProvider.schedule(
event: { (printOptionsProvider: PrintOptionsProvider) in
printOptionsProvider.richFormatEnabled = arc4random() % 2 == 0;
})
assembly.printer.schedule(event: { (printer: Printer) in
printer.doWork(what: value)
})
// Simplified version
//
// assembly.backgroundScheduler.schedule {
// assembly.printOptionsProvider.object.richFormatEnabled = arc4random() % 2 == 0
// assembly.printer.object.doWork(what: value)
// }
}
|
mit
|
50f7b30b813b8e655c4cfdec5fe57b55
| 22.761905 | 89 | 0.606642 | 4.501289 | false | false | false | false |
derekli66/Learning-Core-Audio-Swift-SampleCode
|
CH04_Recorder-Swift/CH04_Recorder-Swift/main.swift
|
1
|
11928
|
//
// main.swift
// CH04_Recorder-Swift
//
// Created by LEE CHIEN-MING on 23/07/2017.
// Copyright © 2017 derekli66. All rights reserved.
//
import Foundation
import AudioToolbox
private let kNumberRecordBuffers = 3
class MyRecorder
{
var recordFile: AudioFileID?
var recordPacket: Int64 = 0
var running: Bool = false
}
extension Int {
func toUInt32() -> UInt32 {
return UInt32(self)
}
func toFloat64() -> Float64 {
return Float64(self)
}
func toDouble() -> Double {
return Double(self)
}
}
extension UInt32 {
func toInt64() -> Int64 {
return Int64(self)
}
func toInt() -> Int {
return Int(self)
}
}
extension Float {
func toFloat64() -> Float64 {
return Float64(self)
}
}
extension Double {
func toInt() -> Int {
return Int(self)
}
func toUInt32() -> UInt32 {
return UInt32(self)
}
}
postfix operator ~>
extension UnsafePointer where Pointee == AudioStreamBasicDescription {
static postfix func ~> (pointer: UnsafePointer<AudioStreamBasicDescription>) -> AudioStreamBasicDescription {
return pointer.pointee
}
}
extension UnsafeMutablePointer where Pointee == MyRecorder {
static postfix func ~> (pointer: UnsafeMutablePointer<MyRecorder>) -> MyRecorder {
return pointer.pointee
}
}
extension UnsafeMutablePointer where Pointee == AudioQueueBuffer {
static postfix func ~> (pointer: UnsafeMutablePointer<AudioQueueBuffer>) -> AudioQueueBuffer {
return pointer.pointee
}
}
// MARK: - Utility Functions
func MyGetDefaultInputDevicesSampleRate(_ outSampleRate: UnsafeMutablePointer<Float64>) -> OSStatus
{
var error: OSStatus = noErr
var deviceID: AudioDeviceID = 0
// get the default input device
var propertyAddress = AudioObjectPropertyAddress(mSelector: kAudioHardwarePropertyDefaultInputDevice,
mScope: kAudioObjectPropertyScopeGlobal,
mElement: 0)
var propertySize: UInt32 = MemoryLayout<AudioDeviceID>.size.toUInt32()
// Refer to: https://developer.apple.com/library/archive/technotes/tn2223/_index.html
// Refer to: https://stackoverflow.com/questions/37132958/audiohardwareservicegetpropertydata-deprecated
error = AudioObjectGetPropertyData(AudioObjectID(kAudioObjectSystemObject),
&propertyAddress,
0,
nil,
&propertySize,
&deviceID)
if (error != noErr) { return error }
// get its sample rate
propertyAddress.mSelector = kAudioDevicePropertyNominalSampleRate
propertyAddress.mScope = kAudioObjectPropertyScopeGlobal
propertyAddress.mElement = 0
propertySize = MemoryLayout<Float64>.size.toUInt32()
error = AudioObjectGetPropertyData(deviceID,
&propertyAddress,
0,
nil,
&propertySize,
outSampleRate)
return error
}
func MyComputeRecordBufferSize(_ format: UnsafePointer<AudioStreamBasicDescription>, _ queue: AudioQueueRef, _ seconds: Float) -> UInt32
{
var packets: UInt32 = 0
var frames: UInt32 = 0
var bytes: UInt32 = 0
frames = ceil(seconds.toFloat64() * format~>.mSampleRate).toUInt32()
if (format~>.mBytesPerFrame > 0 ) { // 1
bytes = frames * format~>.mBytesPerFrame
}
else {
var maxPacketSize: UInt32 = 0
if (format~>.mBytesPerPacket > 0) { // 2
maxPacketSize = format.pointee.mBytesPerPacket
}
else {
// get the largest single packet size possible
var propertySize: UInt32 = MemoryLayout.size(ofValue: maxPacketSize).toUInt32()
CheckError(AudioQueueGetProperty(queue,
kAudioConverterPropertyMaximumOutputPacketSize,
&maxPacketSize,
&propertySize), "couldn't get queue's maximum output packet size")
}
if (format~>.mFramesPerPacket > 0) {
packets = frames / format~>.mFramesPerPacket
}
else {
// worst-case scenario: 1 frame in a packet. WHY?
packets = frames
}
if (0 == packets) { // sanitfy check
packets = 1;
}
bytes = packets * maxPacketSize
}
return bytes;
}
// Copy a queue's encoder's magic cookie to an audio file
func MyCopyEncoderCookieToFile(_ queue: AudioQueueRef, _ theFile: AudioFileID) -> Void
{
var propertySize: UInt32 = 0
// get the magic cookie, if any, from the queue's converter
let result: OSStatus = AudioQueueGetPropertySize(queue,
kAudioConverterCompressionMagicCookie,
&propertySize)
if (noErr == result && propertySize > 0) {
// there is valid cookie data to be fetched, get it.
let magicCookie = UnsafeMutablePointer<UInt8>.allocate(capacity: propertySize.toInt())
magicCookie.initialize(repeating: 0, count: propertySize.toInt())
CheckError(AudioQueueGetProperty(queue,
kAudioQueueProperty_MagicCookie,
magicCookie,
&propertySize), "get audio queue's magic cookie")
// now set the magic cookie on the output file
CheckError(AudioFileSetProperty(theFile,
kAudioFilePropertyMagicCookieData,
propertySize,
magicCookie), "set audio file's magic cookie")
magicCookie.deinitialize(count: propertySize.toInt())
magicCookie.deallocate()
}
}
// MARK: - Audio Queue
// Audio Queue callback function, called when an input buffer has been filled
let MyAQInputCallback: AudioQueueInputCallback = {
(inUserData: UnsafeMutableRawPointer?,
inAQ: AudioQueueRef,
inBuffer: AudioQueueBufferRef,
inStartTime: UnsafePointer<AudioTimeStamp>,
inNumberPacketDescriptions: UInt32,
inPacketDescs: UnsafePointer<AudioStreamPacketDescription>?) in
var recorderRef = inUserData?.bindMemory(to: MyRecorder.self, capacity: 1)
guard let recorder = recorderRef else { return }
var inNumPackets = inNumberPacketDescriptions
if (inNumPackets > 0) {
// write packets to file
CheckError(AudioFileWritePackets(recorder~>.recordFile!,
false,
inBuffer~>.mAudioDataByteSize,
inPacketDescs,
recorder~>.recordPacket,
&inNumPackets,
inBuffer~>.mAudioData), "AudioFileWritePackets failed")
// increment packet index
recorder~>.recordPacket += inNumPackets.toInt64()
}
// if we're not stopping, re-enqueue the buffer so that it gets filled again
if (recorder~>.running) {
CheckError(AudioQueueEnqueueBuffer(inAQ,
inBuffer,
0,
nil), "AudioQueueEnqueueBuffer failed")
}
}
func main() -> Void
{
var recorder = MyRecorder()
var recordFormat = AudioStreamBasicDescription()
// Configure the output data format to be AAC
recordFormat.mFormatID = kAudioFormatMPEG4AAC
recordFormat.mChannelsPerFrame = 2
// get the sample rate of the default input device
// we use this to adapt the output data format to match hardware capabilities
_ = MyGetDefaultInputDevicesSampleRate(&recordFormat.mSampleRate)
// ProTip: Use the AudioFormat API to trivialize ASBD creation.
// input: at least the mFormatID, however, at this point we already have
// mSampleRate, mFormatID, and mChannelsPerFrame
// output: the remainder of the ASBD will be filled out as much as possible
// given the information known about the format
var propSize = MemoryLayout.size(ofValue: recordFormat).toUInt32()
CheckError(AudioFormatGetProperty(kAudioFormatProperty_FormatInfo,
0,
nil,
&propSize,
&recordFormat), "AudioFormatGetProperty failed")
// create a input (recording) queue
var queue_: AudioQueueRef?
CheckError(AudioQueueNewInput(&recordFormat,
MyAQInputCallback,
&recorder,
nil,
nil,
0,
&queue_), "AudioQueueNewInput failed")
guard let queue = queue_ else { exit(1) }
// since the queue is now initilized, we ask it's Audio Converter object
// for the ASBD it has configured itself with. The file may require a more
// specific stream description than was necessary to create the audio queue.
//
// for example: certain fields in an ASBD cannot possibly be known until it's
// codec is instantiated (in this case, by the AudioQueue's Audio Converter object)
var size = MemoryLayout.size(ofValue: recordFormat).toUInt32()
CheckError(AudioQueueGetProperty(queue,
kAudioConverterCurrentOutputStreamDescription,
&recordFormat,
&size), "couldn't get queue's format")
let myFileURL = URL(fileURLWithPath: "output.caf")
CheckError(AudioFileCreateWithURL(myFileURL as CFURL,
kAudioFileCAFType,
&recordFormat,
AudioFileFlags.eraseFile,
&recorder.recordFile), "AudioFileCreateWithURL failed")
// many encoded formats require a 'magic cookie'. we set the cookie first
// to give the file object as much info as we can about the data it will be receiving
MyCopyEncoderCookieToFile(queue, recorder.recordFile!)
// allocate and enqueue buffers
let bufferBytesSize = MyComputeRecordBufferSize(&recordFormat, queue, 0.5)
for _ in 0..<kNumberRecordBuffers {
var buffer: AudioQueueBufferRef?
CheckError(AudioQueueAllocateBuffer(queue,
bufferBytesSize,
&buffer), "AudioQueueAllocateBuffer failed")
CheckError(AudioQueueEnqueueBuffer(queue,
buffer!,
0,
nil), "AudioQueueEnqueueBuffer failed")
}
// start the queue. this function return immedatly and begins
// invoking the callback, as needed, asynchronously.
recorder.running = true;
CheckError(AudioQueueStart(queue, nil), "AudioQueueStart failed")
// and wait
debugPrint("Recording, press <return> to stop: ")
getchar();
// end recording
debugPrint("* recording done *")
recorder.running = false
CheckError(AudioQueueStop(queue, true), "AudioQueueStop failed")
// a codec may update its magic cookie at the end of an encoding session
// so reapply it to the file now
MyCopyEncoderCookieToFile(queue, recorder.recordFile!)
AudioQueueDispose(queue, true)
AudioFileClose(recorder.recordFile!)
}
main()
|
mit
|
2aa0c62e54a4e25dc08d1737fc6c02dc
| 35.811728 | 136 | 0.58682 | 5.261138 | false | false | false | false |
openHPI/xikolo-ios
|
Common/Data/Helper/LastVisitHelper.swift
|
1
|
1714
|
//
// Created for xikolo-ios under GPL-3.0 license.
// Copyright © HPI. All rights reserved.
//
import BrightFutures
import CoreData
import Foundation
import Stockpile
public enum LastVisitHelper {
public static func syncLastVisit(forCourse course: Course) -> Future<SyncSingleResult, XikoloError> {
let fetchRequest = Self.FetchRequest.lastVisit(forCourse: course)
let query = SingleResourceQuery(type: LastVisit.self, id: course.id)
return XikoloSyncEngine().synchronize(withFetchRequest: fetchRequest, withQuery: query)
}
@discardableResult
public static func recordVisit( for item: CourseItem) -> Future<Void, XikoloError> {
let promise = Promise<Void, XikoloError>()
CoreDataHelper.persistentContainer.performBackgroundTask { context in
context.mergePolicy = NSMergePolicy.mergeByPropertyObjectTrump
guard let item = context.existingTypedObject(with: item.objectID) as? CourseItem else {
promise.failure(.missingResource(ofType: CourseItem.self))
return
}
guard let course = item.section?.course else {
promise.failure(.missingResource(ofType: Course.self))
return
}
let fetchRequest = Self.FetchRequest.lastVisit(forCourse: course)
guard let lastVisit = context.fetchSingle(fetchRequest).value else {
promise.failure(.missingResource(ofType: LastVisit.self))
return
}
lastVisit.visitDate = Date()
lastVisit.item = item
promise.complete(context.saveWithResult())
}
return promise.future
}
}
|
gpl-3.0
|
89b87232f8eff941bfbddba0e727aba5
| 33.26 | 105 | 0.656743 | 4.965217 | false | false | false | false |
Chaosspeeder/YourGoals
|
YourGoals/UI/Controller/PlanningViewController.swift
|
1
|
3561
|
//
// PlanningViewController.swift
// YourGoals
//
// Created by André Claaßen on 07.04.18.
// Copyright © 2018 André Claaßen. All rights reserved.
//
import UIKit
/// view controller for planning a week or more
class PlanningViewController: UIViewController, ActionableTableViewDelegate, EditActionableViewControllerDelegate {
@IBOutlet weak var actionableTableView: ActionableTableView!
/// the storage manager needed for various core data operaitons
var manager = GoalsStorageManager.defaultStorageManager
var editActionable:Actionable?
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.prefersLargeTitles = true
self.actionableTableView.configure(manager: self.manager, dataSource: PlannableTasksDataSource(manager: self.manager), delegate: self)
}
override func viewWillAppear(_ animated: Bool) {
self.navigationController?.isNavigationBarHidden = false
self.navigationController?.navigationBar.topItem?.title = "Planning"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func reloadAll() {
self.actionableTableView.reload()
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// let destinationViewController = segue.destination
guard let identifier = segue.identifier else {
fatalError("couldn't process segue with no identifier")
}
switch identifier {
case "presentEditActionable":
var parameter = (segue.destination as! UINavigationController).topViewController! as! EditActionableViewControllerParameter
parameter.goal = self.editActionable?.goal
parameter.delegate = self
parameter.editActionable = self.editActionable
parameter.editActionableType = .task
parameter.manager = self.manager
parameter.commitParameter()
self.editActionable = nil
default:
fatalError("couldn't process segue: \(String(describing: segue.identifier))")
}
}
// MARK: - ActionableTableViewDelegate
func requestForEdit(actionable: Actionable) {
self.editActionable = actionable
performSegue(withIdentifier: "presentEditActionable", sender: self)
}
func progressChanged(actionable: Actionable) {
self.reloadAll()
}
func goalChanged(goal: Goal) {
self.reloadAll()
}
func goalChanged() {
self.reloadAll()
}
func commitmentChanged() {
self.reloadAll()
}
// MARK: EditActionableViewControllerDelegate
func createNewActionable(actionableInfo: ActionableInfo) throws {
}
func updateActionable(actionable: Actionable, updateInfo: ActionableInfo) throws {
let goalComposer = GoalComposer(manager: self.manager)
let _ = try goalComposer.update(actionable: actionable, withInfo: updateInfo, forDate: Date())
self.reloadAll()
}
func deleteActionable(actionable: Actionable) throws {
let goalComposer = GoalComposer(manager: self.manager)
let _ = try goalComposer.delete(actionable: actionable)
self.reloadAll()
}
}
|
lgpl-3.0
|
3b7826e88fd3378542cd8ab20724a27a
| 31.925926 | 142 | 0.670416 | 5.470769 | false | false | false | false |
yanqingsmile/ChemicalCalculator
|
ChemicalCalculator/UIExtensions.swift
|
1
|
1372
|
//
// UIExtensions.swift
// ChemicalCalculator
//
// Created by Vivian Liu on 4/20/17.
// Copyright © 2017 Vivian Liu. All rights reserved.
//
import Foundation
import UIKit
extension UIColor {
//let mintBlue = UIColor(red: 145/255.0, green: 186/255.0, blue: 185/255.0, alpha: 1.0)
static func mintBlue() -> UIColor {
return UIColor(red: 145/255.0, green: 186/255.0, blue: 185/255.0, alpha: 1.0)
}
static func warmOrange() -> UIColor {
return UIColor(red: 238/255.0, green: 180/255.0, blue: 122/255.0, alpha: 1.0)
}
static func grayWhite() -> UIColor {
return UIColor(red: 251/255.0, green: 248/255.0, blue: 243/255.0, alpha: 1.0)
}
}
extension UIViewController {
func addDoneButtonOnKeyboard(toTextField textField: UITextField) {
let doneToolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: 320, height: 50))
doneToolBar.barStyle = .default
let done = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(dismissKeyboard))
var items = [UIBarButtonItem]()
items.append(done)
doneToolBar.items = items
doneToolBar.sizeToFit()
textField.inputAccessoryView = doneToolBar
}
@objc fileprivate func dismissKeyboard() {
view.endEditing(true)
}
}
|
mit
|
edea070a3ee3c3a2371a190d4a63814b
| 27.5625 | 113 | 0.618527 | 3.685484 | false | false | false | false |
jaredsinclair/JTSBGTask
|
JTSBGTask.swift
|
1
|
2016
|
//
// JTSBGTask.swift
// JTSBGTask
//
// Created by Jared Sinclair on 8/15/15.
// Copyright © 2015 Nice Boy LLC. All rights reserved.
//
import UIKit
/**
//-----------------------------------------------------------------------------
static func start() -> BackgroundTask?
Convenience for initializing a task with a default expiration handler;
@return Returns nil if background task time was denied.
//-----------------------------------------------------------------------------
func startWithExpirationHandler(handler: (() -> Void)?) -> Bool
Begins a background task.
@param handler The expiration handler. Optional. Will be called on whatever
thread UIKit pops the expiration handler for the task. The handler should
perform cleanup in a synchronous manner, since it is called when background
time is being brought to a halt.
@return Returns YES if a valid task id was created.
//-----------------------------------------------------------------------------
end()
Ends the background task for `taskId`, if the id is valid.
*/
public class BackgroundTask {
// MARK: Public
public static func start() -> BackgroundTask? {
let task = BackgroundTask();
let successful = task.startWithExpirationHandler(nil)
return (successful) ? task : nil
}
public func startWithExpirationHandler(handler: (() -> Void)?) -> Bool {
self.taskId = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler {
if let safeHandler = handler { safeHandler() }
self.end()
}
return (self.taskId != UIBackgroundTaskInvalid);
}
public func end() {
if (self.taskId != UIBackgroundTaskInvalid) {
let taskId = self.taskId
self.taskId = UIBackgroundTaskInvalid
UIApplication.sharedApplication().endBackgroundTask(taskId)
}
}
// MARK: Private
private var taskId: UIBackgroundTaskIdentifier = UIBackgroundTaskInvalid
}
|
mit
|
679aba0fdd3157ada81649095f840d41
| 27.380282 | 98 | 0.59603 | 5.206718 | false | false | false | false |
syoung-smallwisdom/BrickBot
|
BrickBot/BrickBot/CalibrationDial.swift
|
1
|
4796
|
//
// CalibrationDial.swift
//
// Created by Shannon Young on 9/30/15.
// Copyright © 2015 Smallwisdom. All rights reserved.
//
import UIKit
@IBDesignable
class CalibrationDial: SWPanControl {
@IBOutlet weak var valueLabel: UILabel?
@IBInspectable var dialPosition: CGFloat {
get {
return position.x;
}
set (dialPosition) {
position.x = round(dialPosition*100)/100;
updateLayerProperties()
}
}
override var position: CGPoint {
didSet {
updateLayerProperties()
}
}
override func updatePosition(dx dx: CGFloat, dy: CGFloat) {
let ddx = (dialPosition >= 0) ? dx - dy : dx + dy
super.updatePosition(dx: round(ddx*100)/100, dy: 0)
}
// MARK: Draw the dial
let lineWidth: CGFloat = 24
private var leftLayer: CAShapeLayer!
private var rightLayer: CAShapeLayer!
private var dotLayer: CAShapeLayer!
override func layoutSubviews() {
super.layoutSubviews()
self.thumb = bounds.width / 2
self.threshold = bounds.width / 200
if (leftLayer == nil) {
leftLayer = CAShapeLayer()
layer.addSublayer(leftLayer)
}
leftLayer.frame = layer.bounds
if (rightLayer == nil) {
rightLayer = CAShapeLayer()
layer.addSublayer(rightLayer)
}
rightLayer.frame = layer.bounds
if (dotLayer == nil) {
dotLayer = CAShapeLayer()
layer.addSublayer(dotLayer)
}
dotLayer.frame = layer.bounds
updateLayerProperties()
}
private func updateLayerProperties() {
valueLabel?.text = String(Int(round(dialPosition * BBMotorCalibrationMaxOffset + BBMotorCalibrationCenter)))
if leftLayer != nil {
leftLayer.path = calculateLeftPath().CGPath
leftLayer.fillColor = UIColor.redColor().CGColor
}
if rightLayer != nil {
rightLayer.path = calculateRightPath().CGPath
rightLayer.fillColor = UIColor.greenColor().CGColor
}
if dotLayer != nil {
dotLayer.path = calculateDotPath().CGPath
dotLayer.fillColor = UIColor.whiteColor().CGColor
dotLayer.shadowColor = UIColor.blackColor().CGColor
dotLayer.shadowPath = dotLayer.path
dotLayer.shadowOffset = CGSizeMake(0, 0)
dotLayer.shadowRadius = 2
dotLayer.shadowOpacity = 0.8
}
}
private func calculateLeftPath() -> UIBezierPath {
return createArcPath(from: -1, to: dialPosition)
}
private func calculateRightPath() -> UIBezierPath {
return createArcPath(from: dialPosition, to: 1)
}
private func calculateDotPath() -> UIBezierPath {
return createArcPath(from: dialPosition, to: dialPosition)
}
private func createArcPath(from from: CGFloat, to: CGFloat) -> UIBezierPath {
let size = bounds.insetBy(dx: lineWidth / 1.5, dy: lineWidth / 1.5)
let outerRadius = (size.height * size.height + size.width * size.width / 4) / (2 * size.height)
let innerRadius = outerRadius - lineWidth
let theta = size.width/2 > size.height ? asin(size.width / (2 * outerRadius)) : CGFloat(M_PI)/2 + asin((size.height - size.width / 2) / outerRadius)
let arcCenter = CGPointMake(bounds.width / 2.0, outerRadius + 3)
let startAngle = -1 * CGFloat(M_PI_2) + from * theta
let endAngle = -1 * CGFloat(M_PI_2) + to * theta
let capRadius = innerRadius + lineWidth / 2
let leftEndCapAngle = startAngle + CGFloat(M_PI)
let leftEndCapCenter = CGPointMake(arcCenter.x - capRadius * sin(-1*from*theta), arcCenter.y - capRadius * cos(from*theta))
let rightEndCapAngle = endAngle + CGFloat(M_PI)
let rightEndCapCenter = CGPointMake(arcCenter.x - capRadius * sin(-1*to*theta), arcCenter.y - capRadius * cos(to*theta))
let shapePath = UIBezierPath()
shapePath.addArcWithCenter(leftEndCapCenter, radius: lineWidth / 2, startAngle: leftEndCapAngle, endAngle: leftEndCapAngle + CGFloat(M_PI), clockwise: true)
shapePath.addArcWithCenter(arcCenter, radius: outerRadius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
shapePath.addArcWithCenter(rightEndCapCenter, radius: lineWidth / 2, startAngle: rightEndCapAngle + CGFloat(M_PI), endAngle: rightEndCapAngle, clockwise: true)
shapePath.addArcWithCenter(arcCenter, radius: innerRadius, startAngle: endAngle, endAngle: startAngle, clockwise: false)
shapePath.closePath()
return shapePath
}
}
|
mit
|
4450b19226423aa8baf493b3fffa3d0c
| 35.610687 | 167 | 0.620021 | 4.4897 | false | false | false | false |
24/ios-o2o-c
|
gxc/OpenSource/SweetAlert/SweetAlert.swift
|
2
|
24978
|
//
// SweetAlert.swift
// SweetAlert
//
// Created by Codester on 11/3/14.
// Copyright (c) 2014 Codester. All rights reserved.
//
import Foundation
import UIKit
import QuartzCore
enum AlertStyle {
case Success,Error,Warning,None
case CustomImag(imageFile:String)
}
class SweetAlert: UIViewController {
let kBakcgroundTansperancy: CGFloat = 0.7
let kHeightMargin: CGFloat = 10.0
let KTopMargin: CGFloat = 20.0
let kWidthMargin: CGFloat = 10.0
let kAnimatedViewHeight: CGFloat = 70.0
let kMaxHeight: CGFloat = 500.0
var kContentWidth: CGFloat = 300.0
let kButtonHeight: CGFloat = 35.0
var textViewHeight: CGFloat = 90.0
let kTitleHeight:CGFloat = 30.0
var strongSelf:SweetAlert?
var contentView = UIView()
var titleLabel: UILabel = UILabel()
var buttons: [UIButton] = []
var animatedView: AnimatableView?
var imageView:UIImageView?
var subTitleTextView = UITextView()
var userAction:((isOtherButton: Bool) -> Void)? = nil
let kFont = "Helvetica"
override init() {
super.init()
self.view.frame = UIScreen.mainScreen().bounds
self.view.autoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth
self.view.backgroundColor = UIColor(red:0, green:0, blue:0, alpha:kBakcgroundTansperancy)
self.view.addSubview(contentView)
//Retaining itself strongly so can exist without strong refrence
strongSelf = self
}
func setupContentView() {
contentView.backgroundColor = UIColor(white: 1.0, alpha: 1.0)
contentView.layer.cornerRadius = 5.0
contentView.layer.masksToBounds = true
contentView.layer.borderWidth = 0.5
contentView.addSubview(titleLabel)
contentView.addSubview(subTitleTextView)
contentView.backgroundColor = UIColorFromRGB(0xFFFFFF)
contentView.layer.borderColor = UIColorFromRGB(0xCCCCCC).CGColor
view.addSubview(contentView)
}
func setupTitleLabel() {
titleLabel.text = ""
titleLabel.numberOfLines = 1
titleLabel.textAlignment = .Center
titleLabel.font = UIFont(name: kFont, size:25)
titleLabel.textColor = UIColorFromRGB(0x575757)
}
func setupSubtitleTextView() {
subTitleTextView.text = ""
subTitleTextView.textAlignment = .Center
subTitleTextView.font = UIFont(name: kFont, size:16)
subTitleTextView.textColor = UIColorFromRGB(0x797979)
subTitleTextView.editable = false
}
func resizeAndRelayout() {
var mainScreenBounds = UIScreen.mainScreen().bounds
self.view.frame.size = mainScreenBounds.size
var x: CGFloat = kWidthMargin
var y: CGFloat = KTopMargin
var width: CGFloat = kContentWidth - (kWidthMargin*2)
if animatedView != nil {
animatedView!.frame = CGRect(x: (kContentWidth - kAnimatedViewHeight) / 2.0, y: y, width: kAnimatedViewHeight, height: kAnimatedViewHeight)
contentView.addSubview(animatedView!)
y += kAnimatedViewHeight + kHeightMargin
}
if imageView != nil {
imageView!.frame = CGRect(x: (kContentWidth - kAnimatedViewHeight) / 2.0, y: y, width: kAnimatedViewHeight, height: kAnimatedViewHeight)
contentView.addSubview(imageView!)
y += imageView!.frame.size.height + kHeightMargin
}
// Title
if self.titleLabel.text != nil {
titleLabel.frame = CGRect(x: x, y: y, width: width, height: kTitleHeight)
contentView.addSubview(titleLabel)
y += kTitleHeight + kHeightMargin
}
// Subtitle
if self.subTitleTextView.text.isEmpty == false {
let subtitleString = subTitleTextView.text! as NSString
let rect = subtitleString.boundingRectWithSize(CGSize(width: width, height:0.0), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes:[NSFontAttributeName:subTitleTextView.font], context:nil)
textViewHeight = ceil(rect.size.height) + 10.0
subTitleTextView.frame = CGRect(x: x, y: y, width: width, height: textViewHeight)
contentView.addSubview(subTitleTextView)
y += textViewHeight + kHeightMargin
}
var buttonRect:[CGRect] = []
for button in buttons {
let string = button.titleForState(UIControlState.Normal)! as NSString
buttonRect.append(string.boundingRectWithSize(CGSize(width: width, height:0.0), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes:[NSFontAttributeName:button.titleLabel!.font], context:nil))
}
var totalWidth: CGFloat = 0.0
if buttons.count == 2 {
totalWidth = buttonRect[0].size.width + buttonRect[1].size.width + kWidthMargin + 40.0
}
else{
totalWidth = buttonRect[0].size.width + 20.0
}
y += kHeightMargin
var buttonX = (kContentWidth - totalWidth ) / 2.0
for var i = 0; i < buttons.count; i++ {
buttons[i].frame = CGRect(x: buttonX, y: y, width: buttonRect[i].size.width + 20.0, height: buttonRect[i].size.height + 10.0)
buttonX = buttons[i].frame.origin.x + kWidthMargin + buttonRect[i].size.width + 20.0
buttons[i].layer.cornerRadius = 5.0
self.contentView.addSubview(buttons[i])
buttons[i].addTarget(self, action: "pressed:", forControlEvents: UIControlEvents.TouchUpInside)
}
y += kHeightMargin + buttonRect[0].size.height + 10.0
contentView.frame = CGRect(x: (mainScreenBounds.size.width - kContentWidth) / 2.0, y: (mainScreenBounds.size.height - y) / 2.0, width: kContentWidth, height: y)
contentView.clipsToBounds = true
}
func pressed(sender: UIButton!) {
self.closeAlert(sender.tag)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
var sz = UIScreen.mainScreen().bounds.size
let sver = UIDevice.currentDevice().systemVersion as NSString
let ver = sver.floatValue
if ver < 8.0 {
// iOS versions before 7.0 did not switch the width and height on device roration
if UIInterfaceOrientationIsLandscape(UIApplication.sharedApplication().statusBarOrientation) {
let ssz = sz
sz = CGSize(width:ssz.height, height:ssz.width)
}
}
self.resizeAndRelayout()
}
func buttonTapped(btn:UIButton) {
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName:nibNameOrNil, bundle:nibBundleOrNil)
}
func closeAlert(buttonIndex:Int){
if userAction != nil {
var isOtherButton = buttonIndex == 0 ? true: false
SweetAlertContext.shouldNotAnimate = true
userAction!(isOtherButton: isOtherButton)
SweetAlertContext.shouldNotAnimate = false
}
UIView.animateWithDuration(0.5, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in
self.view.alpha = 0.0
}) { (Bool) -> Void in
self.view.removeFromSuperview()
self.cleanUpAlert()
//Releasing strong refrence of itself.
self.strongSelf = nil
}
}
func cleanUpAlert() {
if self.animatedView != nil {
self.animatedView!.removeFromSuperview()
self.animatedView = nil
}
self.contentView.removeFromSuperview()
self.contentView = UIView()
}
func showAlert(title: String) -> SweetAlert {
self.showAlert(title, subTitle: nil, style: .None)
return self
}
func showAlert(title: String, subTitle: String?, style: AlertStyle) -> SweetAlert {
self.showAlert(title, subTitle: subTitle, style: style, buttonTitle: "OK")
return self
}
func showAlert(title: String, subTitle: String?, style: AlertStyle,buttonTitle: String, action: ((isOtherButton: Bool) -> Void)? = nil) -> SweetAlert {
self.showAlert(title, subTitle: subTitle, style: style, buttonTitle: buttonTitle,buttonColor: UIColorFromRGB(0xAEDEF4))
userAction = action
return self
}
func showAlert(title: String, subTitle: String?, style: AlertStyle,buttonTitle: String,buttonColor: UIColor,action: ((isOtherButton: Bool) -> Void)? = nil) -> SweetAlert {
self.showAlert(title, subTitle: subTitle, style: style, buttonTitle: buttonTitle,buttonColor: buttonColor,otherButtonTitle:
nil)
userAction = action
return self
}
func showAlert(title: String, subTitle: String?, style: AlertStyle,buttonTitle: String,buttonColor: UIColor,otherButtonTitle:
String?, action: ((isOtherButton: Bool) -> Void)? = nil) -> SweetAlert {
self.showAlert(title, subTitle: subTitle, style: style, buttonTitle: buttonTitle,buttonColor: buttonColor,otherButtonTitle:
otherButtonTitle,otherButtonColor: UIColor.redColor())
userAction = action
return self
}
func showAlert(title: String, subTitle: String?, style: AlertStyle,buttonTitle: String,buttonColor: UIColor,otherButtonTitle:
String?, otherButtonColor: UIColor?,action: ((isOtherButton: Bool) -> Void)? = nil) {
userAction = action
let window = UIApplication.sharedApplication().keyWindow?.subviews.first as UIView
window.addSubview(view)
view.frame = window.bounds
self.setupContentView()
self.setupTitleLabel()
self.setupSubtitleTextView()
switch style {
case .Success:
self.animatedView = SuccessAnimatedView()
case .Error:
self.animatedView = CancelAnimatedView()
case .Warning:
self.animatedView = InfoAnimatedView()
case let .CustomImag(imageFile):
if let image = UIImage(named: imageFile) {
self.imageView = UIImageView(image: image)
}
case .None:
self.animatedView = nil
}
self.titleLabel.text = title
if subTitle != nil {
self.subTitleTextView.text = subTitle
}
buttons = []
if buttonTitle.isEmpty == false {
var button: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
button.setTitle(buttonTitle, forState: UIControlState.Normal)
button.backgroundColor = buttonColor
button.userInteractionEnabled = true
button.tag = 0
buttons.append(button)
}
if otherButtonTitle != nil && otherButtonTitle!.isEmpty == false {
var button: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
button.setTitle(otherButtonTitle, forState: UIControlState.Normal)
button.backgroundColor = otherButtonColor
button.addTarget(self, action: "pressed:", forControlEvents: UIControlEvents.TouchUpInside)
button.tag = 1
buttons.append(button)
}
resizeAndRelayout()
if SweetAlertContext.shouldNotAnimate == true {
//Do not animate Alert
if self.animatedView != nil {
self.animatedView!.animate()
}
}
else {
animateAlert()
}
}
func animateAlert() {
view.alpha = 0;
UIView.animateWithDuration(0.1, animations: { () -> Void in
self.view.alpha = 1.0;
})
var previousTransform = self.contentView.transform
self.contentView.layer.transform = CATransform3DMakeScale(0.9, 0.9, 0.0);
UIView.animateWithDuration(0.2, animations: { () -> Void in
self.contentView.layer.transform = CATransform3DMakeScale(1.1, 1.1, 0.0);
}) { (Bool) -> Void in
UIView.animateWithDuration(0.1, animations: { () -> Void in
self.contentView.layer.transform = CATransform3DMakeScale(0.9, 0.9, 0.0);
}) { (Bool) -> Void in
UIView.animateWithDuration(0.1, animations: { () -> Void in
self.contentView.layer.transform = CATransform3DMakeScale(1.0, 1.0, 0.0);
if self.animatedView != nil {
self.animatedView!.animate()
}
}) { (Bool) -> Void in
self.contentView.transform = previousTransform
}
}
}
}
private struct SweetAlertContext {
static var shouldNotAnimate = false
}
}
// MARK: -
// MARK: Animatable Views
class AnimatableView: UIView {
func animate(){
println("Should overide by subclasss")
}
}
class CancelAnimatedView: AnimatableView {
var circleLayer = CAShapeLayer()
var crossPathLayer = CAShapeLayer()
override init() {
super.init()
}
override required init(frame: CGRect) {
super.init(frame: frame)
setupLayers()
var t = CATransform3DIdentity;
t.m34 = 1.0 / -500.0;
t = CATransform3DRotate(t, CGFloat(90.0 * M_PI / 180.0), 1, 0, 0);
circleLayer.transform = t
crossPathLayer.opacity = 0.0
}
override func layoutSubviews() {
setupLayers()
}
required override init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var outlineCircle: CGPath {
var path = UIBezierPath()
let startAngle: CGFloat = CGFloat((0) / 180.0 * M_PI) //0
let endAngle: CGFloat = CGFloat((360) / 180.0 * M_PI) //360
path.addArcWithCenter(CGPointMake(self.frame.size.width/2.0, self.frame.size.width/2.0), radius: self.frame.size.width/2.0, startAngle: startAngle, endAngle: endAngle, clockwise: false)
return path.CGPath
}
var crossPath: CGPath {
var path = UIBezierPath()
var factor:CGFloat = self.frame.size.width / 5.0
path.moveToPoint(CGPoint(x: self.frame.size.height/2.0-factor,y: self.frame.size.height/2.0-factor))
path.addLineToPoint(CGPoint(x: self.frame.size.height/2.0+factor,y: self.frame.size.height/2.0+factor))
path.moveToPoint(CGPoint(x: self.frame.size.height/2.0+factor,y: self.frame.size.height/2.0-factor))
path.addLineToPoint(CGPoint(x: self.frame.size.height/2.0-factor,y: self.frame.size.height/2.0+factor))
return path.CGPath
}
func setupLayers() {
circleLayer.path = outlineCircle
circleLayer.fillColor = UIColor.clearColor().CGColor;
circleLayer.strokeColor = UIColorFromRGB(0xF27474).CGColor;
circleLayer.lineCap = kCALineCapRound
circleLayer.lineWidth = 4;
circleLayer.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)
circleLayer.position = CGPoint(x: self.frame.size.width/2.0, y: self.frame.size.height/2.0)
self.layer.addSublayer(circleLayer)
crossPathLayer.path = crossPath
crossPathLayer.fillColor = UIColor.clearColor().CGColor;
crossPathLayer.strokeColor = UIColorFromRGB(0xF27474).CGColor;
crossPathLayer.lineCap = kCALineCapRound
crossPathLayer.lineWidth = 4;
crossPathLayer.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)
crossPathLayer.position = CGPoint(x: self.frame.size.width/2.0, y: self.frame.size.height/2.0)
self.layer.addSublayer(crossPathLayer)
}
override func animate() {
var t = CATransform3DIdentity;
t.m34 = 1.0 / -500.0;
t = CATransform3DRotate(t, CGFloat(90.0 * M_PI / 180.0), 1, 0, 0);
var t2 = CATransform3DIdentity;
t2.m34 = 1.0 / -500.0;
t2 = CATransform3DRotate(t2, CGFloat(-M_PI), 1, 0, 0);
let animation = CABasicAnimation(keyPath: "transform")
var time = 0.3
animation.duration = time;
animation.fromValue = NSValue(CATransform3D: t)
animation.toValue = NSValue(CATransform3D:t2)
animation.removedOnCompletion = false
animation.fillMode = kCAFillModeForwards
self.circleLayer.addAnimation(animation, forKey: "transform")
var scale = CATransform3DIdentity;
scale = CATransform3DScale(scale, 0.3, 0.3, 0)
let crossAnimation = CABasicAnimation(keyPath: "transform")
crossAnimation.duration = 0.3;
crossAnimation.beginTime = CACurrentMediaTime() + time
crossAnimation.fromValue = NSValue(CATransform3D: scale)
crossAnimation.timingFunction = CAMediaTimingFunction(controlPoints: 0.25, 0.8, 0.7, 2.0)
crossAnimation.toValue = NSValue(CATransform3D:CATransform3DIdentity)
self.crossPathLayer.addAnimation(crossAnimation, forKey: "scale")
var fadeInAnimation = CABasicAnimation(keyPath: "opacity")
fadeInAnimation.duration = 0.3;
fadeInAnimation.beginTime = CACurrentMediaTime() + time
fadeInAnimation.fromValue = 0.3
fadeInAnimation.toValue = 1.0
fadeInAnimation.removedOnCompletion = false
fadeInAnimation.fillMode = kCAFillModeForwards
self.crossPathLayer.addAnimation(fadeInAnimation, forKey: "opacity")
}
}
class InfoAnimatedView: AnimatableView {
var circleLayer = CAShapeLayer()
var crossPathLayer = CAShapeLayer()
override init() {
super.init()
}
override required init(frame: CGRect) {
super.init(frame: frame)
setupLayers()
}
override func layoutSubviews() {
setupLayers()
}
required override init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var outlineCircle: CGPath {
var path = UIBezierPath()
let startAngle: CGFloat = CGFloat((0) / 180.0 * M_PI) //0
let endAngle: CGFloat = CGFloat((360) / 180.0 * M_PI) //360
path.addArcWithCenter(CGPointMake(self.frame.size.width/2.0, self.frame.size.width/2.0), radius: self.frame.size.width/2.0, startAngle: startAngle, endAngle: endAngle, clockwise: false)
var factor:CGFloat = self.frame.size.width / 1.5
path.moveToPoint(CGPoint(x: self.frame.size.width/2.0 , y: 15.0))
path.addLineToPoint(CGPoint(x: self.frame.size.width/2.0,y: factor))
path.moveToPoint(CGPoint(x: self.frame.size.width/2.0,y: factor + 10.0))
path.addArcWithCenter(CGPoint(x: self.frame.size.width/2.0,y: factor + 10.0), radius: 1.0, startAngle: startAngle, endAngle: endAngle, clockwise: true)
return path.CGPath
}
func setupLayers() {
circleLayer.path = outlineCircle
circleLayer.fillColor = UIColor.clearColor().CGColor;
circleLayer.strokeColor = UIColorFromRGB(0xF8D486).CGColor;
circleLayer.lineCap = kCALineCapRound
circleLayer.lineWidth = 4;
circleLayer.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)
circleLayer.position = CGPoint(x: self.frame.size.width/2.0, y: self.frame.size.height/2.0)
self.layer.addSublayer(circleLayer)
}
override func animate() {
var colorAnimation = CABasicAnimation(keyPath:"strokeColor")
colorAnimation.duration = 1.0;
colorAnimation.repeatCount = HUGE
colorAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
colorAnimation.autoreverses = true
colorAnimation.fromValue = UIColorFromRGB(0xF7D58B).CGColor
colorAnimation.toValue = UIColorFromRGB(0xF2A665).CGColor
circleLayer.addAnimation(colorAnimation, forKey: "strokeColor")
}
}
class SuccessAnimatedView: AnimatableView {
var circleLayer = CAShapeLayer()
var outlineLayer = CAShapeLayer()
override init() {
super.init()
self.setupLayers()
circleLayer.strokeStart = 0.0
circleLayer.strokeEnd = 0.0
}
override init(frame: CGRect) {
super.init(frame: frame)
setupLayers()
circleLayer.strokeStart = 0.0
circleLayer.strokeEnd = 0.0
}
required override init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
setupLayers()
}
var outlineCircle: CGPath {
var path = UIBezierPath()
let startAngle: CGFloat = CGFloat((0) / 180.0 * M_PI) //0
let endAngle: CGFloat = CGFloat((360) / 180.0 * M_PI) //360
path.addArcWithCenter(CGPointMake(self.frame.size.width/2.0, self.frame.size.height/2.0), radius: self.frame.size.width/2.0, startAngle: startAngle, endAngle: endAngle, clockwise: false)
return path.CGPath
}
var path: CGPath {
var path = UIBezierPath()
var startAngle:CGFloat = CGFloat((60) / 180.0 * M_PI) //60
var endAngle:CGFloat = CGFloat((200) / 180.0 * M_PI) //190
path.addArcWithCenter(CGPointMake(self.frame.size.width/2.0, self.frame.size.height/2.0), radius: self.frame.size.width/2.0, startAngle: startAngle, endAngle: endAngle, clockwise: false)
path.addLineToPoint(CGPoint(x: 36.0 - 10.0 ,y: 60.0 - 10.0))
path.addLineToPoint(CGPoint(x: 85.0 - 20.0, y: 30.0 - 20.0))
return path.CGPath
}
func setupLayers() {
outlineLayer.position = CGPointMake(0,
0);
outlineLayer.path = outlineCircle
outlineLayer.fillColor = UIColor.clearColor().CGColor;
outlineLayer.strokeColor = UIColor(red: 150.0/255.0, green: 216.0/255.0, blue: 115.0/255.0, alpha: 1.0).CGColor;
outlineLayer.lineCap = kCALineCapRound
outlineLayer.lineWidth = 4;
outlineLayer.opacity = 0.1
self.layer.addSublayer(outlineLayer)
circleLayer.position = CGPointMake(0,
0);
circleLayer.path = path
circleLayer.fillColor = UIColor.clearColor().CGColor;
circleLayer.strokeColor = UIColor(red: 150.0/255.0, green: 216.0/255.0, blue: 115.0/255.0, alpha: 1.0).CGColor;
circleLayer.lineCap = kCALineCapRound
circleLayer.lineWidth = 4;
circleLayer.actions = [
"strokeStart": NSNull(),
"strokeEnd": NSNull(),
"transform": NSNull()
]
self.layer.addSublayer(circleLayer)
}
override func animate() {
let strokeStart = CABasicAnimation(keyPath: "strokeStart")
let strokeEnd = CABasicAnimation(keyPath: "strokeEnd")
var factor = 0.045
strokeEnd.fromValue = 0.00
strokeEnd.toValue = 0.93
strokeEnd.duration = 10.0*factor
var timing = CAMediaTimingFunction(controlPoints: 0.3, 0.6, 0.8, 1.2)
strokeEnd.timingFunction = timing
strokeStart.fromValue = 0.0
strokeStart.toValue = 0.68
strokeStart.duration = 7.0*factor
strokeStart.beginTime = CACurrentMediaTime() + 3.0*factor
strokeStart.fillMode = kCAFillModeBackwards
strokeStart.timingFunction = timing
circleLayer.strokeStart = 0.68
circleLayer.strokeEnd = 0.93
self.circleLayer.addAnimation(strokeEnd, forKey: "strokeEnd")
self.circleLayer.addAnimation(strokeStart, forKey: "strokeStart")
}
}
func UIColorFromRGB(rgbValue: UInt) -> UIColor {
return UIColor(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
|
mit
|
0d5e9aba47b03a4eda1078661fffa959
| 36.504505 | 219 | 0.610217 | 4.683668 | false | false | false | false |
andressbarnes/ABLoader
|
ABLoader/ABLoader/AppDelegate.swift
|
1
|
2609
|
//
// AppDelegate.swift
// ABLoader
//
// Created by John Barnes on 8/14/16.
// Copyright © 2016 Andress Barnes. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
// Override point for customization after application launch.
let vc = ViewController()
let navigationController = UINavigationController(rootViewController: vc)
self.window!.rootViewController = navigationController
self.window!.makeKeyAndVisible()
navigationController.setNavigationBarHidden(true, animated: false)
self.window!.backgroundColor = UIColor.lightGrayColor()
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:.
}
}
|
mit
|
aac3d8ef48829b835a8ef334cc417a6c
| 44.754386 | 285 | 0.739264 | 5.694323 | false | false | false | false |
steve-holmes/music-app-2
|
MusicApp/Modules/Player/PlayerViewController.swift
|
1
|
6507
|
//
// PlayerViewController.swift
// MusicApp
//
// Created by Hưng Đỗ on 6/9/17.
// Copyright © 2017 HungDo. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import RxGesture
import Action
import NSObject_Rx
class PlayerViewController: UIViewController {
@IBOutlet weak var backgroundImageView: UIImageView!
@IBOutlet weak var containerView: PlayContainerView!
@IBOutlet weak var alphaView: UIVisualEffectView!
@IBOutlet weak var progressBar: PlayerProgressBar!
@IBOutlet weak var playButton: PlayCenterView!
@IBOutlet weak var backwardButton: UIButton!
@IBOutlet weak var forwardButton: UIButton!
@IBOutlet weak var repeatButton: UIButton!
@IBOutlet weak var refreshButton: UIButton!
@IBOutlet weak var pageControl: PlayerPageControl!
@IBOutlet weak var heartButton: UIButton!
@IBOutlet weak var downloadButton: UIButton!
@IBOutlet weak var shareButton: UIButton!
@IBOutlet weak var calendarButton: UIButton!
@IBOutlet weak var volumeButton: UIButton!
@IBOutlet weak var panelView: UIView!
@IBOutlet weak var volumeView: PlayerVolumeView!
var store: PlayerStore!
var action: PlayerAction!
var controllers: [UIViewController] = []
var timer: PlayerTimer!
// MARK Life Cycles
override func viewDidLoad() {
super.viewDidLoad()
containerView.configure(controllers: controllers, pageControl: pageControl, containerController: self)
progressBar.configure()
pageControl.configure()
bindStore()
bindAction()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
timer.stop()
}
// MARK: Actions
@IBAction func backButtonTapped(_ backButton: UIButton) {
self.dismiss(animated: true, completion: nil)
}
// MARK: Status Bar
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
}
// MARK: Store
extension PlayerViewController {
func bindStore() {
store.playButtonState.asObservable()
.filter { $0 == .playing }
.subscribe(onNext: { [weak self] _ in
self?.playButton.updatePlayingState()
})
.addDisposableTo(rx_disposeBag)
store.playButtonState.asObservable()
.filter { $0 == .paused }
.subscribe(onNext: { [weak self] _ in
self?.playButton.updatePausedState()
})
.addDisposableTo(rx_disposeBag)
store.repeatMode.asObservable()
.subscribe(onNext: { [weak self] mode in
switch mode {
case .flow: self?.repeatButton.setImage(#imageLiteral(resourceName: "repeat_flow"), for: .normal)
case .repeat: self?.repeatButton.setImage(#imageLiteral(resourceName: "repeat"), for: .normal)
case .repeatOne: self?.repeatButton.setImage(#imageLiteral(resourceName: "repeat_one"), for: .normal)
case .shuffle: self?.repeatButton.setImage(#imageLiteral(resourceName: "repeat_shuffle"), for: .normal)
}
})
.addDisposableTo(rx_disposeBag)
store.duration.asObservable()
.bind(to: progressBar.rx.duration)
.addDisposableTo(rx_disposeBag)
store.currentTime.asObservable()
.bind(to: progressBar.rx.currentTime)
.addDisposableTo(rx_disposeBag)
store.track.asObservable()
.skip(1)
.subscribe(onNext: { [weak self] track in
self?.backgroundImageView.fadeImage(track.avatar, placeholder: nil, duration: 1)
})
.addDisposableTo(rx_disposeBag)
let volumeEnabled = store.volumeEnabled.asObservable()
.skip(1)
.distinctUntilChanged()
.shareReplay(1)
volumeEnabled
.filter { $0 }
.subscribe(onNext: { [weak self] _ in
guard let this = self else { return }
this.volumeView.isHidden = false
this.panelView.isHidden = false
this.volumeView.alpha = 0
this.panelView.alpha = 1
UIView.animate(withDuration: 0.2, animations: {
this.volumeView.alpha = 1
this.panelView.alpha = 0
}, completion: { _ in
this.volumeView.isHidden = false
this.panelView.isHidden = true
})
})
.addDisposableTo(rx_disposeBag)
volumeEnabled
.filter { !$0 }
.subscribe(onNext: { [weak self] _ in
guard let this = self else { return }
this.volumeView.isHidden = false
this.panelView.isHidden = false
this.volumeView.alpha = 1
this.panelView.alpha = 0
UIView.animate(withDuration: 0.2, animations: {
this.volumeView.alpha = 0
this.panelView.alpha = 1
}, completion: { _ in
this.volumeView.isHidden = true
this.panelView.isHidden = false
})
})
.addDisposableTo(rx_disposeBag)
}
}
// MARK: Action
extension PlayerViewController {
func bindAction() {
playButton.action = action.onPlayButtonPress()
backwardButton.rx.action = action.onBackwardPress()
forwardButton.rx.action = action.onForwardPress()
repeatButton.rx.action = action.onRepeatPress()
refreshButton.rx.action = action.onRefreshPress()
progressBar.endDraggingAction = action.onProgressBarDidEndDragging()
heartButton.rx.action = action.onHeartButtonPress()
downloadButton.rx.action = action.onDownloadButtonPress()
shareButton.rx.action = action.onShareButtonPress()
calendarButton.rx.action = CocoaAction { [weak self] in
self?.timer.presentPanel() ?? .empty()
}
volumeButton.rx.action = action.onVolumeButtonPress()
volumeView.action = action.onVolumeButtonPress()
}
}
|
mit
|
4b96224a83471e90265534fe10f82439
| 31.838384 | 124 | 0.581052 | 5.152139 | false | false | false | false |
OneBusAway/onebusaway-iphone
|
Carthage/Checkouts/SwiftEntryKit/Source/MessageViews/Notes/EKAccessoryNoteMessageView.swift
|
3
|
1144
|
//
// EKAccessoryNoteMessageView.swift
// SwiftEntryKit
//
// Created by Daniel Huri on 5/4/18.
//
import UIKit
public class EKAccessoryNoteMessageView: UIView {
// MARK: Props
private let contentView = UIView()
private var noteMessageView: EKNoteMessageView!
var accessoryView: UIView!
func setup(with content: EKProperty.LabelContent) {
clipsToBounds = true
addSubview(contentView)
contentView.layoutToSuperview(.centerX, .top, .bottom)
contentView.layoutToSuperview(.left, relation: .greaterThanOrEqual, offset: 16)
contentView.layoutToSuperview(.right, relation: .lessThanOrEqual, offset: -16)
noteMessageView = EKNoteMessageView(with: content)
noteMessageView.horizontalOffset = 8
noteMessageView.verticalOffset = 7
contentView.addSubview(noteMessageView)
noteMessageView.layoutToSuperview(.top, .bottom, .trailing)
contentView.addSubview(accessoryView)
accessoryView.layoutToSuperview(.leading, .centerY)
accessoryView.layout(.trailing, to: .leading, of: noteMessageView)
}
}
|
apache-2.0
|
4601ef8c6e02defe22de3a1d119a2fc2
| 31.685714 | 87 | 0.697552 | 4.847458 | false | false | false | false |
SpriteKitAlliance/SKATiledMap
|
SKATiledMap/SKAObject.swift
|
1
|
3836
|
//
// SKAObject.swift
//
// Created by Skyler Lauren on 10/5/15.
// Copyright © 2015 Sprite Kit Alliance. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import Foundation
class SKAObject{
/**
X position defined by Tiled at creation
*/
let x : Int
/**
Y position defined by Tiled at creation
y position is flipped based on layer draworder
*/
var y : Int
/**
Width defined by Tiled at creation
*/
let width : Int
/**
Height defined by Tiled at creation
*/
let height : Int
/**
Name defined by Tiled at creation
*/
let name : String
/**
Type defined by Tiled at creation
*/
let type : String
/**
Rotation defined by Tiled at creation
*/
var rotation : Float
/**
Visible defined by Tiled at creation
*/
var visible : Bool
var properties : [String : AnyObject]?
/**
Designated Initializer
@param properties the properties that come from the JSON or TMX file
*/
init(properties: [String: AnyObject]){
guard let _ = properties["name"] as? String else{
fatalError("Error: required name property missing on tile object")
}
name = properties["name"] as! String
guard let _ = properties["type"] as? String else{
fatalError("Error: required type property missing on tile object")
}
type = properties["type"] as! String
guard let _ = properties["x"] as? Int else{
fatalError("Error: required x position is missing on tile object")
}
x = properties["x"] as! Int
guard let _ = properties["y"] as? Int else{
fatalError("Error: required y position is missing on tile object")
}
y = properties["y"] as! Int
guard let _ = properties["width"] as? Int else {
fatalError("Error: required width is missing on tile object")
}
width = properties["width"] as! Int
guard let _ = properties["height"] as? Int else{
fatalError("Error: required height is missing on tile object")
}
height = properties["height"] as! Int
self.properties = properties["properties"] as? [String : AnyObject]
guard let _ = properties["rotation"] as? Float else{
fatalError("Error: required rotation is missing on tile object")
}
rotation = properties["rotation"] as! Float
guard let _ = properties["visible"] as? Bool else{
fatalError("Error: required visible is missing on tile object")
}
visible = properties["visible"] as! Bool
}
}
|
mit
|
aca5bbda8344fef784f518ca9b0e4e7e
| 29.927419 | 80 | 0.621643 | 4.694002 | false | false | false | false |
clonezer/FreeForm
|
FreeForm/Classes/FreeFormTextFieldCell.swift
|
1
|
4719
|
//
// FreeFormTextFieldCell.swift
// FreeForm
//
// Created by Peerasak Unsakon on 11/27/16.
// Copyright © 2016 Peerasak Unsakon. All rights reserved.
//
import UIKit
import Validator
public class FreeFormTextFieldRow: FreeFormRow {
public var validationRuleSet: ValidationRuleSet<String>? = ValidationRuleSet<String>() {
didSet {
self.validationErrors = [String]()
}
}
public var validationErrors: [String]?
override public init(tag: String, title: String, value: AnyObject?) {
super.init(tag: tag, title: title, value: value)
self.cellType = String(describing: FreeFormTextFieldCell.self)
}
public func updateValidationState(text: String?, result: ValidationResult) -> Bool {
if self.isOptional == true {
if let content = text {
if content.characters.count > 0 {
switch result {
case .invalid(let failures):
self.validated = false
self.validationErrors = failures.map { $0.localizedDescription }
return false
case .valid:
self.validated = true
self.validationErrors?.removeAll()
return true
}
}else {
self.validated = true
self.validationErrors?.removeAll()
return true
}
}else {
self.validated = true
self.validationErrors?.removeAll()
return true
}
}else {
switch result {
case .invalid(let failures):
self.validated = false
self.validationErrors = failures.map { $0.localizedDescription }
return false
case .valid:
self.validated = true
self.validationErrors?.removeAll()
return true
}
}
}
public func clearRules() {
self.validationRuleSet = ValidationRuleSet<String>()
}
}
public class FreeFormTextFieldCell: FreeFormCell {
@IBOutlet weak public var textField: UITextField!
@IBOutlet weak public var titleLabel: UILabel!
@IBOutlet weak public var errorLabel: UILabel!
override public func awakeFromNib() {
super.awakeFromNib()
self.textField.delegate = self
self.textField.addTarget(self, action: #selector(self.textFieldDidChange(textField:)), for: UIControlEvents.editingChanged)
}
override public func update() {
super.update()
self.clearError()
guard let textfieldRow = self.row as? FreeFormTextFieldRow else { return }
titleLabel.text = textfieldRow.title
self.textField.validationRules = textfieldRow.validationRuleSet
guard let value = textfieldRow.value as? String else {
textField.text = ""
return
}
textField.text = value
}
public func validateTextField() {
guard let textfieldRow = self.row as? FreeFormTextFieldRow else { return }
guard let rules = textfieldRow.validationRuleSet else { return }
let result = self.textField.validate(rules: rules)
textfieldRow.validationErrors = [String]()
if textfieldRow.updateValidationState(text: self.textField.text, result: result) {
self.clearError()
}else {
if let message = textfieldRow.validationErrors?.joined(separator: "/") {
self.showError(message: message)
}
}
}
public func showError(message: String) {
self.errorLabel.text = message
}
public func clearError() {
self.errorLabel.text = ""
guard let textfieldRow = self.row as? FreeFormTextFieldRow else { return }
textfieldRow.validationErrors?.removeAll()
}
}
extension FreeFormTextFieldCell: UITextFieldDelegate {
public func textFieldDidChange(textField: UITextField) {
guard let text = textField.text else { return }
row.value = textField.text as AnyObject?
if let changeBlock = row.didChanged {
changeBlock(textField.text! as AnyObject, row)
}
}
public func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
guard row.disable == false else { return false }
return true
}
public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
|
mit
|
da800b88aa628815d0bfbfbdc7b853a2
| 31.763889 | 131 | 0.58139 | 5.307087 | false | false | false | false |
MastodonKit/MastodonKit
|
Sources/MastodonKit/Requests/DomainBlocks.swift
|
1
|
1521
|
//
// DomainBlocks.swift
// MastodonKit
//
// Created by Ornithologist Coder on 6/5/17.
// Copyright © 2017 MastodonKit. All rights reserved.
//
import Foundation
/// `DomainBlocks` requests.
public enum DomainBlocks {
/// Fetches a user's blocked domains.
///
/// - Parameter range: The bounds used when requesting data from Mastodon.
/// - Returns: Request for `[String]`.
public static func all(range: RequestRange = .default) -> Request<[String]> {
let parameters = range.parameters(limit: between(1, and: 80, default: 40))
let method = HTTPMethod.get(.parameters(parameters))
return Request<[String]>(path: "/api/v1/domain_blocks", method: method)
}
/// Blocks a domain.
///
/// - Parameter domain: The domain to block.
/// - Returns: Request for `Empty`.
public static func block(domain: String) -> Request<Empty> {
let parameter = [Parameter(name: "domain", value: domain)]
let method = HTTPMethod.post(.parameters(parameter))
return Request<Empty>(path: "/api/v1/domain_blocks", method: method)
}
/// Unblocks a domain.
///
/// - Parameter domain: The domain to unblock.
/// - Returns: Request for `Empty`.
public static func unblock(domain: String) -> Request<Empty> {
let parameter = [Parameter(name: "domain", value: domain)]
let method = HTTPMethod.delete(.parameters(parameter))
return Request<Empty>(path: "/api/v1/domain_blocks", method: method)
}
}
|
mit
|
2cd5e07c37fbaafdbc10c9bb693f564f
| 32.777778 | 82 | 0.639474 | 4.086022 | false | false | false | false |
cloudant/swift-cloudant
|
Source/SwiftCloudant/Operations/Database/GetChangesOperation.swift
|
1
|
8197
|
//
// GetChangesOperation.swift
// SwiftCloudant
//
// Created by Rhys Short on 22/08/2016.
//
// Copyright (C) 2016 IBM Corp.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
//
import Foundation
/**
Operation to get the changes feed for a database.
Example usage:
```
let changes = GetChangesOperation(dbName: "exampleDB", changeHandler: {(change) in
// do something for each change.
}) { (response, info, error) in
if let error = error {
// handle the error
} else {
// process the changes feed result.
}
}
```
*/
public class GetChangesOperation : CouchDatabaseOperation, JSONOperation {
public typealias Json = [String: Any]
/**
Abstract representation of a CouchDB Sequence. No assumptions should be
made about the concrete type that is returned from the server, it should be used
transparently.
*/
public typealias Sequence = Any
/**
The style of changes feed that should be requested.
*/
public enum Style : String {
/**
Only the "winning" revision.
*/
case main = "main_only"
/**
All "leaf" revisions (include previously deleted conflicts).
*/
case allLeaves = "all_docs"
}
public let databaseName: String
public let completionHandler: (([String: Any]?, HTTPInfo?, Error?) -> Void)?
/**
List of document IDs to limit the changes to.
*/
public let docIDs: [String]?
/**
Include conflict information in the response.
*/
public let conflicts: Bool?
/**
Sort the changes feed in descending sequence order.
*/
public let descending: Bool?
/**
The filter function to use to filter the feed.
*/
public let filter: String?
/**
Include the associated document with each result in the changes feed.
*/
public let includeDocs: Bool?
/**
Include attachments as Base-64 encoded data in the document.
*/
public let includeAttachments: Bool?
/**
Include information encoding in attachment stubs.
*/
public let includeAttachmentEncodingInformation: Bool?
/**
The number of results that the feed should be limited to.
*/
public let limit: Int?
/**
Return results starting from the sequence after.
*/
public let since: Sequence?
/**
Specifies how many revisions are returned in the changes array.
*/
public let style: Style?
/**
The view to use for filtering the changes feed, to be used with the `_view` filter.
*/
public let view: String?
/**
A handler to run for each entry in the `results` array in the response.
*/
public let changeHandler: (([String: Any]) -> Void)? // this will be each result in the `results` section of the response
/**
Creates the operation.
- param databaseName: The name of the database from which to get the changes
- param docIDs: Document IDs to limit the changes result to.
- param conflicts: include information about conflicts in the response
- param descending: sort the changes feed in descending sequence order.
- param filter: the name of a filter function to use to filter the changes feed.
- param includeDocs: include the document contents with the changes feed result.
- param includeAttachments: include the attachments inline with the document results
- param includeAttachmentEncodingInformation: Include attachment encoding information for attachment stubs
- param limit: the number of results the response should be limited to.
- param since: Return results starting from the sequence after this one.
- param style: the style of changes feed that should be returned
- param view: The view to use for filtering the changes feed, should be used with `_view` filter.
- param changeHandler: A handler to call for each change returned from the server.
- param completionHander: A handler to call when the operation has compeleted.
*/
public init(databaseName:String,
docIDs:[String]? = nil,
conflicts: Bool? = nil,
descending: Bool? = nil,
filter: String? = nil,
includeDocs: Bool? = nil,
includeAttachments: Bool? = nil,
includeAttachmentEncodingInformation: Bool? = nil,
limit: Int? = nil,
since: Int? = nil,
style: Style? = nil,
view: String? = nil,
changeHandler: (([String: Any]) -> Void)? = nil,
completionHandler: (([String: Any]?, HTTPInfo?, Error?) -> Void)? = nil){
self.databaseName = databaseName
self.docIDs = docIDs
self.conflicts = conflicts
self.descending = descending
self.filter = filter
self.includeDocs = includeDocs
self.includeAttachments = includeAttachments
self.includeAttachmentEncodingInformation = includeAttachmentEncodingInformation
self.limit = limit
self.since = since
self.style = style
self.view = view
self.changeHandler = changeHandler
self.completionHandler = completionHandler
}
public var endpoint: String {
return "/\(self.databaseName)/_changes"
}
public var parameters: [String : String] {
get {
var params: [String: String] = [:]
if let conflicts = conflicts {
params["conflicts"] = conflicts.description
}
if let descending = descending {
params["descending"] = descending.description
}
if let filter = filter {
params["filter"] = filter
}
if let includeDocs = includeDocs {
params["include_docs"] = includeDocs.description
}
if let includeAttachments = includeAttachments {
params["attachments"] = includeAttachments.description
}
if let includeAttachmentEncodingInformation = includeAttachmentEncodingInformation {
params["att_encoding_info"] = includeAttachmentEncodingInformation.description
}
if let limit = limit {
params["limit"] = "\(limit)"
}
if let since = since {
params["since"] = "\(since)"
}
if let style = style {
params["style"] = style.rawValue
}
if let view = view {
params["view"] = view
}
return params
}
}
private var jsonData: Data? = nil
public func serialise() throws {
if let docIDs = docIDs {
jsonData = try JSONSerialization.data(withJSONObject: ["doc_ids": docIDs])
}
}
public var data: Data? {
return jsonData
}
public func processResponse(json: Any) {
if let json = json as? [String: Any],
let results = json["results"] as? [[String: Any]] {
for result in results {
self.changeHandler?(result)
}
}
}
public var method: String {
get {
if let _ = jsonData {
return "POST"
} else {
return "GET"
}
}
}
}
|
apache-2.0
|
1954f7bdcf791382cb247d3ebe3d7171
| 30.771318 | 125 | 0.583872 | 5.069264 | false | false | false | false |
railsdog/CleanroomLogger
|
Code/Log.swift
|
3
|
13979
|
//
// Log.swift
// Cleanroom Project
//
// Created by Evan Maloney on 3/18/15.
// Copyright (c) 2015 Gilt Groupe. All rights reserved.
//
import Foundation
/**
`Log` is the primary public API for CleanroomLogger.
If you wish to send a message to the log, you do so by calling the appropriae
function provided by the appropriate `LogChannel` given the importance of your
message.
There are five levels of severity at which log messages can be recorded. Each
level is represented by a read-only static variable maintained by the `Log`:
- `Log.error` — The highest severity; something has gone wrong and a fatal error
may be imminent
- `Log.warning` — Something appears amiss and might bear looking into before a
larger problem arises
- `Log.info` — Something notable happened, but it isn't anything to worry about
- `Log.debug` — Used for debugging and diagnostic information
- `Log.verbose` - The lowest severity; used for detailed or frequently occurring
debugging and diagnostic information
Each `LogChannel` can be used in one of three ways:
- The `trace()` function records a short log message detailing the source
file, source line, and function name of the caller. It is intended to be called
with no arguments, as follows:
```
Log.debug?.trace()
```
- The `message()` function records a message specified by the caller:
```
Log.info?.message("The application has finished launching.")
```
`message()` is intended to be called with a single parameter, the message
string, as shown above. Unlike `NSLog()`, no `printf`-like functionality
is provided; instead, use Swift string interpolation to construct parameterized
messages.
- Finally, the `value()` function records a string representation of an
arbitrary `Any` value:
```
Log.verbose?.value(delegate)
```
The `value()` function is intended to be called with a single parameter, of
type `Any?`.
The underlying logging implementation is responsible for converting this value
into a string representation.
Note that some implementations may not be able to convert certain values into
strings; in those cases, log requests may be silently ignored.
### Enabling logging
By default, logging is disabled, meaning that none of the `Log`'s *log channels*
have been populated. As a result, attempts to perform any logging will silently
fail.
It is the responsibility of the *application developer* to enable logging, which
is done by calling the appropriate `Log.enable()` function.
*/
public struct Log
{
/** The `LogChannel` that can be used to perform logging at the `.Error`
log severity level. Will be `nil` if the `Log` has not been enabled with
a minimum severity of `.Error` or greater. */
public static var error: LogChannel? { return _error }
/** The `LogChannel` that can be used to perform logging at the `.Warning`
log severity level. Will be `nil` if the `Log` has not been enabled with
a minimum severity of `.Warning` or greater. */
public static var warning: LogChannel? { return _warning }
/** The `LogChannel` that can be used to perform logging at the `.Info`
log severity level. Will be `nil` if the `Log` has not been enabled with
a minimum severity of `.Info` or greater. */
public static var info: LogChannel? { return _info }
/** The `LogChannel` that can be used to perform logging at the `.Debug`
log severity level. Will be `nil` if the `Log` has not been enabled with
a minimum severity of `.Debug` or greater. */
public static var debug: LogChannel? { return _debug }
/** The `LogChannel` that can be used to perform logging at the `.Verbose`
log severity level. Will be `nil` if the `Log` has not been enabled with
a minimum severity of `.Verbose` or greater. */
public static var verbose: LogChannel? { return _verbose }
/**
Enables logging with the specified minimum `LogSeverity` using the
`DefaultLogConfiguration`.
This variant logs to the Apple System Log and to the `stderr` output
stream of the application process. In Xcode, log messages will appear in
the console.
:param: minimumSeverity The minimum `LogSeverity` for which log messages
will be accepted. Attempts to log messages less severe than
`minimumSeverity` will be silently ignored.
:param: synchronousMode Determines whether synchronous mode logging
will be used. **Use of synchronous mode is not recommended in
production code**; it is provided for use during debugging, to
help ensure that messages send prior to hitting a breakpoint
will appear in the console when the breakpoint is hit.
*/
public static func enable(minimumSeverity: LogSeverity = .Info, synchronousMode: Bool = false)
{
let config = DefaultLogConfiguration(minimumSeverity: minimumSeverity, synchronousMode: synchronousMode)
enable(config)
}
/**
Enables logging using the specified `LogConfiguration`.
:param: configuration The `LogConfiguration` to use for controlling
the behavior of logging.
*/
public static func enable(configuration: LogConfiguration)
{
enable([configuration], minimumSeverity: configuration.minimumSeverity)
}
/**
Enables logging using the specified list of `LogConfiguration`s.
:param: configuration The list of `LogConfiguration`s to use for controlling
the behavior of logging.
:param: minimumSeverity The minimum `LogSeverity` for which log messages
will be accepted. Attempts to log messages less severe than
`minimumSeverity` will be silently ignored.
*/
public static func enable(configuration: [LogConfiguration], minimumSeverity: LogSeverity = .Info)
{
let recept = LogReceptacle(configuration: configuration)
enable(recept, minimumSeverity: minimumSeverity)
}
/**
Enables logging using the specified `LogReceptacle`.
Individual `LogChannel`s for `error`, `warning`, `info`, `debug`, and
`verbose` will be constructed based on the specified `minimumSeverity`.
Each channel will use `receptacle` as the underlying `LogReceptacle`.
:param: receptacle The list of `LogConfiguration`s to use for controlling
the behavior of logging.
:param: minimumSeverity The minimum `LogSeverity` for which log messages
will be accepted. Attempts to log messages less severe than
`minimumSeverity` will be silently ignored.
*/
public static func enable(receptacle: LogReceptacle, minimumSeverity: LogSeverity = .Info)
{
enable(
errorChannel: self.createLogChannelWithSeverity(.Error, receptacle: receptacle, minimumSeverity: minimumSeverity),
warningChannel: self.createLogChannelWithSeverity(.Warning, receptacle: receptacle, minimumSeverity: minimumSeverity),
infoChannel: self.createLogChannelWithSeverity(.Info, receptacle: receptacle, minimumSeverity: minimumSeverity),
debugChannel: self.createLogChannelWithSeverity(.Debug, receptacle: receptacle, minimumSeverity: minimumSeverity),
verboseChannel: self.createLogChannelWithSeverity(.Verbose, receptacle: receptacle, minimumSeverity: minimumSeverity)
)
}
/**
Enables logging using the specified `LogChannel`s.
The static `error`, `warning`, `info`, `debug`, and `verbose` properties of
`Log` will be set using the specified values.
If you know that the configuration of a given `LogChannel` guarantees that
it will never perform logging, it is best to pass `nil` instead. Otherwise,
needless overhead will be added to the application.
:param: errorChannel The `LogChannel` to use for logging messages with
a `severity` of `.Error`.
:param: warningChannel The `LogChannel` to use for logging messages with
a `severity` of `.Warning`.
:param: infoChannel The `LogChannel` to use for logging messages with
a `severity` of `.Info`.
:param: debugChannel The `LogChannel` to use for logging messages with
a `severity` of `.Debug`.
:param: verboseChannel The `LogChannel` to use for logging messages with
a `severity` of `.Verbose`.
*/
public static func enable(errorChannel errorChannel: LogChannel?, warningChannel: LogChannel?, infoChannel: LogChannel?, debugChannel: LogChannel?, verboseChannel: LogChannel?)
{
dispatch_once(&enableOnce) {
self._error = errorChannel
self._warning = warningChannel
self._info = infoChannel
self._debug = debugChannel
self._verbose = verboseChannel
}
}
private static var _error: LogChannel?
private static var _warning: LogChannel?
private static var _info: LogChannel?
private static var _debug: LogChannel?
private static var _verbose: LogChannel?
private static var enableOnce = dispatch_once_t()
/**
Returns the `LogChannel` responsible for logging at the given severity.
:param: severity The `LogSeverity` level of the `LogChannel` to
return.
:returns: The `LogChannel` used by `Log` to perform logging at the given
severity; will be `nil` if `Log` is not configured to
perform logging at that severity.
*/
public static func channelForSeverity(severity: LogSeverity)
-> LogChannel?
{
switch severity {
case .Verbose: return _verbose
case .Debug: return _debug
case .Info: return _info
case .Warning: return _warning
case .Error: return _error
}
}
/**
Writes program execution trace information to the log using the specified
severity. This information includes the signature of the calling function,
as well as the source file and line at which the call to `trace()` was
issued.
:param: severity The `LogSeverity` for the message being recorded.
:param: function The default value provided for this parameter captures
the signature of the calling function. **You should not provide
a value for this parameter.**
:param: filePath The default value provided for this parameter captures
the file path of the code issuing the call to this function.
**You should not provide a value for this parameter.**
:param: fileLine The default value provided for this parameter captures
the line number issuing the call to this function. **You should
not provide a value for this parameter.**
*/
public static func trace(severity: LogSeverity, function: String = __FUNCTION__, filePath: String = __FILE__, fileLine: Int = __LINE__)
{
channelForSeverity(severity)?.trace(function, filePath: filePath, fileLine: fileLine)
}
/**
Writes a string-based message to the log using the specified severity.
:param: severity The `LogSeverity` for the message being recorded.
:param: msg The message to log.
:param: function The default value provided for this parameter captures
the signature of the calling function. **You should not provide
a value for this parameter.**
:param: filePath The default value provided for this parameter captures
the file path of the code issuing the call to this function.
**You should not provide a value for this parameter.**
:param: fileLine The default value provided for this parameter captures
the line number issuing the call to this function. **You should
not provide a value for this parameter.**
*/
public static func message(severity: LogSeverity, message: String, function: String = __FUNCTION__, filePath: String = __FILE__, fileLine: Int = __LINE__)
{
channelForSeverity(severity)?.message(message, function: function, filePath: filePath, fileLine: fileLine)
}
/**
Writes an arbitrary value to the log using the specified severity.
:param: severity The `LogSeverity` for the message being recorded.
:param: value The value to write to the log. The underlying logging
implementation is responsible for converting `value` into a
text representation. If that is not possible, the log request
may be silently ignored.
:param: function The default value provided for this parameter captures
the signature of the calling function. **You should not provide
a value for this parameter.**
:param: filePath The default value provided for this parameter captures
the file path of the code issuing the call to this function.
**You should not provide a value for this parameter.**
:param: fileLine The default value provided for this parameter captures
the line number issuing the call to this function. **You should
not provide a value for this parameter.**
*/
public static func value(severity: LogSeverity, value: Any?, function: String = __FUNCTION__, filePath: String = __FILE__, fileLine: Int = __LINE__)
{
channelForSeverity(severity)?.value(value, function: function, filePath: filePath, fileLine: fileLine)
}
private static func createLogChannelWithSeverity(severity: LogSeverity, receptacle: LogReceptacle, minimumSeverity: LogSeverity)
-> LogChannel?
{
if severity >= minimumSeverity {
return LogChannel(severity: severity, receptacle: receptacle)
}
return nil
}
}
|
mit
|
b23a2ec482d1e5ddec4165feaee912f7
| 40.945946 | 180 | 0.681415 | 4.91831 | false | true | false | false |
Nihility-Ming/Design_Patterns_In_Objective-C
|
创建型模式/简单工厂模式/Example_02/SimpleFactory/OperationFactory.swift
|
1
|
598
|
//
// OperationFactory.swift
// SimpleFactory
//
// Created by Bi Weiming on 15/5/14.
// Copyright (c) 2015年 Bi Weiming. All rights reserved.
//
import Foundation
class OperationFactory {
static func createOperate(str:String) -> Operation? {
var oper:Operation? = nil
switch str {
case "+":
oper = OperationAdd()
case "-":
oper = OperationSub()
case "*":
oper = OperationMul()
case "/":
oper = OperationDiv()
default:
break
}
return oper
}
}
|
apache-2.0
|
d3d560bfc702c6756c6ba1dfd619fa49
| 19.586207 | 57 | 0.516779 | 4.414815 | false | false | false | false |
dsay/POPDataSource
|
DataSources/DataSource/Extensions.swift
|
1
|
3007
|
import UIKit
public protocol ReuseIdentifier {
static var identifier: String { get }
}
public extension ReuseIdentifier where Self: UIView {
static var identifier: String {
let type = String(describing: self)
return type
}
}
public extension UITableView {
func register<T: ReuseIdentifier>(_ headerFooterView: T.Type) {
let identifier = headerFooterView.identifier
self.register(UINib(nibName: identifier , bundle: nil), forHeaderFooterViewReuseIdentifier: identifier)
}
func register<T: ReuseIdentifier>(cell: T.Type) {
let identifier = cell.identifier
self.register(UINib(nibName: identifier , bundle: nil), forCellReuseIdentifier: identifier)
}
}
public class EmptyView : UIView, ReuseIdentifier {
}
public class ActionHandleButton : UIButton {
var action :(() -> Void)?
func triggerActionHandleBlock() {
self.action?()
}
func actionHandle(_ control :UIControlEvents, ForAction action:@escaping () -> Void) {
self.action = action
self.addTarget(self, action: #selector(ActionHandleButton.triggerActionHandleBlock), for: control)
}
}
public extension UITableView {
func collapse<T: Collapsible>(_ dataSource: T, at section: Int = 0) {
let indexPaths = (0..<dataSource.numberOfItems()).map {
IndexPath(row: $0, section: section)
}
dataSource.open = false
self.deleteRows(at: indexPaths, with: .fade)
}
func expand<T: Collapsible>(_ dataSource: T, at section: Int = 0) {
let indexPaths = (0..<dataSource.numberOfItems()).map {
IndexPath(row: $0, section: section)
}
dataSource.open = true
self.insertRows(at: indexPaths, with: .fade)
}
}
public extension UITableView {
func animationReload() {
self.reloadData()
}
func animationCell() {
self.reloadData()
let cells = self.visibleCells
let tableHeight: CGFloat = self.bounds.size.height
for i in cells {
let cell: UITableViewCell = i as UITableViewCell
cell.transform = CGAffineTransform(translationX: 0, y:tableHeight)
}
var index = 0
for a in cells {
let cell: UITableViewCell = a as UITableViewCell
UIView.animate(withDuration: 1.5, delay: 0.05 * Double(index), usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: [], animations: {
cell.transform = CGAffineTransform(translationX: 0, y:0)
}, completion: { animation in
})
index += 1
}
}
func show(_ emptyView: UIView) {
if self.backgroundView != emptyView {
self.backgroundView = emptyView
}
}
func hideEmptyView() {
self.backgroundView = nil
}
}
|
mit
|
f488e1d5143d4c8b0dcf35f0479f66bc
| 26.09009 | 156 | 0.593947 | 4.905383 | false | false | false | false |
huonw/swift
|
test/ClangImporter/enum.swift
|
5
|
8100
|
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck %s -verify
// RUN: not %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck %s 2>&1 | %FileCheck %s
// -- Check that we can successfully round-trip.
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -D IRGEN -emit-ir -primary-file %s | %FileCheck -check-prefix=CHECK-IR %s
// REQUIRES: objc_interop
// At one point we diagnosed enum case aliases that referred to unavailable
// cases in their (synthesized) implementation.
// CHECK-NOT: unknown
import Foundation
import user_objc
import enums_using_attributes
// NS_ENUM
var mince = NSRuncingMode.mince
var quince = NSRuncingMode.quince
var rawMince: UInt = NSRuncingMode.mince.rawValue
var rawFoo: CInt = NSUnderlyingType.foo.rawValue
var rawNegativeOne: CUnsignedInt
= NSUnsignedUnderlyingTypeNegativeValue.negativeOne.rawValue
var rawWordBreakA: Int = NSPrefixWordBreak.banjo.rawValue
var rawWordBreakB: Int = NSPrefixWordBreak.bandana.rawValue
var rawWordBreak2A: Int = NSPrefixWordBreak2.breakBarBas.rawValue
var rawWordBreak2B: Int = NSPrefixWordBreak2.breakBareBass.rawValue
var rawWordBreak3A: Int = NSPrefixWordBreak3.break1Bob.rawValue
var rawWordBreak3B: Int = NSPrefixWordBreak3.break1Ben.rawValue
var singleConstant = NSSingleConstantEnum.value
var myCoolWaterMelon = MyCoolEnum.waterMelon
var hashMince: Int = NSRuncingMode.mince.hashValue
if NSRuncingMode.mince != .quince { }
var numberBehavior: NumberFormatter.Behavior = .default
numberBehavior = .behavior10_4
var postingStyle: NotificationQueue.PostingStyle = .whenIdle
postingStyle = .asap
func handler(_ formatter: ByteCountFormatter) {
// Ensure that the Equality protocol is properly added to an
// imported ObjC enum type before the type is referenced by name
if (formatter.countStyle == .file) {}
}
// Unfortunate consequence of treating runs of capitals as a single word.
// See <rdar://problem/16768954>.
var pathStyle: CFURLPathStyle = .cfurlposixPathStyle
pathStyle = .cfurlWindowsPathStyle
var URLOrUTI: CFURLOrUTI = .cfurlKind
URLOrUTI = .cfutiKind
let magnitude: Magnitude = .k2
let magnitude2: MagnitudeWords = .two
let objcABI: objc_abi = .v2
let underscoreSuffix: ALL_CAPS_ENUM = .ENUM_CASE_ONE
let underscoreSuffix2: ALL_CAPS_ENUM2 = .CASE_TWO
var alias1 = NSAliasesEnum.bySameValue
var alias2 = NSAliasesEnum.byEquivalentValue
var alias3 = NSAliasesEnum.byName
var aliasOriginal = NSAliasesEnum.original
switch aliasOriginal {
case .original:
break
case .differentValue:
break
}
switch aliasOriginal {
case .original:
break
default:
break
}
switch aliasOriginal {
case .bySameValue:
break
case .differentValue:
break
default:
break
}
switch aliasOriginal {
case .bySameValue:
break
default:
break
}
switch aliasOriginal {
case NSAliasesEnum.bySameValue:
break
case NSAliasesEnum.differentValue:
break
default:
break
}
extension NSAliasesEnum {
func test() {
switch aliasOriginal {
case .bySameValue:
break
case .differentValue:
break
default:
break
}
}
}
#if !IRGEN
_ = NSUnavailableAliasesEnum.originalAU
_ = NSUnavailableAliasesEnum.aliasAU // expected-error {{'aliasAU' is unavailable}}
_ = NSUnavailableAliasesEnum.originalUA // expected-error {{'originalUA' is unavailable}}
_ = NSUnavailableAliasesEnum.aliasUA
_ = NSUnavailableAliasesEnum.originalUU // expected-error {{'originalUU' is unavailable}}
_ = NSUnavailableAliasesEnum.aliasUU // expected-error {{'aliasUU' is unavailable}}
#endif
// Test NS_SWIFT_NAME:
_ = XMLNode.Kind.DTDKind == .invalid
_ = NSPrefixWordBreakCustom.problemCase == .deprecatedGoodCase // expected-warning {{deprecated}}
_ = NSPrefixWordBreak2Custom.problemCase == .goodCase
_ = NSPrefixWordBreak2Custom.problemCase == .PrefixWordBreak2DeprecatedBadCase // expected-warning {{deprecated}}
_ = NSPrefixWordBreak2Custom.problemCase == .deprecatedGoodCase // expected-warning {{deprecated}}
_ = NSPrefixWordBreakReversedCustom.problemCase == .deprecatedGoodCase // expected-warning {{deprecated}}
_ = NSPrefixWordBreakReorderedCustom.problemCase == .goodCase
_ = NSPrefixWordBreakReorderedCustom.problemCase == .PrefixWordBreakReorderedDeprecatedBadCase // expected-warning {{deprecated}}
_ = NSPrefixWordBreakReorderedCustom.problemCase == .deprecatedGoodCase // expected-warning {{deprecated}}
_ = NSPrefixWordBreakReordered2Custom.problemCase == .goodCase
_ = NSPrefixWordBreakReordered2Custom.problemCase == .PrefixWordBreakReordered2DeprecatedBadCase // expected-warning {{deprecated}}
_ = NSPrefixWordBreakReordered2Custom.problemCase == .deprecatedGoodCase // expected-warning {{deprecated}}
_ = NSSwiftNameAllTheThings.Foo == .Bar
_ = NSSwiftNameBad.`class`
#if !IRGEN
var qualifiedName = NSRuncingMode.mince
var topLevelCaseName = RuncingMince // expected-error{{}}
#endif
let _: EnumViaAttribute = .first
let _: CFEnumWithAttr = .first
// NS_OPTIONS
var withMince: NSRuncingOptions = .enableMince
var withQuince: NSRuncingOptions = .enableQuince
// When there is a single enum constant, compare it against the type name to
// derive the namespaced name.
var singleValue: NSSingleOptions = .value
// Check OptionSet conformance.
var minceAndQuince: NSRuncingOptions = NSRuncingOptions.enableMince.intersection(NSRuncingOptions.enableQuince)
var minceOrQuince: NSRuncingOptions = [.enableMince, .enableQuince]
minceOrQuince.formIntersection(minceAndQuince)
minceOrQuince.formUnion(minceAndQuince)
var minceValue: UInt = minceAndQuince.rawValue
var minceFromMask: NSRuncingOptions = []
// Strip leading 'k' in "kConstant".
let calendarUnit: CFCalendarUnit = [.year, .weekday]
// ...unless the next character is a non-identifier.
let curve3D: AU3DMixerAttenuationCurve = .k3DMixerAttenuationCurve_Exponential
// Match various plurals.
let observingOpts: NSKeyValueObservingOptions = [.new, .old]
let bluetoothProps: CBCharacteristicProperties = [.write, .writeWithoutResponse]
let buzzFilter: AlertBuzzes = [.funk, .sosumi]
// Match multi-capital acronym.
let bitmapFormat: NSBitmapFormat = [.NSAlphaFirstBitmapFormat, .NS32BitBigEndianBitmapFormat];
let bitmapFormatR: NSBitmapFormatReversed = [.NSAlphaFirstBitmapFormatR, .NS32BitBigEndianBitmapFormatR];
let bitmapFormat2: NSBitmapFormat2 = [.NSU16a , .NSU32a]
let bitmapFormat3: NSBitmapFormat3 = [.NSU16b , .NSS32b]
let bitmapFormat4: NSUBitmapFormat4 = [.NSU16c , .NSU32c]
let bitmapFormat5: NSABitmapFormat5 = [.NSAA16d , .NSAB32d]
// Drop trailing underscores when possible.
let timeFlags: CMTimeFlags = [.valid , .hasBeenRounded]
let timeFlags2: CMTimeFlagsWithNumber = [._Valid, ._888]
let audioComponentOpts: AudioComponentInstantiationOptions = [.loadOutOfProcess]
let audioComponentFlags: AudioComponentFlags = [.sandboxSafe]
let audioComponentFlags2: FakeAudioComponentFlags = [.loadOutOfProcess]
let objcFlags: objc_flags = [.taggedPointer, .swiftRefcount]
let optionsWithSwiftName: NSOptionsAlsoGetSwiftName = .Case
let optionsViaAttribute: OptionsViaAttribute = [.first, .second]
let optionsViaAttribute2: CFOptionsWithAttr = [.first]
// <rdar://problem/25168818> Don't import None members in NS_OPTIONS types
#if !IRGEN
let _ = NSRuncingOptions.none // expected-error {{'none' is unavailable: use [] to construct an empty option set}}
#endif
// ...but do if they have a custom name
_ = EmptySet1.default
// ...even if the custom name is the same as the name they would have had
_ = EmptySet2.none
// ...or the original name.
_ = EmptySet3.None
// Just use this type, making sure that its case alias doesn't cause problems.
// rdar://problem/30401506
_ = EnumWithAwkwardDeprecations.normalCase1
#if !IRGEN
let _: UnknownEnumThanksToAPINotes = .first // expected-error {{has no member 'first'}}
let _: UnknownOptionsThanksToAPINotes = .first // expected-error {{has no member 'first'}}
#endif
let _ = UnknownEnumThanksToAPINotesFirst
let _ = UnknownOptionsThanksToAPINotesFirst
// CHECK-IR: $S4enum12testMangling2e12e22e3ySo9EnumByTagV_So0gH7TypedefaSo0gH4BothVtF
func testMangling(e1: EnumByTag, e2: EnumByTypedef, e3: EnumByBoth) {}
|
apache-2.0
|
3a2fd5c42c8b7d621bb65ef5a8ab06b4
| 33.913793 | 135 | 0.780864 | 3.630659 | false | false | false | false |
konanxu/WeiBoWithSwift
|
WeiBo/WeiBo/Classes/Main/BaseTableViewController.swift
|
1
|
3995
|
//
// BaseTableViewController.swift
// WeiBo
//
// Created by Konan on 16/3/9.
// Copyright © 2016年 Konan. All rights reserved.
//
import UIKit
class BaseTableViewController: UITableViewController {
var userLogin = UserAccount.loadAccount() != nil ? true :false
var vistorView: VistorView?
override func loadView() {
userLogin ? super.loadView() : setupVistorView()
}
private func setupVistorView(){
let customview = VistorView()
customview.backgroundColor = UIColor.whiteColor()
view = customview
view.backgroundColor = UIColor(colorLiteralRed: 237/255.0, green: 237/255.0, blue: 237/255.0, alpha: 1)
vistorView = customview
vistorView?.delegate = self
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: UIBarButtonItemStyle.Plain, target: self, action: "vistorViewRegisterClick")
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "登录", style: UIBarButtonItemStyle.Plain, target: self, action: "vistorViewLoginClick")
}
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
extension BaseTableViewController:vistorViewDelegate{
func vistorViewRegisterClick() {
print("hello")
let account = UserAccount.loadAccount()
print(account)
}
func vistorViewLoginClick() {
print("fuck")
let vc = UINavigationController(rootViewController: OAuthViewController())
presentViewController(vc, animated: true, completion: nil)
}
}
|
mit
|
2495d72b3e233b4a12400b071b5ecc16
| 33.643478 | 157 | 0.677209 | 5.427793 | false | false | false | false |
nodes-ios/NStack
|
NStackSDK/NStackSDKTests/Translations/TranslationsRepositoryMock.swift
|
1
|
1990
|
//
// TranslationsRepositoryMock.swift
// NStackSDK
//
// Created by Dominik Hádl on 05/12/2016.
// Copyright © 2016 Nodes ApS. All rights reserved.
//
import Foundation
import Alamofire
@testable import NStackSDK
class TranslationsRepositoryMock: TranslationsRepository {
var translationsResponse: TranslationsResponse?
var availableLanguages: [Language]?
var currentLanguage: Language?
var preferredLanguages = ["en"]
var customBundles: [Bundle]?
func fetchTranslations(acceptLanguage: String, completion: @escaping ((DataResponse<TranslationsResponse>) -> Void)) {
let error = NSError(domain: "", code: 0, userInfo: nil)
let result: Result = translationsResponse != nil ? .success(translationsResponse!) : .failure(error)
let response = DataResponse(request: nil, response: nil, data: nil, result: result)
completion(response)
}
func fetchAvailableLanguages(completion: @escaping ((DataResponse<[Language]>) -> Void)) {
let error = NSError(domain: "", code: 0, userInfo: nil)
let result: Result = availableLanguages != nil ? .success(availableLanguages!) : .failure(error)
let response = DataResponse(request: nil, response: nil, data: nil, result: result)
completion(response)
}
func fetchCurrentLanguage(acceptLanguage: String, completion: @escaping ((DataResponse<Language>) -> Void)) {
let error = NSError(domain: "", code: 0, userInfo: nil)
let result: Result = currentLanguage != nil ? .success(currentLanguage!) : .failure(error)
let response = DataResponse(request: nil, response: nil, data: nil, result: result)
completion(response)
}
func fetchPreferredLanguages() -> [String] {
return preferredLanguages
}
func fetchBundles() -> [Bundle] {
return customBundles ?? Bundle.allBundles
}
func fetchCurrentPhoneLanguage() -> String? {
return preferredLanguages.first
}
}
|
mit
|
594fa59f65928e7def85989aedca8491
| 36.509434 | 122 | 0.682596 | 4.591224 | false | false | false | false |
zhenghuadong11/firstGitHub
|
旅游app_useSwift/旅游app_useSwift/Source/ConstraintDescription.swift
|
22
|
28118
|
//
// SnapKit
//
// Copyright (c) 2011-2015 SnapKit Team - https://github.com/SnapKit
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
/**
Used to expose the final API of a `ConstraintDescription` which allows getting a constraint from it
*/
public protocol ConstraintDescriptionFinalizable: class {
var constraint: Constraint { get }
func labeled(label: String) -> ConstraintDescriptionFinalizable
}
/**
Used to expose priority APIs
*/
public protocol ConstraintDescriptionPriortizable: ConstraintDescriptionFinalizable {
func priority(priority: Float) -> ConstraintDescriptionFinalizable
func priority(priority: Double) -> ConstraintDescriptionFinalizable
func priority(priority: CGFloat) -> ConstraintDescriptionFinalizable
func priority(priority: UInt) -> ConstraintDescriptionFinalizable
func priority(priority: Int) -> ConstraintDescriptionFinalizable
func priorityRequired() -> ConstraintDescriptionFinalizable
func priorityHigh() -> ConstraintDescriptionFinalizable
func priorityMedium() -> ConstraintDescriptionFinalizable
func priorityLow() -> ConstraintDescriptionFinalizable
}
/**
Used to expose multiplier & constant APIs
*/
public protocol ConstraintDescriptionEditable: ConstraintDescriptionPriortizable {
func multipliedBy(amount: Float) -> ConstraintDescriptionEditable
func multipliedBy(amount: Double) -> ConstraintDescriptionEditable
func multipliedBy(amount: CGFloat) -> ConstraintDescriptionEditable
func multipliedBy(amount: Int) -> ConstraintDescriptionEditable
func multipliedBy(amount: UInt) -> ConstraintDescriptionEditable
func dividedBy(amount: Float) -> ConstraintDescriptionEditable
func dividedBy(amount: Double) -> ConstraintDescriptionEditable
func dividedBy(amount: CGFloat) -> ConstraintDescriptionEditable
func dividedBy(amount: Int) -> ConstraintDescriptionEditable
func dividedBy(amount: UInt) -> ConstraintDescriptionEditable
func offset(amount: Float) -> ConstraintDescriptionEditable
func offset(amount: Double) -> ConstraintDescriptionEditable
func offset(amount: CGFloat) -> ConstraintDescriptionEditable
func offset(amount: Int) -> ConstraintDescriptionEditable
func offset(amount: UInt) -> ConstraintDescriptionEditable
func offset(amount: CGPoint) -> ConstraintDescriptionEditable
func offset(amount: CGSize) -> ConstraintDescriptionEditable
func offset(amount: EdgeInsets) -> ConstraintDescriptionEditable
func inset(amount: Float) -> ConstraintDescriptionEditable
func inset(amount: Double) -> ConstraintDescriptionEditable
func inset(amount: CGFloat) -> ConstraintDescriptionEditable
func inset(amount: Int) -> ConstraintDescriptionEditable
func inset(amount: UInt) -> ConstraintDescriptionEditable
func inset(amount: EdgeInsets) -> ConstraintDescriptionEditable
}
/**
Used to expose relation APIs
*/
public protocol ConstraintDescriptionRelatable: class {
func equalTo(other: ConstraintItem) -> ConstraintDescriptionEditable
func equalTo(other: View) -> ConstraintDescriptionEditable
@available(iOS 7.0, *)
func equalTo(other: LayoutSupport) -> ConstraintDescriptionEditable
@available(iOS 9.0, OSX 10.11, *)
func equalTo(other: NSLayoutAnchor) -> ConstraintDescriptionEditable
func equalTo(other: Float) -> ConstraintDescriptionEditable
func equalTo(other: Double) -> ConstraintDescriptionEditable
func equalTo(other: CGFloat) -> ConstraintDescriptionEditable
func equalTo(other: Int) -> ConstraintDescriptionEditable
func equalTo(other: UInt) -> ConstraintDescriptionEditable
func equalTo(other: CGSize) -> ConstraintDescriptionEditable
func equalTo(other: CGPoint) -> ConstraintDescriptionEditable
func equalTo(other: EdgeInsets) -> ConstraintDescriptionEditable
func lessThanOrEqualTo(other: ConstraintItem) -> ConstraintDescriptionEditable
func lessThanOrEqualTo(other: View) -> ConstraintDescriptionEditable
@available(iOS 7.0, *)
func lessThanOrEqualTo(other: LayoutSupport) -> ConstraintDescriptionEditable
@available(iOS 9.0, OSX 10.11, *)
func lessThanOrEqualTo(other: NSLayoutAnchor) -> ConstraintDescriptionEditable
func lessThanOrEqualTo(other: Float) -> ConstraintDescriptionEditable
func lessThanOrEqualTo(other: Double) -> ConstraintDescriptionEditable
func lessThanOrEqualTo(other: CGFloat) -> ConstraintDescriptionEditable
func lessThanOrEqualTo(other: Int) -> ConstraintDescriptionEditable
func lessThanOrEqualTo(other: UInt) -> ConstraintDescriptionEditable
func lessThanOrEqualTo(other: CGSize) -> ConstraintDescriptionEditable
func lessThanOrEqualTo(other: CGPoint) -> ConstraintDescriptionEditable
func lessThanOrEqualTo(other: EdgeInsets) -> ConstraintDescriptionEditable
func greaterThanOrEqualTo(other: ConstraintItem) -> ConstraintDescriptionEditable
func greaterThanOrEqualTo(other: View) -> ConstraintDescriptionEditable
@available(iOS 7.0, *)
func greaterThanOrEqualTo(other: LayoutSupport) -> ConstraintDescriptionEditable
@available(iOS 9.0, OSX 10.11, *)
func greaterThanOrEqualTo(other: NSLayoutAnchor) -> ConstraintDescriptionEditable
func greaterThanOrEqualTo(other: Float) -> ConstraintDescriptionEditable
func greaterThanOrEqualTo(other: Double) -> ConstraintDescriptionEditable
func greaterThanOrEqualTo(other: CGFloat) -> ConstraintDescriptionEditable
func greaterThanOrEqualTo(other: Int) -> ConstraintDescriptionEditable
func greaterThanOrEqualTo(other: UInt) -> ConstraintDescriptionEditable
func greaterThanOrEqualTo(other: CGSize) -> ConstraintDescriptionEditable
func greaterThanOrEqualTo(other: CGPoint) -> ConstraintDescriptionEditable
func greaterThanOrEqualTo(other: EdgeInsets) -> ConstraintDescriptionEditable
}
/**
Used to expose chaining APIs
*/
public protocol ConstraintDescriptionExtendable: ConstraintDescriptionRelatable {
var left: ConstraintDescriptionExtendable { get }
var top: ConstraintDescriptionExtendable { get }
var bottom: ConstraintDescriptionExtendable { get }
var right: ConstraintDescriptionExtendable { get }
var leading: ConstraintDescriptionExtendable { get }
var trailing: ConstraintDescriptionExtendable { get }
var width: ConstraintDescriptionExtendable { get }
var height: ConstraintDescriptionExtendable { get }
var centerX: ConstraintDescriptionExtendable { get }
var centerY: ConstraintDescriptionExtendable { get }
var baseline: ConstraintDescriptionExtendable { get }
@available(iOS 8.0, *)
var firstBaseline: ConstraintDescriptionExtendable { get }
@available(iOS 8.0, *)
var leftMargin: ConstraintDescriptionExtendable { get }
@available(iOS 8.0, *)
var rightMargin: ConstraintDescriptionExtendable { get }
@available(iOS 8.0, *)
var topMargin: ConstraintDescriptionExtendable { get }
@available(iOS 8.0, *)
var bottomMargin: ConstraintDescriptionExtendable { get }
@available(iOS 8.0, *)
var leadingMargin: ConstraintDescriptionExtendable { get }
@available(iOS 8.0, *)
var trailingMargin: ConstraintDescriptionExtendable { get }
@available(iOS 8.0, *)
var centerXWithinMargins: ConstraintDescriptionExtendable { get }
@available(iOS 8.0, *)
var centerYWithinMargins: ConstraintDescriptionExtendable { get }
}
/**
Used to internally manage building constraint
*/
internal class ConstraintDescription: ConstraintDescriptionExtendable, ConstraintDescriptionEditable, ConstraintDescriptionFinalizable {
internal var left: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.Left) }
internal var top: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.Top) }
internal var right: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.Right) }
internal var bottom: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.Bottom) }
internal var leading: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.Leading) }
internal var trailing: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.Trailing) }
internal var width: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.Width) }
internal var height: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.Height) }
internal var centerX: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.CenterX) }
internal var centerY: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.CenterY) }
internal var baseline: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.Baseline) }
internal var label: String?
@available(iOS 8.0, *)
internal var firstBaseline: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.FirstBaseline) }
@available(iOS 8.0, *)
internal var leftMargin: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.LeftMargin) }
@available(iOS 8.0, *)
internal var rightMargin: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.RightMargin) }
@available(iOS 8.0, *)
internal var topMargin: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.TopMargin) }
@available(iOS 8.0, *)
internal var bottomMargin: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.BottomMargin) }
@available(iOS 8.0, *)
internal var leadingMargin: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.LeadingMargin) }
@available(iOS 8.0, *)
internal var trailingMargin: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.TrailingMargin) }
@available(iOS 8.0, *)
internal var centerXWithinMargins: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.CenterXWithinMargins) }
@available(iOS 8.0, *)
internal var centerYWithinMargins: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.CenterYWithinMargins) }
// MARK: initializer
init(fromItem: ConstraintItem) {
self.fromItem = fromItem
self.toItem = ConstraintItem(object: nil, attributes: ConstraintAttributes.None)
}
// MARK: equalTo
internal func equalTo(other: ConstraintItem) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .Equal)
}
internal func equalTo(other: View) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .Equal)
}
@available(iOS 7.0, *)
internal func equalTo(other: LayoutSupport) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .Equal)
}
@available(iOS 9.0, OSX 10.11, *)
internal func equalTo(other: NSLayoutAnchor) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .Equal)
}
internal func equalTo(other: Float) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .Equal)
}
internal func equalTo(other: Double) -> ConstraintDescriptionEditable {
return self.constrainTo(Float(other), relation: .Equal)
}
internal func equalTo(other: CGFloat) -> ConstraintDescriptionEditable {
return self.constrainTo(Float(other), relation: .Equal)
}
internal func equalTo(other: Int) -> ConstraintDescriptionEditable {
return self.constrainTo(Float(other), relation: .Equal)
}
internal func equalTo(other: UInt) -> ConstraintDescriptionEditable {
return self.constrainTo(Float(other), relation: .Equal)
}
internal func equalTo(other: CGSize) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .Equal)
}
internal func equalTo(other: CGPoint) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .Equal)
}
internal func equalTo(other: EdgeInsets) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .Equal)
}
// MARK: lessThanOrEqualTo
internal func lessThanOrEqualTo(other: ConstraintItem) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .LessThanOrEqualTo)
}
internal func lessThanOrEqualTo(other: View) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .LessThanOrEqualTo)
}
@available(iOS 7.0, *)
internal func lessThanOrEqualTo(other: LayoutSupport) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .LessThanOrEqualTo)
}
@available(iOS 9.0, OSX 10.11, *)
internal func lessThanOrEqualTo(other: NSLayoutAnchor) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .LessThanOrEqualTo)
}
internal func lessThanOrEqualTo(other: Float) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .LessThanOrEqualTo)
}
internal func lessThanOrEqualTo(other: Double) -> ConstraintDescriptionEditable {
return self.constrainTo(Float(other), relation: .LessThanOrEqualTo)
}
internal func lessThanOrEqualTo(other: CGFloat) -> ConstraintDescriptionEditable {
return self.constrainTo(Float(other), relation: .LessThanOrEqualTo)
}
internal func lessThanOrEqualTo(other: Int) -> ConstraintDescriptionEditable {
return self.constrainTo(Float(other), relation: .LessThanOrEqualTo)
}
internal func lessThanOrEqualTo(other: UInt) -> ConstraintDescriptionEditable {
return self.constrainTo(Float(other), relation: .LessThanOrEqualTo)
}
internal func lessThanOrEqualTo(other: CGSize) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .LessThanOrEqualTo)
}
internal func lessThanOrEqualTo(other: CGPoint) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .LessThanOrEqualTo)
}
internal func lessThanOrEqualTo(other: EdgeInsets) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .LessThanOrEqualTo)
}
// MARK: greaterThanOrEqualTo
internal func greaterThanOrEqualTo(other: ConstraintItem) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .GreaterThanOrEqualTo)
}
internal func greaterThanOrEqualTo(other: View) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .GreaterThanOrEqualTo)
}
@available(iOS 7.0, *)
internal func greaterThanOrEqualTo(other: LayoutSupport) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .GreaterThanOrEqualTo)
}
@available(iOS 9.0, OSX 10.11, *)
internal func greaterThanOrEqualTo(other: NSLayoutAnchor) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .LessThanOrEqualTo)
}
internal func greaterThanOrEqualTo(other: Float) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .GreaterThanOrEqualTo)
}
internal func greaterThanOrEqualTo(other: Double) -> ConstraintDescriptionEditable {
return self.constrainTo(Float(other), relation: .GreaterThanOrEqualTo)
}
internal func greaterThanOrEqualTo(other: CGFloat) -> ConstraintDescriptionEditable {
return self.constrainTo(Float(other), relation: .GreaterThanOrEqualTo)
}
internal func greaterThanOrEqualTo(other: Int) -> ConstraintDescriptionEditable {
return self.constrainTo(Float(other), relation: .GreaterThanOrEqualTo)
}
internal func greaterThanOrEqualTo(other: UInt) -> ConstraintDescriptionEditable {
return self.constrainTo(Float(other), relation: .GreaterThanOrEqualTo)
}
internal func greaterThanOrEqualTo(other: CGSize) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .GreaterThanOrEqualTo)
}
internal func greaterThanOrEqualTo(other: CGPoint) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .GreaterThanOrEqualTo)
}
internal func greaterThanOrEqualTo(other: EdgeInsets) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .GreaterThanOrEqualTo)
}
// MARK: multiplier
internal func multipliedBy(amount: Float) -> ConstraintDescriptionEditable {
self.multiplier = amount
return self
}
internal func multipliedBy(amount: Double) -> ConstraintDescriptionEditable {
return self.multipliedBy(Float(amount))
}
internal func multipliedBy(amount: CGFloat) -> ConstraintDescriptionEditable {
return self.multipliedBy(Float(amount))
}
internal func multipliedBy(amount: Int) -> ConstraintDescriptionEditable {
return self.multipliedBy(Float(amount))
}
internal func multipliedBy(amount: UInt) -> ConstraintDescriptionEditable {
return self.multipliedBy(Float(amount))
}
internal func dividedBy(amount: Float) -> ConstraintDescriptionEditable {
self.multiplier = 1.0 / amount;
return self
}
internal func dividedBy(amount: Double) -> ConstraintDescriptionEditable {
return self.dividedBy(Float(amount))
}
internal func dividedBy(amount: CGFloat) -> ConstraintDescriptionEditable {
return self.dividedBy(Float(amount))
}
internal func dividedBy(amount: Int) -> ConstraintDescriptionEditable {
return self.dividedBy(Float(amount))
}
internal func dividedBy(amount: UInt) -> ConstraintDescriptionEditable {
return self.dividedBy(Float(amount))
}
// MARK: offset
internal func offset(amount: Float) -> ConstraintDescriptionEditable {
self.constant = amount
return self
}
internal func offset(amount: Double) -> ConstraintDescriptionEditable {
return self.offset(Float(amount))
}
internal func offset(amount: CGFloat) -> ConstraintDescriptionEditable {
return self.offset(Float(amount))
}
internal func offset(amount: Int) -> ConstraintDescriptionEditable {
return self.offset(Float(amount))
}
internal func offset(amount: UInt) -> ConstraintDescriptionEditable {
return self.offset(Float(amount))
}
internal func offset(amount: CGPoint) -> ConstraintDescriptionEditable {
self.constant = amount
return self
}
internal func offset(amount: CGSize) -> ConstraintDescriptionEditable {
self.constant = amount
return self
}
internal func offset(amount: EdgeInsets) -> ConstraintDescriptionEditable {
self.constant = amount
return self
}
// MARK: inset
internal func inset(amount: Float) -> ConstraintDescriptionEditable {
let value = CGFloat(amount)
self.constant = EdgeInsets(top: value, left: value, bottom: -value, right: -value)
return self
}
internal func inset(amount: Double) -> ConstraintDescriptionEditable {
let value = CGFloat(amount)
self.constant = EdgeInsets(top: value, left: value, bottom: -value, right: -value)
return self
}
internal func inset(amount: CGFloat) -> ConstraintDescriptionEditable {
self.constant = EdgeInsets(top: amount, left: amount, bottom: -amount, right: -amount)
return self
}
internal func inset(amount: Int) -> ConstraintDescriptionEditable {
let value = CGFloat(amount)
self.constant = EdgeInsets(top: value, left: value, bottom: -value, right: -value)
return self
}
internal func inset(amount: UInt) -> ConstraintDescriptionEditable {
let value = CGFloat(amount)
self.constant = EdgeInsets(top: value, left: value, bottom: -value, right: -value)
return self
}
internal func inset(amount: EdgeInsets) -> ConstraintDescriptionEditable {
self.constant = EdgeInsets(top: amount.top, left: amount.left, bottom: -amount.bottom, right: -amount.right)
return self
}
// MARK: priority
internal func priority(priority: Float) -> ConstraintDescriptionFinalizable {
self.priority = priority
return self
}
internal func priority(priority: Double) -> ConstraintDescriptionFinalizable {
return self.priority(Float(priority))
}
internal func priority(priority: CGFloat) -> ConstraintDescriptionFinalizable {
return self.priority(Float(priority))
}
func priority(priority: UInt) -> ConstraintDescriptionFinalizable {
return self.priority(Float(priority))
}
internal func priority(priority: Int) -> ConstraintDescriptionFinalizable {
return self.priority(Float(priority))
}
internal func priorityRequired() -> ConstraintDescriptionFinalizable {
return self.priority(1000.0)
}
internal func priorityHigh() -> ConstraintDescriptionFinalizable {
return self.priority(750.0)
}
internal func priorityMedium() -> ConstraintDescriptionFinalizable {
#if os(iOS) || os(tvOS)
return self.priority(500.0)
#else
return self.priority(501.0)
#endif
}
internal func priorityLow() -> ConstraintDescriptionFinalizable {
return self.priority(250.0)
}
// MARK: Constraint
internal var constraint: Constraint {
if self.concreteConstraint == nil {
if self.relation == nil {
fatalError("Attempting to create a constraint from a ConstraintDescription before it has been fully chained.")
}
self.concreteConstraint = ConcreteConstraint(
fromItem: self.fromItem,
toItem: self.toItem,
relation: self.relation!,
constant: self.constant,
multiplier: self.multiplier,
priority: self.priority,
label: self.label)
}
return self.concreteConstraint!
}
func labeled(label: String) -> ConstraintDescriptionFinalizable {
self.label = label
return self
}
// MARK: Private
private let fromItem: ConstraintItem
private var toItem: ConstraintItem {
willSet {
if self.concreteConstraint != nil {
fatalError("Attempting to modify a ConstraintDescription after its constraint has been created.")
}
}
}
private var relation: ConstraintRelation? {
willSet {
if self.concreteConstraint != nil {
fatalError("Attempting to modify a ConstraintDescription after its constraint has been created.")
}
}
}
private var constant: Any = Float(0.0) {
willSet {
if self.concreteConstraint != nil {
fatalError("Attempting to modify a ConstraintDescription after its constraint has been created.")
}
}
}
private var multiplier: Float = 1.0 {
willSet {
if self.concreteConstraint != nil {
fatalError("Attempting to modify a ConstraintDescription after its constraint has been created.")
}
}
}
private var priority: Float = 1000.0 {
willSet {
if self.concreteConstraint != nil {
fatalError("Attempting to modify a ConstraintDescription after its constraint has been created.")
}
}
}
private var concreteConstraint: ConcreteConstraint? = nil
private func addConstraint(attributes: ConstraintAttributes) -> ConstraintDescription {
if self.relation == nil {
self.fromItem.attributes += attributes
}
return self
}
private func constrainTo(other: ConstraintItem, relation: ConstraintRelation) -> ConstraintDescription {
if other.attributes != ConstraintAttributes.None {
let toLayoutAttributes = other.attributes.layoutAttributes
if toLayoutAttributes.count > 1 {
let fromLayoutAttributes = self.fromItem.attributes.layoutAttributes
if toLayoutAttributes != fromLayoutAttributes {
NSException(name: "Invalid Constraint", reason: "Cannot constrain to multiple non identical attributes", userInfo: nil).raise()
return self
}
other.attributes = ConstraintAttributes.None
}
}
self.toItem = other
self.relation = relation
return self
}
private func constrainTo(other: View, relation: ConstraintRelation) -> ConstraintDescription {
return constrainTo(ConstraintItem(object: other, attributes: ConstraintAttributes.None), relation: relation)
}
@available(iOS 7.0, *)
private func constrainTo(other: LayoutSupport, relation: ConstraintRelation) -> ConstraintDescription {
return constrainTo(ConstraintItem(object: other, attributes: ConstraintAttributes.None), relation: relation)
}
@available(iOS 9.0, OSX 10.11, *)
private func constrainTo(other: NSLayoutAnchor, relation: ConstraintRelation) -> ConstraintDescription {
return constrainTo(ConstraintItem(object: other, attributes: ConstraintAttributes.None), relation: relation)
}
private func constrainTo(other: Float, relation: ConstraintRelation) -> ConstraintDescription {
self.constant = other
return constrainTo(ConstraintItem(object: nil, attributes: ConstraintAttributes.None), relation: relation)
}
private func constrainTo(other: Double, relation: ConstraintRelation) -> ConstraintDescription {
self.constant = other
return constrainTo(ConstraintItem(object: nil, attributes: ConstraintAttributes.None), relation: relation)
}
private func constrainTo(other: CGSize, relation: ConstraintRelation) -> ConstraintDescription {
self.constant = other
return constrainTo(ConstraintItem(object: nil, attributes: ConstraintAttributes.None), relation: relation)
}
private func constrainTo(other: CGPoint, relation: ConstraintRelation) -> ConstraintDescription {
self.constant = other
return constrainTo(ConstraintItem(object: nil, attributes: ConstraintAttributes.None), relation: relation)
}
private func constrainTo(other: EdgeInsets, relation: ConstraintRelation) -> ConstraintDescription {
self.constant = other
return constrainTo(ConstraintItem(object: nil, attributes: ConstraintAttributes.None), relation: relation)
}
}
|
apache-2.0
|
654b1d2cdc268523589c70510a7192be
| 45.39934 | 147 | 0.722989 | 5.466174 | false | false | false | false |
comcxx11/HGAlertView
|
HGAlertView/HGAlertView.swift
|
1
|
4304
|
//
// HGAlertView.swift
// HGAlertView Example
//
// Created by HongSeojin on 7/8/15.
// Copyright (c) 2015 HongSeojin. All rights reserved.
//
/**
JTAlertView *alertView = [[JTAlertView alloc] initWithTitle:@"You are wonderful" andImage:image];
self.alertView.size = CGSizeMake(280, 230);
[self.alertView addButtonWithTitle:@"OK" style:JTAlertViewStyleDefault action:^(JTAlertView *alertView) {
[alertView hide];
}];
[self.alertView show];
*/
import UIKit
class HGAlertView: UIView {
private var backGroundView:UIView?
private var buttons:[UIButton]? = []
var backGroundColor:UIColor
class var sharedView:HGAlertView {
struct Static {
static var instance:HGAlertView?
static var token:dispatch_once_t = 0
}
dispatch_once(&Static.token) {
Static.instance = HGAlertView()
}
return Static.instance!
}
init() {
backGroundColor = UIColor.blackColor()
super.init(frame: CGRectZero)
}
required init(coder aDecoder: NSCoder) {
backGroundColor = UIColor.blackColor()
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
backGroundColor = UIColor.blackColor()
super.init(frame: frame)
}
func show(viewController:UIViewController) {
self.hide()
self.frame = viewController.view.frame
setBackground(self)
self.addButton2()
self.addButton()
viewController.view.addSubview(self)
}
func addButton() {
var btn = UIButton(frame: CGRectZero)
btn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
btn.setTitle("OK", forState: UIControlState.Normal)
self.addSubview(btn)
self.buttons?.append(btn)
self.layoutButtons()
}
func addButton2() {
var btn = UIButton(frame: CGRectZero)
btn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
btn.setTitle("Cancel", forState: UIControlState.Normal)
self.addSubview(btn)
self.buttons?.append(btn)
self.layoutButtons()
}
func layoutButtons() {
for var i:Int = 0; i < self.buttons?.count; i++ {
let btn:UIButton = self.buttons?[i] as UIButton!
btn.removeFromSuperview()
}
let cnt:CGFloat = CGFloat(self.buttons!.count)
let btnWidth:CGFloat = self.backGroundView!.frame.size.width / cnt
for var i:Int = 0; i < self.buttons?.count; i++ {
let btn:UIButton = self.buttons?[i] as UIButton!
btn.frame = CGRectMake(btnWidth * CGFloat(i), 230 - 40, btnWidth, 40)
self.backGroundView!.insertSubview(btn, atIndex: 1)
if CGFloat(i) < cnt - 1 {
} else {
}
}
}
// Understating the Autolayout in Swift
// http://makeapppie.com/2014/07/26/the-swift-swift-tutorial-how-to-use-uiviews-with-auto-layout-programmatically/
// https://developer.apple.com/videos/wwdc/2015/?id=218
// https://developer.apple.com/videos/wwdc/2015/?id=219
private func setBackground(view:UIView) {
if backGroundView?.superview != nil {
backGroundView?.removeFromSuperview()
var aView = backGroundView?.viewWithTag(1001) as UIView?
aView?.removeFromSuperview()
}
backGroundView = UIView(frame:getBackGroundFrame(self))
backGroundView?.backgroundColor = UIColor.clearColor()
var translucentView = UIView(frame: backGroundView!.bounds)
translucentView.backgroundColor = backGroundColor
translucentView.alpha = 0.85
translucentView.tag = 1001;
translucentView.layer.cornerRadius = 10.0
backGroundView?.addSubview(translucentView)
backGroundView?.layer.cornerRadius = 10.0
self.addSubview(backGroundView!)
}
private func getBackGroundFrame(view:UIView)->CGRect {
return CGRectMake(view.center.x - 280 / 2, view.center.y - 230 / 2, 280, 230)
}
func hide() {
if self.superview != nil {
self.removeFromSuperview()
}
}
}
|
mit
|
cbbba706e63d020955cb368b99bb9086
| 29.742857 | 118 | 0.611059 | 4.488008 | false | false | false | false |
inamiy/VTree
|
Demo/GestureDemo/App.swift
|
1
|
3601
|
import UIKit
import VTree
import Flexbox
/// Complex `Message` type that has associated values.
/// - Important: See `VTree.Message` comment documentation for more detail.
enum Msg: AutoMessage
{
case increment
case decrement
case tap(GestureContext)
case pan(PanGestureContext)
case longPress(GestureContext)
case swipe(GestureContext)
case pinch(PinchGestureContext)
case rotation(RotationGestureContext)
case dummy(DummyContext)
}
/// Custom `MessageContext` that is recognizable in Sourcery.
struct DummyContext: AutoMessageContext {}
struct Model
{
let rootSize = UIScreen.main.bounds.size
let message: String
let cursor: Cursor?
struct Cursor
{
let frame: CGRect
let backgroundColor: UIColor
}
}
extension Model.Cursor
{
init?(msg: Msg)
{
switch msg {
case let .tap(context):
let frame = CGRect(origin: context.location, size: .zero)
.insetBy(dx: -20, dy: -20)
self = Model.Cursor(frame: frame, backgroundColor: .orange)
case let .pan(context) where context.state == .changed:
let frame = CGRect(origin: context.location, size: .zero)
.insetBy(dx: -20, dy: -20)
self = Model.Cursor(frame: frame, backgroundColor: .green)
default:
return nil
}
}
}
func update(_ model: Model, _ msg: Msg) -> Model?
{
print(msg) // Warning: impure logging
let argsString = msg.rawMessage.arguments.map { "\($0)" }.joined(separator: "\n")
let cursor = Model.Cursor(msg: msg)
return Model(
message: "\(msg.rawMessage.funcName)\n\(argsString)",
cursor: cursor
)
}
func view(model: Model) -> VView<Msg>
{
let rootWidth = model.rootSize.width
let rootHeight = model.rootSize.height
func rootView(_ children: [AnyVTree<Msg>?]) -> VView<Msg>
{
return VView(
styles: .init {
$0.frame = CGRect(x: 0, y: 0, width: rootWidth, height: rootHeight)
$0.backgroundColor = .white
},
gestures: [.tap(^Msg.tap), .pan(^Msg.pan), .longPress(^Msg.longPress), .swipe(^Msg.swipe), .pinch(^Msg.pinch), .rotation(^Msg.rotation)],
children: children.flatMap { $0 }
)
}
func label(_ message: String) -> VLabel<Msg>
{
return VLabel(
key: key("label"),
text: .text(message),
styles: .init {
$0.frame = CGRect(x: 0, y: 40, width: rootWidth, height: 300)
$0.backgroundColor = .clear
$0.textAlignment = .center
$0.font = .systemFont(ofSize: 24)
}
)
}
func noteLabel() -> VLabel<Msg>
{
return VLabel(
key: key("noteLabel"),
text: "Tap anywhere to test gesture.",
styles: .init {
$0.frame = CGRect(x: 0, y: 350, width: rootWidth, height: 80)
$0.backgroundColor = .clear
$0.textAlignment = .center
$0.font = .systemFont(ofSize: 20)
}
)
}
func cursorView(_ cursor: Model.Cursor) -> VView<Msg>
{
return VView(
key: key("cursor"),
styles: .init {
$0.frame = cursor.frame
$0.backgroundColor = cursor.backgroundColor
}
)
}
return rootView([
*label(model.message),
*noteLabel(),
model.cursor.map(cursorView).map(*)
])
}
|
mit
|
6395f919cafd3332e94615b919de4a0b
| 26.7 | 149 | 0.551236 | 4.041526 | false | false | false | false |
kotdark/Swift
|
XML/XML/RootViewController.swift
|
32
|
6399
|
//
// RootViewController.swift
// XML
//
// Created by Carlos Butron on 02/12/14.
// Copyright (c) 2014 Carlos Butron.
//
// This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later
// version.
// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along with this program. If not, see
// http:/www.gnu.org/licenses/.
//
import UIKit
class RootViewController: UITableViewController, NSURLConnectionDelegate, NSXMLParserDelegate {
var xmlData:NSMutableData? = nil
var songs:NSMutableArray = []
var song:Song = Song(title: "")
var currentStringValue: NSMutableString? = NSMutableString() //Variable Global
override func viewDidLoad() {
super.viewDidLoad()
println("First Ejecution")
var url = NSURL(string: "http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/ws/RSS/topsongs/limit=10/xml")
var request = NSURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 30)
self.xmlData = NSMutableData()
NSURLConnection(request: request, delegate: self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
println("AAAAAA \(songs.count)")
return songs.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("celda") as! UITableViewCell
var elem = songs[indexPath.row] as! Song
println("AAAAAA \(elem.myTitle)")
cell.textLabel!.text = (elem.myTitle) as? String
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
func connection(connection: NSURLConnection, didFailWithError error: NSError){
println("URL access error")
self.xmlData = nil
}
func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
self.xmlData!.appendData(data)
}
func connectionDidFinishLoading(connection: NSURLConnection!){
var xmlCheck = NSString(data: self.xmlData!, encoding: NSUTF8StringEncoding)
//println("XML recived: \(xmlCheck)")
var parser:NSXMLParser = NSXMLParser(data: self.xmlData!)
parser.delegate = self
parser.shouldResolveExternalEntities = true
parser.parse()
for(var i=0; i<songs.count;i++){
var elem = songs[i] as! Song
println(elem.myTitle)
}
self.tableView.reloadData()
}
func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [NSObject : AnyObject]){
if(elementName == "feed") {
//init array
songs = NSMutableArray()
return
}
if(elementName == "entry") {
//Find new song. Create object of song class.
song = Song(title: "")
return
}
if(elementName == "title") {
currentStringValue = NSMutableString(capacity: 50)
}
}
func parser(parser: NSXMLParser, foundCharacters string: String?) {
if(currentStringValue != nil) {
//NSMutableString where we save characters of actual item
currentStringValue = NSMutableString(capacity: 50)
}
currentStringValue?.appendString(string!)
}
func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?){
if(elementName == "entry"){
//add song to array
songs.addObject(song)
}
if(elementName == "title"){
//if we find a title save it in nsstring characters
song.myTitle = currentStringValue!
}
}
}
|
gpl-3.0
|
195a1f42683272e98d42f4bbd3d7c4b4
| 34.748603 | 177 | 0.651352 | 5.210912 | false | false | false | false |
DuckDeck/ViewChaos
|
Sources/LogView.swift
|
1
|
3915
|
//
// LogView.swift
// ViewChaosDemo
//
// Created by Stan Hu on 2018/8/8.
// Copyright © 2018 Qfq. All rights reserved.
//
import UIKit
class LogView: UIView {
static let sharedInstance = LogView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.width * 0.6))
var arrMsg = [String]()
let tbmsg = UITableView()
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 0.8)
tbmsg.backgroundColor = UIColor.clear
tbmsg.frame = CGRect(origin: CGPoint(), size: frame.size)
tbmsg.dataSource = self
tbmsg.delegate = self
tbmsg.estimatedRowHeight = 20
tbmsg.separatorStyle = .singleLine
tbmsg.separatorColor = UIColor.white
tbmsg.register(logTableViewCell.self, forCellReuseIdentifier: "LogCell")
tbmsg.tableFooterView = UIView()
addSubview(tbmsg)
}
func addLog(msg:String) {
if arrMsg.count >= 80{
arrMsg.removeSubrange(50..<80)
}
arrMsg.append(msg)
tbmsg.reloadData()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class logTableViewCell: UITableViewCell {
let lblMsg = UILabel()
var msg:String?{
didSet{
lblMsg.text = msg
}
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
backgroundColor = UIColor.clear
lblMsg.numberOfLines = 0
lblMsg.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(lblMsg)
let leftConstraint = NSLayoutConstraint.init(item: lblMsg, attribute: NSLayoutConstraint.Attribute.leading, relatedBy: NSLayoutConstraint.Relation.equal, toItem: contentView, attribute: NSLayoutConstraint.Attribute.leading, multiplier: 1, constant: 10)
let rightConstraint = NSLayoutConstraint.init(item: lblMsg, attribute: NSLayoutConstraint.Attribute.trailing, relatedBy: NSLayoutConstraint.Relation.equal, toItem: contentView, attribute: NSLayoutConstraint.Attribute.trailing, multiplier: 1, constant: -10)
let topConstraint = NSLayoutConstraint.init(item: lblMsg, attribute: NSLayoutConstraint.Attribute.top, relatedBy: NSLayoutConstraint.Relation.equal, toItem: contentView, attribute: NSLayoutConstraint.Attribute.top, multiplier: 1, constant: 3)
let bottomConstraint = NSLayoutConstraint.init(item: lblMsg, attribute: NSLayoutConstraint.Attribute.bottom, relatedBy: NSLayoutConstraint.Relation.equal, toItem: contentView, attribute: NSLayoutConstraint.Attribute.bottom, multiplier: 1, constant: -3)
NSLayoutConstraint.activate([leftConstraint,rightConstraint,topConstraint,bottomConstraint])
lblMsg.textColor = UIColor.white
lblMsg.font = UIFont.systemFont(ofSize: 12)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension LogView:UITableViewDataSource,UITableViewDelegate{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrMsg.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "LogCell", for: indexPath) as! logTableViewCell
cell.msg = arrMsg[indexPath.row]
return cell
}
}
func VCLog<T>(message:T,file:String = #file, method:String = #function,line:Int = #line){
#if DEBUG
if let path = NSURL(string: file)
{
let log = "\(path.lastPathComponent!)[\(line)],\(method) \(message)"
LogView.sharedInstance.addLog(msg: log)
print(log)
}
#endif
}
|
mit
|
70cd0312080c9e6e2369f691e47f5c10
| 40.2 | 264 | 0.69162 | 4.442679 | false | false | false | false |
NoryCao/zhuishushenqi
|
zhuishushenqi/NewVersion/Comment/ZSPostReview.swift
|
1
|
2981
|
//
// ZSPostReview.swift
// zhuishushenqi
//
// Created by yung on 2019/8/7.
// Copyright © 2019 QS. All rights reserved.
//
import UIKit
import HandyJSON
struct ZSPostReview:HandyJSON {
var _id:String = ""
var rating:Int = 0
var type:String = ""
var book:ZSPostReviewBook = ZSPostReviewBook()
var author:ZSPostReviewAuthor = ZSPostReviewAuthor()
var helpful:ZSPostReviewHelpful = ZSPostReviewHelpful(no: 0, total: 0, yes: 0)
var state:String = ""
var updated:String = ""
var created:String = ""
var commentCount:Int = 0
var content:String = ""
var title:String = ""
var shareLink:String = ""
var id:String = ""
}
//{
// "review": {
// "_id": "5d47f6c109fdcf734ec03ec3",
// "rating": 3,
// "type": "review",
// "book": {
// "_id": "58c8b41a08eed7c070137872",
// "author": "薄凉君子",
// "title": "独步惊华,腹黑嫡女御天下",
// "cover": "/agent/http%3A%2F%2Fimg.1391.com%2Fapi%2Fv1%2Fbookcenter%2Fcover%2F1%2F2066474%2F2066474_c1b2752e5649449c9a341556542dbfce.jpg%2F",
// "safelevel": 5,
// "allowFree": true,
// "apptype": [0, 1, 2, 4, 6],
// "id": "58c8b41a08eed7c070137872",
// "latelyFollower": null,
// "retentionRatio": null
// },
// "author": {
// "_id": "5cfa56b67a823add1cf3e377",
// "avatar": "/avatar/cf/46/cf4682dccd69c381ce4ebf4abbb44f5f",
// "nickname": "晨",
// "activityAvatar": "",
// "type": "normal",
// "lv": 5,
// "gender": "female",
// "rank": null,
// "created": "2019-06-07T12:21:10.000Z",
// "id": "5cfa56b67a823add1cf3e377"
// },
// "helpful": {
// "total": -1,
// "no": 2,
// "yes": 1
// },
// "state": "normal",
// "updated": "2019-08-06T13:46:47.643Z",
// "created": "2019-08-05T09:28:33.410Z",
// "commentCount": 0,
// "content": "故事情节不错,作者用词要斟酌下了,看了一点就明显,秀色可餐的食物,秀色可餐是用来形容好看的人。男主看着女主,想让女主放下伪装。。。前几个词都不错,但醉生梦死。。这真的适合形容他俩吗? \n 😂",
// "title": "加油加油",
// "shareLink": "http://share.zhuishushenqi.com/post/5d47f6c109fdcf734ec03ec3",
// "id": "5d47f6c109fdcf734ec03ec3"
// },
// "ok": true
//}
|
mit
|
24aac344200aa09f55fe4b93550b2636
| 35.706667 | 525 | 0.447875 | 2.995647 | false | false | false | false |
acrookston/ACRAutoComplete
|
Example/ACRAutoComplete/ViewController.swift
|
1
|
4766
|
//
// ViewController.swift
// ACRAutoComplete
//
// Created by Andrew Crookston on 09/20/2016.
// Copyright (c) 2016 Andrew Crookston. All rights reserved.
//
import UIKit
import ACRAutoComplete
final class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate {
var words = [Word]()
var autoComplete = AutoComplete<Word>()
var results = [Word]()
var searching = false
private lazy var searchBar: UISearchBar = {
let searchBar = UISearchBar(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 44))
searchBar.searchBarStyle = .minimal
searchBar.barTintColor = .white
searchBar.delegate = self
searchBar.placeholder = "Search"
searchBar.returnKeyType = .done
searchBar.enablesReturnKeyAutomatically = false
searchBar.showsCancelButton = true
return searchBar
}()
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
loadWords()
tableView.tableHeaderView = searchBar
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
words = []
autoComplete = AutoComplete<Word>()
loadWords()
}
func loadWords() {
guard words.count == 0 else { return }
guard let path = Bundle.main.path(forResource: "sowpods", ofType: "txt") else { return }
DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated).async {
do {
let data = try String(contentsOfFile: path, encoding: .utf8)
printTimeElapsedWhenRunningCode(title: "parsing words", operation: {
data.components(separatedBy: .newlines).forEach({
self.words.append(Word(word: $0))
})
})
DispatchQueue.main.async {
self.tableView.reloadData()
}
printTimeElapsedWhenRunningCode(title: "indexing words", operation: {
for word in self.words {
self.autoComplete.insert(word)
}
})
} catch {
print(error)
}
}
}
// MARK: - UISearchBarDelegate
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
guard let text = searchBar.text else { return }
searching = text != ""
if searching {
DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated).async {
printTimeElapsedWhenRunningCode(title: "searching \(text)", operation: {
self.results = self.autoComplete.search(text) // .sorted(by: { $0.word < $1.word })
})
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
} else {
self.tableView.reloadData()
}
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.resignFirstResponder()
searchBar.text = ""
searching = false
results = []
tableView.reloadData()
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchBar.resignFirstResponder()
}
// MARK: - UITableViewDataSource
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searching {
return results.count
}
return words.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: LabelCell.identifier) as? LabelCell else {
fatalError("wrong cell")
}
if searching {
cell.label.text = results[indexPath.row].word
} else {
cell.label.text = words[indexPath.row].word
}
return cell
}
// MARK: - UITableViewDelegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if searching {
UIPasteboard.general.string = results[indexPath.row].word
} else {
UIPasteboard.general.string = words[indexPath.row].word
}
tableView.deselectRow(at: indexPath, animated: true)
}
}
func printTimeElapsedWhenRunningCode(title: String, operation:() -> Void) {
let startTime = CFAbsoluteTimeGetCurrent()
operation()
let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
print("Time elapsed for \(title): \(timeElapsed) s")
}
|
mit
|
2ae86746abfca0b21a3967646ea0a197
| 30.562914 | 114 | 0.600084 | 5.186072 | false | false | false | false |
DanisFabric/RainbowNavigation
|
RainbowNavigationSample/TransparentTableViewController.swift
|
1
|
2123
|
//
// TransparentTableViewController.swift
// RainbowNavigationSample
//
// Created by Danis on 15/12/30.
// Copyright © 2015年 danis. All rights reserved.
//
import UIKit
import RainbowNavigation
class TransparentTableViewController: UITableViewController, RainbowColorSource {
override func viewDidLoad() {
super.viewDidLoad()
self.automaticallyAdjustsScrollViewInsets = false
let imageView = UIImageView(image: UIImage(named: "demo-header"))
imageView.contentMode = .scaleAspectFill
imageView.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.width * 0.75)
tableView.tableHeaderView = imageView
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 20
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "SampleCell", for: indexPath)
cell.textLabel?.text = "Cell"
return cell
}
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
let themeColor = UIColor(red: 247/255.0, green: 80/255.0, blue: 120/255.0, alpha: 1.0)
let offsetY = scrollView.contentOffset.y
if offsetY >= 0 {
let height = self.tableView.tableHeaderView!.bounds.height
let maxOffset = height - 64
var progress = (scrollView.contentOffset.y - 64) / maxOffset
progress = min(progress, 1)
self.navigationController?.navigationBar.rb.backgroundColor = themeColor.withAlphaComponent(progress)
}
}
// MARK: - RainbowColorSource
func navigationBarInColor() -> UIColor {
return UIColor.clear
}
}
|
mit
|
a0e816296fc64f73e3a7639518f708b2
| 32.125 | 114 | 0.654245 | 5.01182 | false | false | false | false |
tkunstek/ElevenNote
|
ElevenNote/Models/Note.swift
|
1
|
1086
|
//
// Note.swift
// ElevenNote
//
// Copyright (c) 2014 ElevenFifty. All rights reserved.
//
import Foundation
class Note : NSObject, NSCoding {
var title = ""
var text = ""
var date = NSDate() // Defaults to current date / time
// Computed property to return date as a string
var shortDate : NSString {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM/dd/yy"
return dateFormatter.stringFromDate(self.date)
}
override init() {
super.init()
}
// 1: Encode ourselves...
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(title, forKey: "title")
aCoder.encodeObject(text, forKey: "text")
aCoder.encodeObject(date, forKey: "date")
}
// 2: Decode ourselves on init
required init(coder aDecoder: NSCoder) {
self.title = aDecoder.decodeObjectForKey("title") as String
self.text = aDecoder.decodeObjectForKey("text") as String
self.date = aDecoder.decodeObjectForKey("date") as NSDate
}
}
|
mit
|
a56c4c6c0fd70ea6f889999c32298fbd
| 26.175 | 67 | 0.620626 | 4.414634 | false | false | false | false |
selfzhou/Swift3
|
Playground/Swift3-II.playground/Pages/StringsAndCharacters.xcplaygroundpage/Contents.swift
|
1
|
1345
|
//: [Previous](@previous)
import Foundation
var emptyString = ""
var anotherEmptyString = String()
if emptyString == anotherEmptyString {
print("Equal")
}
for character in "Dog!🐶".characters {
print(character)
}
let catChatacters: [Character] = ["C", "a", "t"]
let catString = String(catChatacters)
var welcome = "welcome"
welcome.append("!")
/**
NSString length 利用 UTF-16 表示的十六位代码单元数字,而不是 Unicode 可扩展字符群集
当一个 NSString length 属性被一个 Swift 的 String 值访问时,实际上是调用了 utf16Count
*/
/**
startIndex 获取 String 的第一个 Character 的索引
endIndex 获取最后一个 Character 的`后一个位置`的索引
*/
let greeting = "Guten Tag!"
greeting[greeting.startIndex]
greeting[greeting.index(before: greeting.endIndex)]
greeting[greeting.index(after: greeting.startIndex)]
let index = greeting.index(greeting.startIndex, offsetBy: 7)
greeting[index]
/**
`indices`
characters 属性的 indices 属性会创建一个包含全部索引的范围(Range),用来在一个字符串中访问单个字符
*/
for index in greeting.characters.indices {
print("\(greeting[index])", terminator: "")
}
welcome.insert(contentsOf: " hello".characters, at: welcome.index(before: welcome.endIndex))
|
mit
|
3570660172e52304a2fa76ecefdad72a
| 18.789474 | 92 | 0.715426 | 3.49226 | false | false | false | false |
manavgabhawala/swift
|
test/SILGen/objc_extensions.swift
|
1
|
8575
|
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -emit-silgen -sdk %S/Inputs/ -I %S/Inputs -enable-source-import %s | %FileCheck %s
// REQUIRES: objc_interop
import Foundation
import objc_extensions_helper
class Sub : Base {}
extension Sub {
override var prop: String! {
didSet {
// Ignore it.
}
// Make sure that we are generating the @objc thunk and are calling the actual method.
//
// CHECK-LABEL: sil hidden [thunk] @_T015objc_extensions3SubC4propSQySSGfgTo : $@convention(objc_method) (Sub) -> @autoreleased Optional<NSString> {
// CHECK: bb0([[SELF:%.*]] : $Sub):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK: [[GETTER_FUNC:%.*]] = function_ref @_T015objc_extensions3SubC4propSQySSGfg : $@convention(method) (@guaranteed Sub) -> @owned Optional<String>
// CHECK: apply [[GETTER_FUNC]]([[BORROWED_SELF_COPY]])
// CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK: destroy_value [[SELF_COPY]]
// CHECK: } // end sil function '_T015objc_extensions3SubC4propSQySSGfgTo'
// Then check the body of the getter calls the super_method.
// CHECK-LABEL: sil hidden @_T015objc_extensions3SubC4propSQySSGfg : $@convention(method) (@guaranteed Sub) -> @owned Optional<String> {
// CHECK: bb0([[SELF:%.*]] : $Sub):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[SELF_COPY_CAST:%.*]] = upcast [[SELF_COPY]] : $Sub to $Base
// CHECK: [[SUPER_METHOD:%.*]] = super_method [volatile] [[SELF_COPY]] : $Sub, #Base.prop!getter.1.foreign
// CHECK: [[RESULT:%.*]] = apply [[SUPER_METHOD]]([[SELF_COPY_CAST]])
// CHECK: bb3(
// CHECK: destroy_value [[SELF_COPY]]
// CHECK: } // end sil function '_T015objc_extensions3SubC4propSQySSGfg'
// Then check the setter @objc thunk.
//
// CHECK-LABEL: sil hidden [thunk] @_T015objc_extensions3SubC4propSQySSGfsTo : $@convention(objc_method) (Optional<NSString>, Sub) -> () {
// CHECK: bb0([[NEW_VALUE:%.*]] : $Optional<NSString>, [[SELF:%.*]] : $Sub):
// CHECK: [[NEW_VALUE_COPY:%.*]] = copy_value [[NEW_VALUE]]
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Sub
// CHECK: switch_enum [[NEW_VALUE_COPY]] : $Optional<NSString>, case #Optional.some!enumelt.1: [[SUCC_BB:bb[0-9]+]], case #Optional.none!enumelt: [[FAIL_BB:bb[0-9]+]]
// CHECK: [[SUCC_BB]]([[STR:%.*]] : $NSString):
// CHECK: [[FAIL_BB]]:
// CHECK: bb3([[BRIDGED_NEW_VALUE:%.*]] : $Optional<String>):
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK: [[NORMAL_FUNC:%.*]] = function_ref @_T015objc_extensions3SubC4propSQySSGfs : $@convention(method) (@owned Optional<String>, @guaranteed Sub) -> ()
// CHECK: apply [[NORMAL_FUNC]]([[BRIDGED_NEW_VALUE]], [[BORROWED_SELF_COPY]])
// CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK: destroy_value [[SELF_COPY]]
// CHECK: } // end sil function '_T015objc_extensions3SubC4propSQySSGfsTo'
// Then check the body of the actually setter value and make sure that we
// call the didSet function.
// CHECK-LABEL: sil hidden @_T015objc_extensions3SubC4propSQySSGfs : $@convention(method) (@owned Optional<String>, @guaranteed Sub) -> () {
// First we get the old value.
// CHECK: bb0([[NEW_VALUE:%.*]] : $Optional<String>, [[SELF:%.*]] : $Sub):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[UPCAST_SELF_COPY:%.*]] = upcast [[SELF_COPY]] : $Sub to $Base
// CHECK: [[GET_SUPER_METHOD:%.*]] = super_method [volatile] [[SELF_COPY]] : $Sub, #Base.prop!getter.1.foreign : (Base) -> () -> String!, $@convention(objc_method) (Base) -> @autoreleased Optional<NSString>
// CHECK: [[OLD_NSSTRING:%.*]] = apply [[GET_SUPER_METHOD]]([[UPCAST_SELF_COPY]])
// CHECK: bb3([[OLD_NSSTRING_BRIDGED:%.*]] : $Optional<String>):
// This next line is completely not needed. But we are emitting it now.
// CHECK: destroy_value [[SELF_COPY]]
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[UPCAST_SELF_COPY:%.*]] = upcast [[SELF_COPY]] : $Sub to $Base
// CHECK: [[BORROWED_NEW_VALUE:%.*]] = begin_borrow [[NEW_VALUE]]
// CHECK: [[NEW_VALUE_COPY:%.*]] = copy_value [[BORROWED_NEW_VALUE]]
// CHECK: [[SET_SUPER_METHOD:%.*]] = super_method [volatile] [[SELF_COPY]] : $Sub, #Base.prop!setter.1.foreign : (Base) -> (String!) -> (), $@convention(objc_method) (Optional<NSString>, Base) -> ()
// CHECK: switch_enum [[NEW_VALUE_COPY]] : $Optional<String>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]]
//
// CHECK: bb4([[OLD_STRING:%.*]] : $String):
// CHECK: bb6([[BRIDGED_NEW_STRING:%.*]] : $Optional<NSString>):
// CHECK: apply [[SET_SUPER_METHOD]]([[BRIDGED_NEW_STRING]], [[UPCAST_SELF_COPY]])
// CHECK: destroy_value [[BRIDGED_NEW_STRING]]
// CHECK: destroy_value [[SELF_COPY]]
// CHECK: [[DIDSET_NOTIFIER:%.*]] = function_ref @_T015objc_extensions3SubC4propSQySSGfW : $@convention(method) (@owned Optional<String>, @guaranteed Sub) -> ()
// CHECK: [[BORROWED_OLD_NSSTRING_BRIDGED:%.*]] = begin_borrow [[OLD_NSSTRING_BRIDGED]]
// CHECK: [[COPIED_OLD_NSSTRING_BRIDGED:%.*]] = copy_value [[BORROWED_OLD_NSSTRING_BRIDGED]]
// CHECK: end_borrow [[BORROWED_OLD_NSSTRING_BRIDGED]] from [[OLD_NSSTRING_BRIDGED]]
// This is an identity cast that should be eliminated by SILGen peepholes.
// CHECK: apply [[DIDSET_NOTIFIER]]([[COPIED_OLD_NSSTRING_BRIDGED]], [[SELF]])
// CHECK: destroy_value [[OLD_NSSTRING_BRIDGED]]
// CHECK: destroy_value [[NEW_VALUE]]
// CHECK: } // end sil function '_T015objc_extensions3SubC4propSQySSGfs'
}
func foo() {
}
override func objCBaseMethod() {}
}
// CHECK-LABEL: sil hidden @_T015objc_extensions20testOverridePropertyyAA3SubCF
func testOverrideProperty(_ obj: Sub) {
// CHECK: bb0([[ARG:%.*]] : $Sub):
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: = class_method [volatile] [[BORROWED_ARG]] : $Sub, #Sub.prop!setter.1.foreign : (Sub) -> (String!) -> ()
obj.prop = "abc"
} // CHECK: } // end sil function '_T015objc_extensions20testOverridePropertyyAA3SubCF'
testOverrideProperty(Sub())
// CHECK-LABEL: sil shared [thunk] @_T015objc_extensions3SubC3fooyyFTc
// CHECK: function_ref @_T015objc_extensions3SubC3fooyyFTD
// CHECK: } // end sil function '_T015objc_extensions3SubC3fooyyFTc'
// CHECK: sil shared [transparent] [thunk] @_T015objc_extensions3SubC3fooyyFTD
// CHECK: bb0([[SELF:%.*]] : $Sub):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: class_method [volatile] [[SELF_COPY]] : $Sub, #Sub.foo!1.foreign
// CHECK: } // end sil function '_T015objc_extensions3SubC3fooyyFTD'
func testCurry(_ x: Sub) {
_ = x.foo
}
extension Sub {
var otherProp: String {
get { return "hello" }
set { }
}
}
class SubSub : Sub {
// CHECK-LABEL: sil hidden @_T015objc_extensions03SubC0C14objCBaseMethodyyF
// CHECK: bb0([[SELF:%.*]] : $SubSub):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: super_method [volatile] [[SELF_COPY]] : $SubSub, #Sub.objCBaseMethod!1.foreign : (Sub) -> () -> (), $@convention(objc_method) (Sub) -> ()
// CHECK: } // end sil function '_T015objc_extensions03SubC0C14objCBaseMethodyyF'
override func objCBaseMethod() {
super.objCBaseMethod()
}
}
extension SubSub {
// CHECK-LABEL: sil hidden @_T015objc_extensions03SubC0C9otherPropSSfs
// CHECK: bb0([[NEW_VALUE:%.*]] : $String, [[SELF:%.*]] : $SubSub):
// CHECK: [[SELF_COPY_1:%.*]] = copy_value [[SELF]]
// CHECK: = super_method [volatile] [[SELF_COPY_1]] : $SubSub, #Sub.otherProp!getter.1.foreign
// CHECK: [[SELF_COPY_2:%.*]] = copy_value [[SELF]]
// CHECK: = super_method [volatile] [[SELF_COPY_2]] : $SubSub, #Sub.otherProp!setter.1.foreign
// CHECK: } // end sil function '_T015objc_extensions03SubC0C9otherPropSSfs'
override var otherProp: String {
didSet {
// Ignore it.
}
}
}
// SR-1025
extension Base {
fileprivate static var x = 1
}
// CHECK-LABEL: sil hidden @_T015objc_extensions19testStaticVarAccessyyF
func testStaticVarAccess() {
// CHECK: [[F:%.*]] = function_ref @_T0So4BaseC15objc_extensionsE1x33_1F05E59585E0BB585FCA206FBFF1A92DLLSifau
// CHECK: [[PTR:%.*]] = apply [[F]]()
// CHECK: [[ADDR:%.*]] = pointer_to_address [[PTR]]
_ = Base.x
}
|
apache-2.0
|
cf030dfd84d497b9b201cf61112aa87f
| 50.656627 | 212 | 0.622741 | 3.378645 | false | false | false | false |
nastia05/TTU-iOS-Developing-Course
|
Lecture 4/ArraysDemo.playground/Contents.swift
|
1
|
1651
|
// dummy array, the type can be derived from the context but it was explicitly
var arrayOfDomains: [String] = ["apple.com", "google.com"]
// for this one we have to add type as it can not be evaluated from context
var arrayOfDifferentThings: [Any] = [1, 2, ""]
// to add something we should do:
arrayOfDomains.append("microsoft.com")
// to get value at index:
let appleDomain = arrayOfDomains[1]
// crash when out of range:
//let domainForNotExisingIndex = arrayOfDomains[3]
// convenience method to get first element:
let firstDomain = arrayOfDomains.first
// and last one:
let lastDomain = arrayOfDomains.last
// to enumerate through the array
for domain in arrayOfDomains {
print(domain)
}
// to get array size(number of elements)
let size = arrayOfDomains.count
// to remove at index, crashes when out of range:
let element = arrayOfDomains.remove(at: 1)
// to insert at index, crashes when out of range:
arrayOfDomains.insert("parallels.com", at: 2)
// to replace at index:
arrayOfDomains[1] = "parallels.com"
// MARK - do it yourself
struct Student {
typealias Group = Int
let name: String
let age: Int
let group: Group
}
class Classroom {
private var students: [Student] = []
func add(student: Student) {
// TODO: implement insert to the end of the students
}
func student(with name: String) -> Student? {
// iterate through and find first student with specified name
return nil
}
func students(of group: Student.Group) -> [Student] {
// find all students with specified group
return []
}
}
|
mit
|
6c2f910be38f466f846cfa52cd635fd1
| 23.279412 | 79 | 0.671714 | 3.76082 | false | false | false | false |
darwinsubramaniam/LetzEat
|
LetzEat/iOS/LetzEat/LetzEat/AppDelegate.swift
|
1
|
6079
|
//
// AppDelegate.swift
// LetzEat
//
// Created by UDLab on 05/03/16.
// Copyright © 2016 UDWorld. 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.
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 "UDworld.net.LetzEat" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
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("LetzEat", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns 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
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = 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 \(wrappedError), \(wrappedError.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
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// 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.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
|
apache-2.0
|
5a09cbc5e334a15c347015c10d8eaba9
| 53.756757 | 291 | 0.719151 | 5.866795 | false | false | false | false |
grigaci/WallpapersCollectionView
|
WallpapersCollectionView/WallpapersCollectionView/Classes/Model/BIModelManager.swift
|
1
|
1914
|
//
// BIModelManager.swift
// WallpapersCollectionView
//
// Created by Bogdan Iusco on 9/28/14.
// Copyright (c) 2014 Grigaci. All rights reserved.
//
import Foundation
class BIModelManager {
let locationsCount = 2
private var Bran: BILocation
private var Sighisoara: BILocation
class var sharedInstance : BIModelManager {
struct Static {
static var onceToken : dispatch_once_t = 0
static var instance : BIModelManager? = nil
}
dispatch_once(&Static.onceToken) {
Static.instance = BIModelManager()
}
return Static.instance!
}
init () {
var branPhotos = BIModelManager.BranPhotoNames()
self.Bran = BILocation(name: "Bran", photoNames: branPhotos)
var sighisoaraPhotos = BIModelManager.SighisoaraPhotoNames()
self.Sighisoara = BILocation(name: "Sighisoara", photoNames: sighisoaraPhotos)
}
func locationAtIndex(index: Int) -> BILocation? {
var returnedLocation: BILocation?
switch index {
case 0:
returnedLocation = self.Bran
case 1:
returnedLocation = self.Sighisoara
default:
returnedLocation = nil
}
return returnedLocation
}
class private func BranPhotoNames() -> NSArray! {
var mutableArray = NSMutableArray()
let countPhotos = 6
for index in 1...countPhotos {
var imageName = "Bran-\(index)"
mutableArray.addObject(imageName)
}
return NSArray(array: mutableArray)
}
class private func SighisoaraPhotoNames() -> NSArray! {
var mutableArray = NSMutableArray()
let countPhotos = 7
for index in 1...countPhotos {
var imageName = "Sighisoara-\(index)"
mutableArray.addObject(imageName)
}
return NSArray(array: mutableArray)
}
}
|
mit
|
7f2a405e2647344c0570810e989bcd7a
| 28.015152 | 86 | 0.617032 | 4.301124 | false | false | false | false |
Esri/arcgis-runtime-samples-ios
|
arcgis-ios-sdk-samples/Route and directions/Route around barriers/RouteParametersViewController.swift
|
1
|
2861
|
//
// Copyright 2016 Esri.
//
// 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 ArcGIS
class RouteParametersViewController: UITableViewController {
@IBOutlet var findBestSequenceSwitch: UISwitch?
@IBOutlet var preserveFirstStopSwitch: UISwitch?
@IBOutlet var preserveLastStopSwitch: UISwitch?
var routeParameters: AGSRouteParameters? {
didSet {
setupUI()
}
}
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadData()
preferredContentSize.height = tableView.contentSize.height
}
private func setupUI() {
guard let routeParameters = routeParameters else {
return
}
findBestSequenceSwitch?.isOn = routeParameters.findBestSequence
preserveFirstStopSwitch?.isOn = routeParameters.preserveFirstStop
preserveLastStopSwitch?.isOn = routeParameters.preserveLastStop
}
// MARK: - Actions
@IBAction func switchValueChanged(_ sender: UISwitch) {
switch sender {
case findBestSequenceSwitch:
routeParameters?.findBestSequence = sender.isOn
let sections: IndexSet = [1]
tableView.performBatchUpdates({
if sender.isOn {
tableView?.insertSections(sections, with: .fade)
} else {
tableView?.deleteSections(sections, with: .fade)
}
}, completion: { (finished) in
guard finished else {
return
}
self.preferredContentSize.height = self.tableView.contentSize.height
})
setupUI()
case preserveFirstStopSwitch:
routeParameters?.preserveFirstStop = sender.isOn
case preserveLastStopSwitch:
routeParameters?.preserveLastStop = sender.isOn
default:
break
}
}
override func numberOfSections(in tableView: UITableView) -> Int {
let superCount = super.numberOfSections(in: tableView)
if routeParameters?.findBestSequence == false {
return superCount - 1
}
return superCount
}
}
|
apache-2.0
|
d5aa06994b440601dc66899798d02e4f
| 31.885057 | 84 | 0.631947 | 5.307978 | false | false | false | false |
hashemi/slox
|
slox/Lox.swift
|
1
|
2580
|
//
// Lox.swift
// slox
//
// Created by Ahmad Alhashemi on 2017-03-18.
// Copyright © 2017 Ahmad Alhashemi. All rights reserved.
//
import Foundation
struct Lox {
static var hadError = false
static var hadRuntimeError = false
static func main(_ args: [String]) throws {
if args.count > 1 {
print("Usage: slox [script]")
} else if args.count == 1 {
try Lox.runFile(args[0])
} else {
try Lox.runPrompt()
}
}
static func runFile(_ path: String) throws {
let bytes = try Data(contentsOf: URL(fileURLWithPath: path))
run(String(bytes: bytes, encoding: .utf8)!, environment: .globals)
if hadError { exit(65) }
if hadRuntimeError { exit(70) }
}
static func runPrompt() throws {
let environment = Environment.globals
while true {
print("> ", terminator: "")
guard let line = readLine() else { return }
run(line, environment: environment)
hadError = false
}
}
static func run(_ source: String, environment: Environment) {
let scanner = Scanner(source)
let tokens = scanner.scanTokens()
let parser = Parser(tokens)
do {
let statements = try parser.parse()
if hadError { return }
let resolver = Resolver()
let resolvedStatements = statements.map { $0.resolve(resolver: resolver) }
if hadError { return }
for statement in resolvedStatements {
try statement.execute(environment: environment)
}
} catch let error as RuntimeError {
runtimeError(error)
} catch {
fatalError("Unexpected error.")
}
}
static func error(_ line: Int, _ message: String) {
report(line, "", message)
}
static func report(_ line: Int, _ `where`: String, _ message: String) {
fputs("[line \(line)] Error\(`where`): \(message)\n", __stderrp)
hadError = true
}
static func error(_ token: Token, _ message: String) {
if token.type == .eof {
report(token.line, " at end", message)
} else {
report(token.line, " at '\(token.lexeme)'", message)
}
}
static func runtimeError(_ error: RuntimeError) {
fputs("\(error.message)\n[line \(String(error.token.line))]\n", __stderrp)
hadRuntimeError = true
}
}
|
mit
|
75a00f465c4c702fba25c7b5ce10a0e2
| 27.977528 | 86 | 0.534316 | 4.431271 | false | false | false | false |
brokenhandsio/SteamPress
|
Sources/SteamPress/Extensions/URL+Converters.swift
|
1
|
1561
|
import Foundation
import Vapor
extension Request {
func url() throws -> URL {
let path = self.http.url.path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? ""
let hostname: String
if let envURL = Environment.get("WEBSITE_URL") {
hostname = envURL
} else {
hostname = self.http.remotePeer.description
}
let urlString = "\(hostname)\(path)"
guard let url = URL(string: urlString) else {
throw SteamPressError(identifier: "SteamPressError", "Failed to convert url path to URL")
}
return url
}
func rootUrl() throws -> URL {
if let envURL = Environment.get("WEBSITE_URL") {
guard let url = URL(string: envURL) else {
throw SteamPressError(identifier: "SteamPressError", "Failed to convert url hostname to URL")
}
return url
}
var hostname = self.http.remotePeer.description
if hostname == "" {
hostname = "/"
}
guard let url = URL(string: hostname) else {
throw SteamPressError(identifier: "SteamPressError", "Failed to convert url hostname to URL")
}
return url
}
}
private extension String {
func replacingFirstOccurrence(of target: String, with replaceString: String) -> String {
if let range = self.range(of: target) {
return self.replacingCharacters(in: range, with: replaceString)
}
return self
}
}
|
mit
|
82894c1439a4f38e44cd94d8dfadd64c
| 31.520833 | 109 | 0.58296 | 4.673653 | false | false | false | false |
AnarchyTools/xcode-emit
|
src/tools.swift
|
2
|
2997
|
// Copyright (c) 2016 Anarchy Tools Contributors.
//
// 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.
#if os(OSX)
import Darwin
#else
import Glibc
#endif
import atfoundation
private func _WSTATUS(_ status: CInt) -> CInt {
return status & 0x7f
}
private func WIFEXITED(_ status: CInt) -> Bool {
return _WSTATUS(status) == 0
}
private func WEXITSTATUS(_ status: CInt) -> CInt {
return (status >> 8) & 0xff
}
/// convenience wrapper for waitpid
private func waitpid(_ pid: pid_t) -> Int32 {
while true {
var exitStatus: Int32 = 0
let rv = waitpid(pid, &exitStatus, 0)
if rv != -1 {
if WIFEXITED(exitStatus) {
return WEXITSTATUS(exitStatus)
} else {
fatalError("Exit signal")
}
} else if errno == EINTR {
continue // see: man waitpid
} else {
fatalError("waitpid: \(errno)")
}
}
}
///A wrapper for POSIX "system" call.
///If return value is non-zero, we exit (not fatalError)
///See #72 for details.
///- note: This function call is appropriate for commands that are user-perceivable (such as compilation)
///Rather than calls that aren't
func anarchySystem(_ cmd: String, environment: [String: String]) -> Int32 {
var output = ""
return anarchySystem(cmd, environment: environment, redirectOutput: &output)
}
func anarchySystem(_ cmd: String, environment: [String: String],redirectOutput: inout String) -> Int32 {
var pid : pid_t = 0
//copy a few well-known values
var environment = environment
for arg in ["PATH","HOME"] {
if let path = getenv(arg) {
environment[arg] = String(validatingUTF8: path)!
}
}
var cmd = cmd
cmd += ">/tmp/anarchySystem.out"
let args: [String] = ["sh","-c",cmd]
let argv = args.map{ $0.withCString(strdup) }
let env: [UnsafeMutablePointer<CChar>?] = environment.map{ "\($0.0)=\($0.1)".withCString(strdup) }
let directory = try! FS.getWorkingDirectory()
defer {try! FS.changeWorkingDirectory(path: directory)}
if let e = environment["PWD"] {
try! FS.changeWorkingDirectory(path: Path(e))
}
let status = posix_spawn(&pid, "/bin/sh",nil,nil,argv + [nil],env + [nil])
if status != 0 {
fatalError("spawn error \(status)")
}
let returnCode = waitpid(pid)
redirectOutput = try! File(path: Path("/tmp/anarchySystem.out"), mode:.ReadOnly).readAll()!
return returnCode
}
|
apache-2.0
|
b75f30946c1348f13d8eaa15030178c7
| 31.236559 | 105 | 0.639306 | 3.808132 | false | false | false | false |
grgcombs/objc-code-challenges
|
10-anagram-strings.swift
|
2
|
1161
|
import Foundation
/**
* Swift function to test if two strings are anagrams
*/
func isAnagram(one: String, two: String) -> Bool
{
if one.startIndex != two.startIndex ||
one.endIndex != two.endIndex
{
return false
}
var occurances : [Character : Int] = [:]
for var i=one.startIndex; i < one.endIndex; i++ {
var count = 0
let oneChar = one[i]
let twoChar = two[i]
func storeOrRemoveOccurance(key : Character, count : Int) {
if count == 0 {
occurances.removeValueForKey(key)
return
}
occurances[key] = count
}
count = occurances[oneChar] ?? 0
count++ // add for this 'one' occurance
storeOrRemoveOccurance(oneChar, count)
count = occurances[twoChar] ?? 0
count-- // subtract for this 'two' occurrance
storeOrRemoveOccurance(twoChar, count)
}
return occurances.isEmpty
}
var result = isAnagram("thing", "ghint")
println("thing vs ghint? (exp. true) \(result)")
result = isAnagram("thingg", "hintt")
println("thingg vs hintt? (exp. false) \(result)")
|
cc0-1.0
|
535ca8ef8a03a0b24216bb3ccbf02ee7
| 24.23913 | 67 | 0.580534 | 3.882943 | false | false | false | false |
yujinjcho/movie_recommendations
|
ios_ui/Pods/Nimble/Sources/Nimble/Utils/Errors.swift
|
160
|
1707
|
import Foundation
// Generic
internal func setFailureMessageForError<T: Error>(
_ failureMessage: FailureMessage,
postfixMessageVerb: String = "throw",
actualError: Error?,
error: T? = nil,
errorType: T.Type? = nil,
closure: ((T) -> Void)? = nil) {
failureMessage.postfixMessage = "\(postfixMessageVerb) error"
if let error = error {
failureMessage.postfixMessage += " <\(error)>"
} else if errorType != nil || closure != nil {
failureMessage.postfixMessage += " from type <\(T.self)>"
}
if closure != nil {
failureMessage.postfixMessage += " that satisfies block"
}
if error == nil && errorType == nil && closure == nil {
failureMessage.postfixMessage = "\(postfixMessageVerb) any error"
}
if let actualError = actualError {
failureMessage.actualValue = "<\(actualError)>"
} else {
failureMessage.actualValue = "no error"
}
}
internal func errorMatchesExpectedError<T: Error>(
_ actualError: Error,
expectedError: T) -> Bool {
return actualError._domain == expectedError._domain
&& actualError._code == expectedError._code
}
// Non-generic
internal func setFailureMessageForError(
_ failureMessage: FailureMessage,
actualError: Error?,
closure: ((Error) -> Void)?) {
failureMessage.postfixMessage = "throw error"
if closure != nil {
failureMessage.postfixMessage += " that satisfies block"
} else {
failureMessage.postfixMessage = "throw any error"
}
if let actualError = actualError {
failureMessage.actualValue = "<\(actualError)>"
} else {
failureMessage.actualValue = "no error"
}
}
|
mit
|
4d5501623e8942120aa4345bff135bca
| 27.932203 | 73 | 0.637961 | 4.768156 | false | false | false | false |
hooman/swift
|
test/SILOptimizer/optionset.swift
|
12
|
1692
|
// RUN: %target-swift-frontend -parse-as-library -primary-file %s -O -sil-verify-all -module-name=test -emit-sil | %FileCheck %s
// RUN: %target-swift-frontend -parse-as-library -primary-file %s -Osize -sil-verify-all -module-name=test -emit-sil | %FileCheck %s
// REQUIRES: swift_stdlib_no_asserts,optimized_stdlib
public struct TestOptions: OptionSet {
public let rawValue: Int
public init(rawValue: Int) { self.rawValue = rawValue }
static let first = TestOptions(rawValue: 1 << 0)
static let second = TestOptions(rawValue: 1 << 1)
static let third = TestOptions(rawValue: 1 << 2)
static let fourth = TestOptions(rawValue: 1 << 3)
}
// CHECK-LABEL: sil_global hidden [let] @$s4test17globalTestOptionsAA0cD0Vvp : $TestOptions = {
// CHECK: [[CONST:%.*]] = integer_literal $Builtin.Int{{32|64}}, 15
// CHECK: [[INT:%.*]] = struct $Int (%0 : $Builtin.Int{{32|64}})
// CHECK: %initval = struct $TestOptions ([[INT]] : $Int)
let globalTestOptions: TestOptions = [.first, .second, .third, .fourth]
// CHECK-LABEL: sil @{{.*}}returnTestOptions{{.*}}
// CHECK-NEXT: bb0:
// CHECK-NEXT: builtin
// CHECK-NEXT: integer_literal {{.*}}, 15
// CHECK-NEXT: struct $Int
// CHECK: struct $TestOptions
// CHECK-NEXT: return
public func returnTestOptions() -> TestOptions {
return [.first, .second, .third, .fourth]
}
// CHECK-LABEL: sil @{{.*}}returnEmptyTestOptions{{.*}}
// CHECK-NEXT: bb0:
// CHECK-NEXT: integer_literal {{.*}}, 0
// CHECK-NEXT: struct $Int
// CHECK: builtin "onFastPath"() : $()
// CHECK-NEXT: struct $TestOptions
// CHECK-NEXT: return
public func returnEmptyTestOptions() -> TestOptions {
return []
}
|
apache-2.0
|
05460ab50b715a24e47e15c470a69ba9
| 40.268293 | 133 | 0.652482 | 3.390782 | false | true | false | false |
hhcszgd/GDRefreshControl
|
GDRefreshControl/code/GDRefreshControl.swift
|
1
|
61091
|
//
// GDRefreshControl.swift
// zjlao
//
// Created by WY on 28/04/2017.
// Copyright © 2017 com.16lao.zjlao. All rights reserved.
//
import UIKit
// MARK: 注释 : 加载结果
public enum GDRefreshResult {
case success
case failure
case networkError
}
//// MARK: 注释 : 刷新方式
//enum GDRefreshType {
// case manual//手动
// case auto//自动
//}
// MARK: 注释 : 刷新控件显示状态
enum GDShowStatus {
case idle
case pulling
case prepareRefreshing
case refreshing
case refreshed
case refreshSuccess
case backing
case refreshFailure
case netWorkError
}
// MARK: 注释 : 刷新控件当前状态
public enum GDRefreshStatus {
case idle
case pulling
case refreshing
case backing
}
// MARK: 注释 : 刷新控件的方向
public enum GDDirection {
case top
case left
case bottom
case right
}
public class GDRefreshControl: GDBaseControl {
public var refreshHeight : CGFloat = 88
public var pullingImages : [UIImage] = pullingImagesForRefresh(){
didSet{
}
}
public var refreshingImages : [UIImage] = refreshingImgs(){
didSet{
}
}
public var networkErrorImage : UIImage = networkErrorImageForRefresh(){
didSet{
}
}
public var successImage : UIImage = successImagesForRefresh(){
didSet{
}
}
public var failureImage : UIImage = failureImagesForRefresh(){
didSet{
}
}
public var pullingStr = "拖动以刷新"
public var loosenStr = "松开刷新"
public var refreshingStr = "刷新中"
public var successStr = "加载成功"
public var failureStr = "加载失败"
public var networkErrorStr = "网络错误"
var showStatus = GDShowStatus.idle
private weak var refreshTarget : AnyObject?
private var refreshAction : Selector?
public var refreshStatus = GDRefreshStatus.idle{
didSet{
if refreshStatus != GDRefreshStatus.refreshing { return }
if oldValue == refreshStatus {return}
switch self.direction {
case GDDirection.top:
let y = -(refreshHeight + originalContentInset.top) - 1.0 // 减 1 是为了满足触发刷新的条件
// self.setrefershStatusEndDrag(contentOffset:CGPoint(x: 0, y: y) )
self.performRefreshAfterSetRefreshingStatus(contentOffset: CGPoint(x: 0, y: y))
// if (self.scrollView?.contentOffset.y ?? 0) < -refreshHeight {//可以刷新
//
// }
break
case GDDirection.left:
if (self.scrollView?.contentOffset.x ?? 0 ) < -refreshHeight {//可以刷新
}
let x = -refreshHeight - 1.0
// self.setrefershStatusEndDrag(contentOffset:CGPoint(x: x, y: 0) )
self.performRefreshAfterSetRefreshingStatus(contentOffset: CGPoint(x: x, y: 0))
break
case GDDirection.bottom:
if (scrollView?.contentSize.height ?? 0) < (scrollView?.bounds.size.height ?? 0){
// if (scrollView?.contentOffset.y ?? 0) > refreshHeight { //可以刷新
//
//
// }
let y = refreshHeight + 1.0
// self.setrefershStatusEndDrag(contentOffset:CGPoint(x: 0, y: y))
self.performRefreshAfterSetRefreshingStatus(contentOffset: CGPoint(x: 0, y: y))
}else{
// if (self.scrollView?.contentOffset.y ?? 0 ) > (scrollView?.contentSize.height ?? 0) - (scrollView?.bounds.size.height ?? 0 ) + refreshHeight {//可以刷新
//
// }
let y = (scrollView?.contentSize.height ?? 0) - (scrollView?.bounds.size.height ?? 0 ) + refreshHeight + 1.0
// self.setrefershStatusEndDrag(contentOffset:CGPoint(x: 0, y: y) )
self.performRefreshAfterSetRefreshingStatus(contentOffset: CGPoint(x: 0, y: y))
}
break
case GDDirection.right:
if (scrollView?.contentSize.width ?? 0) < (scrollView?.bounds.size.width ?? 0){
let x = refreshHeight + 1
// self.setrefershStatusEndDrag(contentOffset:CGPoint(x:x, y: 0) )
self.performRefreshAfterSetRefreshingStatus(contentOffset: CGPoint(x: x, y: 0))
}else{
// if (self.scrollView?.contentOffset.x ?? 0) > (scrollView?.contentSize.width ?? 0) - (scrollView?.bounds.size.width ?? 0 ) + refreshHeight {//可以刷新
let x = (scrollView?.contentSize.width ?? 0) - (scrollView?.bounds.size.width ?? 0 ) + refreshHeight + 1
// self.setrefershStatusEndDrag(contentOffset:CGPoint(x:x, y: 0) )
self.performRefreshAfterSetRefreshingStatus(contentOffset: CGPoint(x: x, y: 0))
// }
}
break
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
self.titleLabel.textAlignment = NSTextAlignment.center
self.titleLabel.numberOfLines = 0
self.direction = GDDirection.top
}
public convenience init(target: AnyObject? , selector : Selector?) {
self.init(frame: CGRect.zero)
self.refreshTarget = target
self.refreshAction = selector
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override func scrollViewContentSizeChanged(){
if let scroll = self.scrollView {
mylog("监听contentSize : \(String(describing: scroll.contentSize))")
self.fixFrame(scrollView: scroll)//自动布局是 , scrollView的contentSize是动态变化的, 所以要实时调整加载控件的frame
}
}
public override func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
// MARK: 注释 a: 当用户拖动时 , 还原滚动控件的isPagingEnable
if scrollView.isPagingEnabled != self.originalIspagingEnable {
self.scrollView?.isPagingEnabled = self.originalIspagingEnable
}
}
public override func scrollViewDidEndDragging(_ scrollView: UIScrollView){
mylog("松手了 ,当前偏移量是\(scrollView.contentOffset)")
if self.refreshStatus != GDRefreshStatus.refreshing {
self.setrefershStatusEndDrag(contentOffset: scrollView.contentOffset)
}
}
func performRefreshAfterSetRefreshingStatus(contentOffset: CGPoint ) {//原计划松手驱动 , for避免重复刷新 , 换成refreshing状态驱动
var inset = UIEdgeInsets.zero
var isNeedRefresh = false
var tempContentOffset = CGPoint.zero
switch self.direction {
case GDDirection.top:
if contentOffset.y < -(refreshHeight + originalContentInset.top) {//可以刷新
inset.top = self.refreshHeight + originalContentInset.top
isNeedRefresh = true
tempContentOffset.y = -(refreshHeight + originalContentInset.top)
}
break
case GDDirection.left:
if contentOffset.x < -refreshHeight {//可以刷新
inset.left = self.refreshHeight
isNeedRefresh = true
tempContentOffset.x = -refreshHeight
}
break
case GDDirection.bottom:
if (scrollView?.contentSize.height ?? 0) < (scrollView?.bounds.size.height ?? 0){//可滚动区域少于滚动控件frame
if contentOffset.y > refreshHeight { //可以刷新
inset.bottom = self.refreshHeight + ((scrollView?.bounds.size.height ?? 0) - (scrollView?.contentSize.height ?? 0))
isNeedRefresh = true
tempContentOffset.y = refreshHeight
// self.scrollView?.setContentOffset(CGPoint(x: 0, y: self.refreshHeight), animated: true )//确保能执行刷新时,才调这句代码 . 否则会出现 偏移后不执行刷新
}
}else{
if contentOffset.y > (scrollView?.contentSize.height ?? 0) - (scrollView?.bounds.size.height ?? 0 ) + refreshHeight {//可以刷新
inset.bottom = self.refreshHeight
isNeedRefresh = true
tempContentOffset.y = (scrollView?.contentSize.height ?? 0) - (scrollView?.bounds.size.height ?? 0) + self.refreshHeight
// self.scrollView?.setContentOffset(CGPoint(x: 0, y: (scrollView?.contentSize.height ?? 0) - (scrollView?.bounds.size.height ?? 0) + self.refreshHeight ), animated: true )//确保能执行刷新时,才调这句代码 . 否则会出现 偏移后不执行刷新
}
}
break
case GDDirection.right:
if (scrollView?.contentSize.width ?? 0) < (scrollView?.bounds.size.width ?? 0){
if contentOffset.x > refreshHeight {//可以刷新
inset.right = self.refreshHeight + ((scrollView?.bounds.size.width ?? 0) - (scrollView?.contentSize.width ?? 0))
isNeedRefresh = true
tempContentOffset.x = self.refreshHeight
// self.scrollView?.setContentOffset(CGPoint(x: self.refreshHeight , y: 0), animated: true )
}
}else{
if contentOffset.x > (scrollView?.contentSize.width ?? 0) - (scrollView?.bounds.size.width ?? 0 ) + refreshHeight {//可以刷新
inset.right = self.refreshHeight
isNeedRefresh = true
tempContentOffset.x = (scrollView?.contentSize.width ?? 0) - (scrollView?.bounds.size.width ?? 0) + self.refreshHeight
// self.scrollView?.setContentOffset(CGPoint(x: (scrollView?.contentSize.width ?? 0) - (scrollView?.bounds.size.width ?? 0) + self.refreshHeight , y: 0), animated: true )//确保能执行刷新时,才调这句代码 . 否则会出现 偏移后不执行刷新
}
}
break
}
if isNeedRefresh {
// MARK: 注释 a: CollectionView的isPagingEnagle = true , 会影响contentInset的设置,不会发生预设的偏移 , 所以 , 设置contentInset之前, 设置为flase , 当用户拖动时再还原到用户设定的状态
UIView.animate(withDuration: 0.25, animations: {
self.scrollView?.contentInset = inset
self.scrollView?.contentOffset = tempContentOffset
}, completion: { (bool ) in
self.scrollView?.isPagingEnabled = false
self.performRefresh()
})
}
}
func setrefershStatusEndDrag(contentOffset: CGPoint ) {//原计划松手驱动 , for避免重复刷新 , 换成refreshing状态驱动
switch self.direction {
case GDDirection.top:
if contentOffset.y < -(refreshHeight + originalContentInset.top) {//可以刷新one
if self.refreshStatus != GDRefreshStatus.refreshing {
self.refreshStatus = .refreshing
return
}
}
break
case GDDirection.left:
if contentOffset.x < -refreshHeight {//可以刷新
if self.refreshStatus != GDRefreshStatus.refreshing {
self.refreshStatus = .refreshing
return
}
}
break
case GDDirection.bottom:
if (scrollView?.contentSize.height ?? 0) < (scrollView?.bounds.size.height ?? 0){//可滚动区域少于滚动控件frame
if contentOffset.y > refreshHeight { //可以刷新
if self.refreshStatus != GDRefreshStatus.refreshing {
self.refreshStatus = .refreshing
return
}
}
}else{
if contentOffset.y > (scrollView?.contentSize.height ?? 0) - (scrollView?.bounds.size.height ?? 0 ) + refreshHeight {//可以刷新
if self.refreshStatus != GDRefreshStatus.refreshing {
self.refreshStatus = .refreshing
return
}
}
}
break
case GDDirection.right:
if (scrollView?.contentSize.width ?? 0) < (scrollView?.bounds.size.width ?? 0){
if contentOffset.x > refreshHeight {//可以刷新
if self.refreshStatus != GDRefreshStatus.refreshing {
self.refreshStatus = .refreshing
return
}
}
}else{
if contentOffset.x > (scrollView?.contentSize.width ?? 0) - (scrollView?.bounds.size.width ?? 0 ) + refreshHeight {//可以刷新
if self.refreshStatus != GDRefreshStatus.refreshing {
self.refreshStatus = .refreshing
return
}
}
}
break
}
}
public override func scrollViewDidScroll(_ scrollView: UIScrollView) {
// mylog(newPoint)//下拉变小
// if let refresh = self.whetherCallRefreshDelegate(scrollView) {
// refresh.scrollViewDidScroll(scrollView)
// }
if self.refreshStatus != GDRefreshStatus.refreshing {
self.adjustContentInset(contentOffset: scrollView.contentOffset)
}
}
func adjustContentInset(contentOffset:CGPoint) {//实时更新图片和显示标签
if self.refreshStatus == GDRefreshStatus.refreshing {
return
}
// mylog(self.frame)
mylog(self.scrollView?.contentOffset)
mylog(self.direction)
var inset = UIEdgeInsets.zero
// var isNeedRefresh = false
switch self.direction {
case GDDirection.top:
var scale : CGFloat = 0
if contentOffset.y <= -originalContentInset.top && contentOffset.y >= -(refreshHeight + originalContentInset.top) {
scale = (-contentOffset.y - originalContentInset.top) / refreshHeight
mylog(scale)
}
mylog(originalContentInset)
mylog(contentOffset)
if contentOffset.y < -(refreshHeight + originalContentInset.top) {//可以刷新
inset.top = (refreshHeight + originalContentInset.top)
// isNeedRefresh = true
self.updateTextAndImage(showStatus: GDShowStatus.prepareRefreshing)
}else{//下拉以刷新
if contentOffset.y >= self.priviousContentOffset.y{//backing
self.updateTextAndImage(showStatus: GDShowStatus.pulling , actionType: GDShowStatus.backing , scale: scale)
}else{//pulling
self.updateTextAndImage(showStatus: GDShowStatus.pulling , actionType: GDShowStatus.pulling , scale: scale)
}
}
break
case GDDirection.left:
if contentOffset.x < -refreshHeight {//可以刷新
inset.left = self.refreshHeight
// isNeedRefresh = true
self.updateTextAndImage(showStatus: GDShowStatus.prepareRefreshing)
}else{//右拉以刷新
var scale : CGFloat = 0
if contentOffset.x <= 0 && contentOffset.x >= -refreshHeight {
scale = -contentOffset.x / refreshHeight
mylog(scale)
}
// self.updateTextAndImage(showStatus: GDShowStatus.pulling)
if contentOffset.x >= self.priviousContentOffset.x{//backing
self.updateTextAndImage(showStatus: GDShowStatus.pulling , actionType: GDShowStatus.backing , scale: scale)
// self.updateTextAndImage(showStatus: GDShowStatus.backing)
// mylog("回去")
}else{//pulling
self.updateTextAndImage(showStatus: GDShowStatus.pulling , actionType: GDShowStatus.pulling , scale: scale)
}
}
break
case GDDirection.bottom:
if (scrollView?.contentSize.height ?? 0) < (scrollView?.bounds.size.height ?? 0){
if contentOffset.y > refreshHeight { //可以刷新
self.updateTextAndImage(showStatus: GDShowStatus.prepareRefreshing)
mylog("松手可刷新")
inset.bottom = self.refreshHeight + ((scrollView?.bounds.size.height ?? 0) - (scrollView?.contentSize.height ?? 0))
// isNeedRefresh = true
}else{//上拉以刷新
var scale : CGFloat = 0
if contentOffset.y >= 0 && contentOffset.y <= refreshHeight {
scale = contentOffset.y / refreshHeight
mylog(scale)
}
if contentOffset.y <= self.priviousContentOffset.y{//backing
self.updateTextAndImage(showStatus: GDShowStatus.pulling , actionType: GDShowStatus.backing , scale: scale)
}else{//pulling
self.updateTextAndImage(showStatus: GDShowStatus.pulling , actionType: GDShowStatus.pulling, scale: scale)
mylog("上拉以刷新")
}
}
}else{
if contentOffset.y > (scrollView?.contentSize.height ?? 0) - (scrollView?.bounds.size.height ?? 0 ) + refreshHeight {//可以刷新
self.updateTextAndImage(showStatus: GDShowStatus.prepareRefreshing)
mylog("松手可刷新")
inset.bottom = self.refreshHeight
// isNeedRefresh = true
}else{//上拉以刷新
var scale : CGFloat = 0
if contentOffset.y <= (scrollView?.contentSize.height ?? 0) - (scrollView?.bounds.size.height ?? 0 ) + refreshHeight && contentOffset.y >= (scrollView?.contentSize.height ?? 0) - (scrollView?.bounds.size.height ?? 0 ) {
scale = (contentOffset.y - ((scrollView?.contentSize.height ?? 0) - (scrollView?.bounds.size.height ?? 0 ) ) ) / refreshHeight
mylog(scale)
}
if contentOffset.y <= self.priviousContentOffset.y{//backing
self.updateTextAndImage(showStatus: GDShowStatus.pulling , actionType: GDShowStatus.backing, scale: scale)
// self.updateTextAndImage(showStatus: GDShowStatus.backing)
// mylog("回去")
}else{//pulling
mylog("上拉以刷新")
self.updateTextAndImage(showStatus: GDShowStatus.pulling , actionType: GDShowStatus.pulling, scale: scale)
// self.updateTextAndImage(showStatus: GDShowStatus.pulling)
}
}
}
break
case GDDirection.right:
if (scrollView?.contentSize.width ?? 0) < (scrollView?.bounds.size.width ?? 0){
if contentOffset.x > refreshHeight {//可以刷新
self.updateTextAndImage(showStatus: GDShowStatus.prepareRefreshing)
mylog("松手可刷新")
inset.right = self.refreshHeight + ((scrollView?.bounds.size.width ?? 0) - (scrollView?.contentSize.width ?? 0))
// isNeedRefresh = true
}else{//左拉以刷新
mylog("左拉以刷新")
var scale : CGFloat = 0
if contentOffset.x >= 0 && contentOffset.x <= refreshHeight {
scale = contentOffset.x / refreshHeight
mylog(scale)
}
if contentOffset.x <= self.priviousContentOffset.x{//backing
self.updateTextAndImage(showStatus: GDShowStatus.pulling , actionType: GDShowStatus.backing , scale : scale )
// self.updateTextAndImage(showStatus: GDShowStatus.backing)
// mylog("回去")
}else{//pulling
self.updateTextAndImage(showStatus: GDShowStatus.pulling , actionType: GDShowStatus.pulling , scale : scale )
// self.updateTextAndImage(showStatus: GDShowStatus.pulling)
}
}
}else{
if contentOffset.x > (scrollView?.contentSize.width ?? 0) - (scrollView?.bounds.size.width ?? 0 ) + refreshHeight {//可以刷新
self.updateTextAndImage(showStatus: GDShowStatus.prepareRefreshing)
mylog("松手可刷新")
inset.right = self.refreshHeight
// isNeedRefresh = true
}else{//左拉以刷新
mylog("左拉以刷新")
var scale : CGFloat = 0
if contentOffset.x <= (scrollView?.contentSize.width ?? 0) - (scrollView?.bounds.size.width ?? 0 ) + refreshHeight && contentOffset.x >= (scrollView?.contentSize.width ?? 0) - (scrollView?.bounds.size.width ?? 0 ) {
scale = (contentOffset.x - ((scrollView?.contentSize.width ?? 0) - (scrollView?.bounds.size.width ?? 0 ) ) ) / refreshHeight
mylog(scale)
}
if contentOffset.x <= self.priviousContentOffset.x{//backing
self.updateTextAndImage(showStatus: GDShowStatus.pulling , actionType: GDShowStatus.backing , scale : scale )
// self.updateTextAndImage(showStatus: GDShowStatus.backing)
// mylog("回去")
}else{//pulling
self.updateTextAndImage(showStatus: GDShowStatus.pulling , actionType: GDShowStatus.pulling , scale : scale )
// self.updateTextAndImage(showStatus: GDShowStatus.pulling)
}
}
}
break
}
self.priviousContentOffset = contentOffset
}
}
// MARK: 注释 : control
extension GDRefreshControl {
func addTarget(_ target: Any?, refreshAction: Selector) {
self.refreshTarget = target as AnyObject
self.refreshAction = refreshAction
}
// func prepareRefresh(contentOffset : CGPoint) {
////
// }
func performRefresh() {//避免重复刷新TODO
mylog("开始刷新 偏移量\(String(describing: self.scrollView?.contentOffset))")
if let load = self.scrollView?.gdLoadControl {
load.loadStatus = GDLoadStatus.idle
}
self.updateTextAndImage(showStatus: GDShowStatus.refreshing , actionType: GDShowStatus.refreshing)
mylog(scrollView?.contentInset)
if self.refreshAction != nil && self.refreshTarget != nil {
_ = self.refreshTarget!.perform(self.refreshAction!)
}
}
/// call after reloadData(tableView)
///
/// - Parameter result: forExample : success , networkError or failure
public func endRefresh(result : GDRefreshResult = GDRefreshResult.success) {
if self.refreshStatus == GDRefreshStatus.refreshing {
mylog("结束刷新 偏移量\(String(describing: self.scrollView?.contentOffset))")
if result == GDRefreshResult.success {
self.updateTextAndImage(showStatus: GDShowStatus.refreshSuccess , actionType: GDShowStatus.refreshed)
}else if result == GDRefreshResult.failure{
self.updateTextAndImage(showStatus: GDShowStatus.refreshFailure , actionType: GDShowStatus.refreshed)
}else if result == GDRefreshResult.networkError{
self.updateTextAndImage(showStatus: GDShowStatus.netWorkError , actionType: GDShowStatus.refreshed)
}
if result == GDRefreshResult.success {
UIView.animate(withDuration: 0.25, animations: {
self.scrollView?.contentInset = self.originalContentInset
}, completion: { (bool ) in
self.refreshStatus = GDRefreshStatus.idle
})
// self.scrollView?.contentInset = originalContentInset
// self.scrollView?.contentInset = UIEdgeInsetsMake(0, 0, 0, 0)//不应该直接设置为0 , 应该记录原始contentInset , 刷新完毕以后重新把contentInset赋值回去
// self.refreshStatus = GDRefreshStatus.idle
}else{
UIView.animate(withDuration: 0.2, delay: 0.5, options: UIViewAnimationOptions.curveEaseInOut, animations: {
// self.scrollView?.contentInset = UIEdgeInsetsMake(0, 0, 0, 0)
self.scrollView?.contentInset = self.originalContentInset
}) { (bool) in
self.refreshStatus = GDRefreshStatus.idle
}
}
}
}
}
// MARK: 注释 : updateUI
extension GDRefreshControl {
func updateTextAndImage(showStatus : GDShowStatus , actionType : GDShowStatus = GDShowStatus.pulling/*拖动中还是弹回中*/,scale : CGFloat = 0) {
var title = ""
if self.imageView.isAnimating {
self.imageView.stopAnimating()
}
if showStatus == GDShowStatus.pulling && actionType == GDShowStatus.pulling {
//下拉以加载
title = pullingStr
let a : Int = Int(( CGFloat( self.pullingImages.count) * scale))
if a > 0 && a < self.pullingImages.count {
self.imageView.image = self.pullingImages[a]
}
}else if showStatus == GDShowStatus.pulling && actionType == GDShowStatus.backing && self.refreshStatus != GDRefreshStatus.refreshing{
//下拉以加载
title = pullingStr
let a : Int = Int(( CGFloat( self.pullingImages.count) * scale))
if a > 0 && a < self.pullingImages.count {
self.imageView.image = self.pullingImages[a]
}
}else if showStatus == GDShowStatus.prepareRefreshing {
title = loosenStr
//松手以刷新
}else if showStatus == GDShowStatus.refreshing && actionType == GDShowStatus.refreshing{
title = refreshingStr
self.imageView.animationImages = self.refreshingImages
self.imageView.animationDuration = 0.5
self.imageView.animationRepeatCount = 19
self.imageView.startAnimating()
//刷新中
}else if showStatus == GDShowStatus.refreshSuccess && actionType == GDShowStatus.refreshed{
title = successStr
self.imageView.image = self.successImage
//刷新成功
}else if showStatus == GDShowStatus.refreshFailure && actionType == GDShowStatus.refreshed{
title = failureStr
self.imageView.image = self.failureImage
//刷新失败
}else if showStatus == GDShowStatus.netWorkError && actionType == GDShowStatus.refreshed{
title = networkErrorStr
self.imageView.image = self.networkErrorImage
//网络错误
}
let attributeTitle = NSMutableAttributedString.init(string: title)
// str.addAttribute(kCTVerticalFormsAttributeName as String, value: true , range:NSMakeRange(0, title.characters.count))
// str.addAttribute(NSVerticalGlyphFormAttributeName as String, value: NSNumber.init(value: 1) , range:NSMakeRange(0, title.characters.count))
self.titleLabel.attributedText = attributeTitle
self.showStatus = showStatus
}
func fixFrame(scrollView : UIScrollView) {
switch self.direction {
case GDDirection.top:
self.frame = CGRect(x: 0, y: -refreshHeight, width: scrollView.bounds.size.width, height: refreshHeight)
if self.labelFrame == CGRect.zero {
self.titleLabel.frame = CGRect(x: 0, y: self.bounds.size.height * 0.5, width: self.bounds.size.width, height: self.titleLabel.font.lineHeight)
}else{
self.titleLabel.frame = self.labelFrame
}
if self.imageViewFrame == CGRect.zero {
self.imageView.frame = CGRect(x: 10, y: self.bounds.size.height * 0.1, width: self.bounds.size.height * 0.8, height: self.bounds.size.height * 0.8)
}else{
self.imageView.frame = self.imageViewFrame
}
break
case GDDirection.left:
self.frame = CGRect(x: -refreshHeight, y: 0, width: refreshHeight, height: scrollView.bounds.size.height)
if self.labelFrame == CGRect.zero {
self.titleLabel.frame = CGRect(x: self.bounds.size.width * 0.5, y: 0, width: self.titleLabel.font.lineHeight, height: self.bounds.size.height)
}else{
self.titleLabel.frame = self.labelFrame
}
if self.imageViewFrame == CGRect.zero {
self.imageView.frame = CGRect(x: self.bounds.size.width * 0.1, y: 10, width: self.bounds.size.width * 0.8, height: self.bounds.size.width * 0.8)
}else{
self.imageView.frame = self.imageViewFrame
}
break
case GDDirection.bottom:
if scrollView.contentSize.height < scrollView.bounds.size.height{
self.frame = CGRect(x: 0, y: scrollView.bounds.size.height, width:scrollView.bounds.size.width , height: refreshHeight)
}else{
self.frame = CGRect(x: 0, y: scrollView.contentSize.height , width:scrollView.bounds.size.width , height: refreshHeight)
}
if self.labelFrame == CGRect.zero {
self.titleLabel.frame = CGRect(x: 0, y: self.bounds.size.height * 0.4, width: self.bounds.size.width, height: self.titleLabel.font.lineHeight)
}else{
self.titleLabel.frame = self.labelFrame
}
if self.imageViewFrame == CGRect.zero {
self.imageView.frame = CGRect(x: 10, y: self.bounds.size.height * 0.1, width: self.bounds.size.height * 0.8, height: self.bounds.size.height * 0.8)
}else{
self.imageView.frame = self.imageViewFrame
}
break
case GDDirection.right:
if scrollView.contentSize.width < scrollView.bounds.size.width{
self.frame = CGRect(x: scrollView.bounds.size.width, y: 0, width: refreshHeight , height: scrollView.bounds.size.height )
}else{
self.frame = CGRect(x: scrollView.contentSize.width, y: 0, width: refreshHeight, height: scrollView.bounds.size.height)
}
if self.labelFrame == CGRect.zero {
self.titleLabel.frame = CGRect(x: self.bounds.size.width * 0.4, y: 0, width: self.titleLabel.font.lineHeight, height: self.bounds.size.height)
}else{
self.titleLabel.frame = self.labelFrame
}
if self.imageViewFrame == CGRect.zero{
self.imageView.frame = CGRect(x: self.bounds.size.width * 0.1, y: 10, width: self.bounds.size.width * 0.8, height: self.bounds.size.width * 0.8)
}else{
self.imageView.frame = self.imageViewFrame
}
break
}
}
}
// MARK: 注释 : KVO
/*
extension GDRefreshControl{
public override func scrollViewContentSizeChanged(){
if let scroll = self.scrollView {
mylog("监听contentSize : \(String(describing: scroll.contentSize))")
self.fixFrame(scrollView: scroll)//自动布局是 , scrollView的contentSize是动态变化的, 所以要实时调整加载控件的frame
}
}
public override func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
// MARK: 注释 a: 当用户拖动时 , 还原滚动控件的isPagingEnable
if scrollView.isPagingEnabled != self.originalIspagingEnable {
self.scrollView?.isPagingEnabled = self.originalIspagingEnable
}
}
public override func scrollViewDidEndDragging(_ scrollView: UIScrollView){
mylog("松手了 ,当前偏移量是\(scrollView.contentOffset)")
if self.refreshStatus != GDRefreshStatus.refreshing {
self.setrefershStatusEndDrag(contentOffset: scrollView.contentOffset)
}
}
func performRefreshAfterSetRefreshingStatus(contentOffset: CGPoint ) {//原计划松手驱动 , for避免重复刷新 , 换成refreshing状态驱动
var inset = UIEdgeInsets.zero
var isNeedRefresh = false
var tempContentOffset = CGPoint.zero
switch self.direction {
case GDDirection.top:
if contentOffset.y < -(refreshHeight + originalContentInset.top) {//可以刷新
inset.top = self.refreshHeight + originalContentInset.top
isNeedRefresh = true
tempContentOffset.y = -(refreshHeight + originalContentInset.top)
}
break
case GDDirection.left:
if contentOffset.x < -refreshHeight {//可以刷新
inset.left = self.refreshHeight
isNeedRefresh = true
tempContentOffset.x = -refreshHeight
}
break
case GDDirection.bottom:
if (scrollView?.contentSize.height ?? 0) < (scrollView?.bounds.size.height ?? 0){//可滚动区域少于滚动控件frame
if contentOffset.y > refreshHeight { //可以刷新
inset.bottom = self.refreshHeight + ((scrollView?.bounds.size.height ?? 0) - (scrollView?.contentSize.height ?? 0))
isNeedRefresh = true
tempContentOffset.y = refreshHeight
// self.scrollView?.setContentOffset(CGPoint(x: 0, y: self.refreshHeight), animated: true )//确保能执行刷新时,才调这句代码 . 否则会出现 偏移后不执行刷新
}
}else{
if contentOffset.y > (scrollView?.contentSize.height ?? 0) - (scrollView?.bounds.size.height ?? 0 ) + refreshHeight {//可以刷新
inset.bottom = self.refreshHeight
isNeedRefresh = true
tempContentOffset.y = (scrollView?.contentSize.height ?? 0) - (scrollView?.bounds.size.height ?? 0) + self.refreshHeight
// self.scrollView?.setContentOffset(CGPoint(x: 0, y: (scrollView?.contentSize.height ?? 0) - (scrollView?.bounds.size.height ?? 0) + self.refreshHeight ), animated: true )//确保能执行刷新时,才调这句代码 . 否则会出现 偏移后不执行刷新
}
}
break
case GDDirection.right:
if (scrollView?.contentSize.width ?? 0) < (scrollView?.bounds.size.width ?? 0){
if contentOffset.x > refreshHeight {//可以刷新
inset.right = self.refreshHeight + ((scrollView?.bounds.size.width ?? 0) - (scrollView?.contentSize.width ?? 0))
isNeedRefresh = true
tempContentOffset.x = self.refreshHeight
// self.scrollView?.setContentOffset(CGPoint(x: self.refreshHeight , y: 0), animated: true )
}
}else{
if contentOffset.x > (scrollView?.contentSize.width ?? 0) - (scrollView?.bounds.size.width ?? 0 ) + refreshHeight {//可以刷新
inset.right = self.refreshHeight
isNeedRefresh = true
tempContentOffset.x = (scrollView?.contentSize.width ?? 0) - (scrollView?.bounds.size.width ?? 0) + self.refreshHeight
// self.scrollView?.setContentOffset(CGPoint(x: (scrollView?.contentSize.width ?? 0) - (scrollView?.bounds.size.width ?? 0) + self.refreshHeight , y: 0), animated: true )//确保能执行刷新时,才调这句代码 . 否则会出现 偏移后不执行刷新
}
}
break
}
if isNeedRefresh {
// MARK: 注释 a: CollectionView的isPagingEnagle = true , 会影响contentInset的设置,不会发生预设的偏移 , 所以 , 设置contentInset之前, 设置为flase , 当用户拖动时再还原到用户设定的状态
UIView.animate(withDuration: 0.25, animations: {
self.scrollView?.contentInset = inset
self.scrollView?.contentOffset = tempContentOffset
}, completion: { (bool ) in
self.scrollView?.isPagingEnabled = false
self.performRefresh()
})
}
}
func setrefershStatusEndDrag(contentOffset: CGPoint ) {//原计划松手驱动 , for避免重复刷新 , 换成refreshing状态驱动
switch self.direction {
case GDDirection.top:
if contentOffset.y < -(refreshHeight + originalContentInset.top) {//可以刷新one
if self.refreshStatus != GDRefreshStatus.refreshing {
self.refreshStatus = .refreshing
return
}
}
break
case GDDirection.left:
if contentOffset.x < -refreshHeight {//可以刷新
if self.refreshStatus != GDRefreshStatus.refreshing {
self.refreshStatus = .refreshing
return
}
}
break
case GDDirection.bottom:
if (scrollView?.contentSize.height ?? 0) < (scrollView?.bounds.size.height ?? 0){//可滚动区域少于滚动控件frame
if contentOffset.y > refreshHeight { //可以刷新
if self.refreshStatus != GDRefreshStatus.refreshing {
self.refreshStatus = .refreshing
return
}
}
}else{
if contentOffset.y > (scrollView?.contentSize.height ?? 0) - (scrollView?.bounds.size.height ?? 0 ) + refreshHeight {//可以刷新
if self.refreshStatus != GDRefreshStatus.refreshing {
self.refreshStatus = .refreshing
return
}
}
}
break
case GDDirection.right:
if (scrollView?.contentSize.width ?? 0) < (scrollView?.bounds.size.width ?? 0){
if contentOffset.x > refreshHeight {//可以刷新
if self.refreshStatus != GDRefreshStatus.refreshing {
self.refreshStatus = .refreshing
return
}
}
}else{
if contentOffset.x > (scrollView?.contentSize.width ?? 0) - (scrollView?.bounds.size.width ?? 0 ) + refreshHeight {//可以刷新
if self.refreshStatus != GDRefreshStatus.refreshing {
self.refreshStatus = .refreshing
return
}
}
}
break
}
}
public override func scrollViewDidScroll(_ scrollView: UIScrollView) {
// mylog(newPoint)//下拉变小
// if let refresh = self.whetherCallRefreshDelegate(scrollView) {
// refresh.scrollViewDidScroll(scrollView)
// }
if self.refreshStatus != GDRefreshStatus.refreshing {
self.adjustContentInset(contentOffset: scrollView.contentOffset)
}
}
func adjustContentInset(contentOffset:CGPoint) {//实时更新图片和显示标签
if self.refreshStatus == GDRefreshStatus.refreshing {
return
}
// mylog(self.frame)
mylog(self.scrollView?.contentOffset)
mylog(self.direction)
var inset = UIEdgeInsets.zero
// var isNeedRefresh = false
switch self.direction {
case GDDirection.top:
var scale : CGFloat = 0
if contentOffset.y <= -originalContentInset.top && contentOffset.y >= -(refreshHeight + originalContentInset.top) {
scale = (-contentOffset.y - originalContentInset.top) / refreshHeight
mylog(scale)
}
mylog(originalContentInset)
mylog(contentOffset)
if contentOffset.y < -(refreshHeight + originalContentInset.top) {//可以刷新
inset.top = (refreshHeight + originalContentInset.top)
// isNeedRefresh = true
self.updateTextAndImage(showStatus: GDShowStatus.prepareRefreshing)
}else{//下拉以刷新
if contentOffset.y >= self.priviousContentOffset.y{//backing
self.updateTextAndImage(showStatus: GDShowStatus.pulling , actionType: GDShowStatus.backing , scale: scale)
}else{//pulling
self.updateTextAndImage(showStatus: GDShowStatus.pulling , actionType: GDShowStatus.pulling , scale: scale)
}
}
break
case GDDirection.left:
if contentOffset.x < -refreshHeight {//可以刷新
inset.left = self.refreshHeight
// isNeedRefresh = true
self.updateTextAndImage(showStatus: GDShowStatus.prepareRefreshing)
}else{//右拉以刷新
var scale : CGFloat = 0
if contentOffset.x <= 0 && contentOffset.x >= -refreshHeight {
scale = -contentOffset.x / refreshHeight
mylog(scale)
}
// self.updateTextAndImage(showStatus: GDShowStatus.pulling)
if contentOffset.x >= self.priviousContentOffset.x{//backing
self.updateTextAndImage(showStatus: GDShowStatus.pulling , actionType: GDShowStatus.backing , scale: scale)
// self.updateTextAndImage(showStatus: GDShowStatus.backing)
// mylog("回去")
}else{//pulling
self.updateTextAndImage(showStatus: GDShowStatus.pulling , actionType: GDShowStatus.pulling , scale: scale)
}
}
break
case GDDirection.bottom:
if (scrollView?.contentSize.height ?? 0) < (scrollView?.bounds.size.height ?? 0){
if contentOffset.y > refreshHeight { //可以刷新
self.updateTextAndImage(showStatus: GDShowStatus.prepareRefreshing)
mylog("松手可刷新")
inset.bottom = self.refreshHeight + ((scrollView?.bounds.size.height ?? 0) - (scrollView?.contentSize.height ?? 0))
// isNeedRefresh = true
}else{//上拉以刷新
var scale : CGFloat = 0
if contentOffset.y >= 0 && contentOffset.y <= refreshHeight {
scale = contentOffset.y / refreshHeight
mylog(scale)
}
if contentOffset.y <= self.priviousContentOffset.y{//backing
self.updateTextAndImage(showStatus: GDShowStatus.pulling , actionType: GDShowStatus.backing , scale: scale)
}else{//pulling
self.updateTextAndImage(showStatus: GDShowStatus.pulling , actionType: GDShowStatus.pulling, scale: scale)
mylog("上拉以刷新")
}
}
}else{
if contentOffset.y > (scrollView?.contentSize.height ?? 0) - (scrollView?.bounds.size.height ?? 0 ) + refreshHeight {//可以刷新
self.updateTextAndImage(showStatus: GDShowStatus.prepareRefreshing)
mylog("松手可刷新")
inset.bottom = self.refreshHeight
// isNeedRefresh = true
}else{//上拉以刷新
var scale : CGFloat = 0
if contentOffset.y <= (scrollView?.contentSize.height ?? 0) - (scrollView?.bounds.size.height ?? 0 ) + refreshHeight && contentOffset.y >= (scrollView?.contentSize.height ?? 0) - (scrollView?.bounds.size.height ?? 0 ) {
scale = (contentOffset.y - ((scrollView?.contentSize.height ?? 0) - (scrollView?.bounds.size.height ?? 0 ) ) ) / refreshHeight
mylog(scale)
}
if contentOffset.y <= self.priviousContentOffset.y{//backing
self.updateTextAndImage(showStatus: GDShowStatus.pulling , actionType: GDShowStatus.backing, scale: scale)
// self.updateTextAndImage(showStatus: GDShowStatus.backing)
// mylog("回去")
}else{//pulling
mylog("上拉以刷新")
self.updateTextAndImage(showStatus: GDShowStatus.pulling , actionType: GDShowStatus.pulling, scale: scale)
// self.updateTextAndImage(showStatus: GDShowStatus.pulling)
}
}
}
break
case GDDirection.right:
if (scrollView?.contentSize.width ?? 0) < (scrollView?.bounds.size.width ?? 0){
if contentOffset.x > refreshHeight {//可以刷新
self.updateTextAndImage(showStatus: GDShowStatus.prepareRefreshing)
mylog("松手可刷新")
inset.right = self.refreshHeight + ((scrollView?.bounds.size.width ?? 0) - (scrollView?.contentSize.width ?? 0))
// isNeedRefresh = true
}else{//左拉以刷新
mylog("左拉以刷新")
var scale : CGFloat = 0
if contentOffset.x >= 0 && contentOffset.x <= refreshHeight {
scale = contentOffset.x / refreshHeight
mylog(scale)
}
if contentOffset.x <= self.priviousContentOffset.x{//backing
self.updateTextAndImage(showStatus: GDShowStatus.pulling , actionType: GDShowStatus.backing , scale : scale )
// self.updateTextAndImage(showStatus: GDShowStatus.backing)
// mylog("回去")
}else{//pulling
self.updateTextAndImage(showStatus: GDShowStatus.pulling , actionType: GDShowStatus.pulling , scale : scale )
// self.updateTextAndImage(showStatus: GDShowStatus.pulling)
}
}
}else{
if contentOffset.x > (scrollView?.contentSize.width ?? 0) - (scrollView?.bounds.size.width ?? 0 ) + refreshHeight {//可以刷新
self.updateTextAndImage(showStatus: GDShowStatus.prepareRefreshing)
mylog("松手可刷新")
inset.right = self.refreshHeight
// isNeedRefresh = true
}else{//左拉以刷新
mylog("左拉以刷新")
var scale : CGFloat = 0
if contentOffset.x <= (scrollView?.contentSize.width ?? 0) - (scrollView?.bounds.size.width ?? 0 ) + refreshHeight && contentOffset.x >= (scrollView?.contentSize.width ?? 0) - (scrollView?.bounds.size.width ?? 0 ) {
scale = (contentOffset.x - ((scrollView?.contentSize.width ?? 0) - (scrollView?.bounds.size.width ?? 0 ) ) ) / refreshHeight
mylog(scale)
}
if contentOffset.x <= self.priviousContentOffset.x{//backing
self.updateTextAndImage(showStatus: GDShowStatus.pulling , actionType: GDShowStatus.backing , scale : scale )
// self.updateTextAndImage(showStatus: GDShowStatus.backing)
// mylog("回去")
}else{//pulling
self.updateTextAndImage(showStatus: GDShowStatus.pulling , actionType: GDShowStatus.pulling , scale : scale )
// self.updateTextAndImage(showStatus: GDShowStatus.pulling)
}
}
}
break
}
self.priviousContentOffset = contentOffset
}
}
*/
public extension UIScrollView{
static var gdRefreshControl: Void?
/** 刷新控件 */
@IBInspectable var gdRefreshControl: GDRefreshControl? {
get {
return objc_getAssociatedObject(self, &UIScrollView.gdRefreshControl) as? GDRefreshControl
}
set(newValue) {
gdRefreshControl?.removeFromSuperview()
self.addSubview(newValue!)
objc_setAssociatedObject(self, &UIScrollView.gdRefreshControl, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
/**
func adjustContentInset(contentOffset:CGPoint) {
var inset = UIEdgeInsets.zero
var isNeedRefresh = false
switch self.direction {
case GDDirection.top:
if contentOffset.y < -refreshHeight {//可以刷新
inset.top = self.refreshHeight
isNeedRefresh = true
self.updateTextAndImage(showStatus: GDShowStatus.prepareRefreshing)
}else{//下拉以刷新
self.updateTextAndImage(showStatus: GDShowStatus.pulling)
}
break
case GDDirection.left:
if contentOffset.x < -refreshHeight {//可以刷新
inset.left = self.refreshHeight
isNeedRefresh = true
self.updateTextAndImage(showStatus: GDShowStatus.prepareRefreshing)
}else{//右拉以刷新
self.updateTextAndImage(showStatus: GDShowStatus.pulling)
}
break
case GDDirection.bottom:
if (scrollView?.contentSize.height ?? 0) < (scrollView?.bounds.size.height ?? 0){
if contentOffset.y > refreshHeight { //可以刷新
self.updateTextAndImage(showStatus: GDShowStatus.prepareRefreshing)
mylog("松手可刷新")
inset.bottom = self.refreshHeight + ((scrollView?.bounds.size.height ?? 0) - (scrollView?.contentSize.height ?? 0))
isNeedRefresh = true
}else{//上拉以刷新
mylog("上拉以刷新")
self.updateTextAndImage(showStatus: GDShowStatus.pulling)
}
}else{
if contentOffset.y > (scrollView?.contentSize.height ?? 0) - (scrollView?.bounds.size.height ?? 0 ) + refreshHeight {//可以刷新
self.updateTextAndImage(showStatus: GDShowStatus.prepareRefreshing)
mylog("松手可刷新")
inset.bottom = self.refreshHeight
isNeedRefresh = true
}else{//上拉以刷新
mylog("上拉以刷新")
self.updateTextAndImage(showStatus: GDShowStatus.pulling)
}
}
break
case GDDirection.right:
if (scrollView?.contentSize.width ?? 0) < (scrollView?.bounds.size.width ?? 0){
if contentOffset.x > refreshHeight {//可以刷新
self.updateTextAndImage(showStatus: GDShowStatus.prepareRefreshing)
mylog("松手可刷新")
inset.right = self.refreshHeight + ((scrollView?.bounds.size.width ?? 0) - (scrollView?.contentSize.width ?? 0))
isNeedRefresh = true
}else{//左拉以刷新
mylog("左拉以刷新")
self.updateTextAndImage(showStatus: GDShowStatus.pulling)
}
}else{
if contentOffset.x > (scrollView?.contentSize.width ?? 0) - (scrollView?.bounds.size.width ?? 0 ) + refreshHeight {//可以刷新
self.updateTextAndImage(showStatus: GDShowStatus.prepareRefreshing)
mylog("松手可刷新")
inset.right = self.refreshHeight
isNeedRefresh = true
}else{//左拉以刷新
mylog("左拉以刷新")
self.updateTextAndImage(showStatus: GDShowStatus.pulling)
}
}
break
}
mylog(scrollView?.contentSize.height)
mylog(scrollView?.bounds.size.height)
mylog(contentOffset.y)
mylog((scrollView?.contentSize.height ?? 0) - (scrollView?.bounds.size.height ?? 0 ) + refreshHeight)
if isNeedRefresh {
// MARK: 注释 a: CollectionView的isPagingEnagle = true , 会影响contentInset的设置,不会发生预设的偏移 , 所以 , 设置contentInset之前, 设置为flase , 当用户拖动时再还原到用户设定的状态
self.scrollView?.isPagingEnabled = false
UIView.animate(withDuration: 0.25, animations: {
self.scrollView?.contentInset = inset
}, completion: { (true ) in
self.performRefresh()
})
}
}
*/
/*
func setrefershStatusEndDrag(contentOffset: CGPoint ) {//原计划松手驱动 , for避免重复刷新 , 换成refreshing状态驱动
var inset = UIEdgeInsets.zero
var isNeedRefresh = false
switch self.direction {
case GDDirection.top:
if contentOffset.y < -refreshHeight {//可以刷新
if self.refreshStatus != GDRefreshStatus.refreshing {
self.refreshStatus = .refreshing
return
}
inset.top = self.refreshHeight
isNeedRefresh = true
self.scrollView?.setContentOffset(CGPoint.zero, animated: true )
}
break
case GDDirection.left:
if contentOffset.x < -refreshHeight {//可以刷新
if self.refreshStatus != GDRefreshStatus.refreshing {
self.refreshStatus = .refreshing
return
}
inset.left = self.refreshHeight
isNeedRefresh = true
self.scrollView?.setContentOffset(CGPoint.zero, animated: true )
}
break
case GDDirection.bottom:
if (scrollView?.contentSize.height ?? 0) < (scrollView?.bounds.size.height ?? 0){//可滚动区域少于滚动控件frame
if contentOffset.y > refreshHeight { //可以刷新
if self.refreshStatus != GDRefreshStatus.refreshing {
self.refreshStatus = .refreshing
return
}
inset.bottom = self.refreshHeight + ((scrollView?.bounds.size.height ?? 0) - (scrollView?.contentSize.height ?? 0))
isNeedRefresh = true
self.scrollView?.setContentOffset(CGPoint(x: 0, y: self.refreshHeight), animated: true )//确保能执行刷新时,才调这句代码 . 否则会出现 偏移后不执行刷新
}
}else{
if contentOffset.y > (scrollView?.contentSize.height ?? 0) - (scrollView?.bounds.size.height ?? 0 ) + refreshHeight {//可以刷新
if self.refreshStatus != GDRefreshStatus.refreshing {
self.refreshStatus = .refreshing
return
}
inset.bottom = self.refreshHeight
isNeedRefresh = true
self.scrollView?.setContentOffset(CGPoint(x: 0, y: (scrollView?.contentSize.height ?? 0) - (scrollView?.bounds.size.height ?? 0) + self.refreshHeight ), animated: true )//确保能执行刷新时,才调这句代码 . 否则会出现 偏移后不执行刷新
}
}
// if refreshType == GDRefreshType.auto {
// }
break
case GDDirection.right:
if (scrollView?.contentSize.width ?? 0) < (scrollView?.bounds.size.width ?? 0){
if contentOffset.x > refreshHeight {//可以刷新
if self.refreshStatus != GDRefreshStatus.refreshing {
self.refreshStatus = .refreshing
return
}
inset.right = self.refreshHeight + ((scrollView?.bounds.size.width ?? 0) - (scrollView?.contentSize.width ?? 0))
isNeedRefresh = true
self.scrollView?.setContentOffset(CGPoint(x: self.refreshHeight , y: 0), animated: true )
}
}else{
if contentOffset.x > (scrollView?.contentSize.width ?? 0) - (scrollView?.bounds.size.width ?? 0 ) + refreshHeight {//可以刷新
if self.refreshStatus != GDRefreshStatus.refreshing {
self.refreshStatus = .refreshing
return
}
inset.right = self.refreshHeight
isNeedRefresh = true
self.scrollView?.setContentOffset(CGPoint(x: (scrollView?.contentSize.width ?? 0) - (scrollView?.bounds.size.width ?? 0) + self.refreshHeight , y: 0), animated: true )//确保能执行刷新时,才调这句代码 . 否则会出现 偏移后不执行刷新
}
}
// if refreshType == GDRefreshType.auto {
//
// }
break
}
return
if isNeedRefresh {
// MARK: 注释 a: CollectionView的isPagingEnagle = true , 会影响contentInset的设置,不会发生预设的偏移 , 所以 , 设置contentInset之前, 设置为flase , 当用户拖动时再还原到用户设定的状态
self.scrollView?.isPagingEnabled = false
// if self.direction == GDDirection.bottom {
// self.scrollView?.setContentOffset(CGPoint(x: 0, y: refreshHeight ), animated: true )
// }
UIView.animate(withDuration: 0.25, animations: {
self.scrollView?.contentInset = inset
}, completion: { (true ) in
self.performRefresh()
})
}
}
*/
|
mit
|
7cc95b8dbbacd332f1c3e10c6d115623
| 41.119597 | 247 | 0.540026 | 4.858069 | false | false | false | false |
craftsmanship-toledo/katangapp-ios
|
Katanga/Extensions/3rdparty/ActivityIndicator.swift
|
1
|
2247
|
//
// ActivityIndicator.swift
// RxExample
//
// Created by Krunoslav Zaher on 10/18/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if !RX_NO_MODULE
import RxCocoa
import RxSwift
#endif
private struct ActivityToken<E> : ObservableConvertibleType, Disposable {
private let _source: Observable<E>
private let _dispose: Cancelable
init(source: Observable<E>, disposeAction: @escaping () -> Void) {
_source = source
_dispose = Disposables.create(with: disposeAction)
}
func dispose() {
_dispose.dispose()
}
func asObservable() -> Observable<E> {
return _source
}
}
/**
Enables monitoring of sequence computation.
If there is at least one sequence computation in progress, `true` will be sent.
When all activities complete `false` will be sent.
*/
public class ActivityIndicator: SharedSequenceConvertibleType {
public typealias E = Bool
public typealias SharingStrategy = DriverSharingStrategy
private let _loading: SharedSequence<SharingStrategy, Bool>
private let _lock = NSRecursiveLock()
private let _variable = Variable(0)
public func asSharedSequence() -> SharedSequence<SharingStrategy, E> {
return _loading
}
public init() {
_loading = _variable.asDriver()
.map { $0 > 0 }
.distinctUntilChanged()
}
private func increment() {
_lock.lock()
_variable.value = _variable.value + 1
_lock.unlock()
}
private func decrement() {
_lock.lock()
_variable.value = _variable.value - 1
_lock.unlock()
}
fileprivate func trackActivityOfObservable<O: ObservableConvertibleType>(_ source: O) -> Observable<O.E> {
return Observable.using({ () -> ActivityToken<O.E> in
self.increment()
return ActivityToken(source: source.asObservable(), disposeAction: self.decrement)
}) { t in
return t.asObservable()
}
}
}
public extension ObservableConvertibleType {
public func trackActivity(_ activityIndicator: ActivityIndicator) -> Observable<E> {
return activityIndicator.trackActivityOfObservable(self)
}
}
|
apache-2.0
|
2ac7c9f8f99bb4fe6cc6f5cf876f4e9f
| 24.235955 | 110 | 0.650935 | 4.679167 | false | false | false | false |
mlavergn/swiftutil
|
Sources/device.swift
|
1
|
1477
|
/// Device struct with hardware related helpers
///
/// - author: Marc Lavergne <[email protected]>
/// - copyright: 2017 Marc Lavergne. All rights reserved.
/// - license: MIT
import Foundation
#if os(iOS) || os(tvOS)
import UIKit
#else
import IOKit
#endif
public enum DeviceOS: Int {
case iOS = 0
case macOS
case watchOS
case tvOS
case other
}
// MARK: - Device struct
public struct Device {
/// Device unique identifier as a String
public static var deviceId: String {
Log.stamp()
var id: String = ""
#if os(iOS) || os(tvOS)
if let serial = UIDevice.current.identifierForVendor?.uuidString {
id = serial
}
#else
let platformExpert = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IOPlatformExpertDevice") )
if let serial = (IORegistryEntryCreateCFProperty(platformExpert, kIOPlatformSerialNumberKey as CFString, kCFAllocatorDefault, 0).takeUnretainedValue() as? String) {
id = serial
}
IOObjectRelease(platformExpert)
#endif
return id
}
/// Device name as a String
public static var name: String {
#if os(iOS) || os(tvOS)
return UIDevice.current.name
#else
guard let name = Host.current().localizedName else {
return ""
}
return name
#endif
}
/// OS as a DeviceOS enum
public static var os: DeviceOS {
#if os(iOS)
return .iOS
#elseif os(macOS)
return .macOS
#elseif os(watchOS)
return .watchOS
#elseif os(tvOS)
return .tvOS
#else
return .other
#endif
}
}
|
mit
|
0ba303ffe9d85a0517247df03ff49fd5
| 19.802817 | 166 | 0.700068 | 3.341629 | false | false | false | false |
benlangmuir/swift
|
stdlib/public/core/CollectionAlgorithms.swift
|
9
|
21666
|
//===--- CollectionAlgorithms.swift ---------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// last
//===----------------------------------------------------------------------===//
extension BidirectionalCollection {
/// The last element of the collection.
///
/// If the collection is empty, the value of this property is `nil`.
///
/// let numbers = [10, 20, 30, 40, 50]
/// if let lastNumber = numbers.last {
/// print(lastNumber)
/// }
/// // Prints "50"
///
/// - Complexity: O(1)
@inlinable
public var last: Element? {
return isEmpty ? nil : self[index(before: endIndex)]
}
}
//===----------------------------------------------------------------------===//
// firstIndex(of:)/firstIndex(where:)
//===----------------------------------------------------------------------===//
extension Collection where Element: Equatable {
/// Returns the first index where the specified value appears in the
/// collection.
///
/// After using `firstIndex(of:)` to find the position of a particular element
/// in a collection, you can use it to access the element by subscripting.
/// This example shows how you can modify one of the names in an array of
/// students.
///
/// var students = ["Ben", "Ivy", "Jordell", "Maxime"]
/// if let i = students.firstIndex(of: "Maxime") {
/// students[i] = "Max"
/// }
/// print(students)
/// // Prints "["Ben", "Ivy", "Jordell", "Max"]"
///
/// - Parameter element: An element to search for in the collection.
/// - Returns: The first index where `element` is found. If `element` is not
/// found in the collection, returns `nil`.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public func firstIndex(of element: Element) -> Index? {
if let result = _customIndexOfEquatableElement(element) {
return result
}
var i = self.startIndex
while i != self.endIndex {
if self[i] == element {
return i
}
self.formIndex(after: &i)
}
return nil
}
}
extension Collection {
/// Returns the first index in which an element of the collection satisfies
/// the given predicate.
///
/// You can use the predicate to find an element of a type that doesn't
/// conform to the `Equatable` protocol or to find an element that matches
/// particular criteria. Here's an example that finds a student name that
/// begins with the letter "A":
///
/// let students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
/// if let i = students.firstIndex(where: { $0.hasPrefix("A") }) {
/// print("\(students[i]) starts with 'A'!")
/// }
/// // Prints "Abena starts with 'A'!"
///
/// - Parameter predicate: A closure that takes an element as its argument
/// and returns a Boolean value that indicates whether the passed element
/// represents a match.
/// - Returns: The index of the first element for which `predicate` returns
/// `true`. If no elements in the collection satisfy the given predicate,
/// returns `nil`.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public func firstIndex(
where predicate: (Element) throws -> Bool
) rethrows -> Index? {
var i = self.startIndex
while i != self.endIndex {
if try predicate(self[i]) {
return i
}
self.formIndex(after: &i)
}
return nil
}
}
//===----------------------------------------------------------------------===//
// lastIndex(of:)/lastIndex(where:)
//===----------------------------------------------------------------------===//
extension BidirectionalCollection {
/// Returns the last element of the sequence that satisfies the given
/// predicate.
///
/// This example uses the `last(where:)` method to find the last
/// negative number in an array of integers:
///
/// let numbers = [3, 7, 4, -2, 9, -6, 10, 1]
/// if let lastNegative = numbers.last(where: { $0 < 0 }) {
/// print("The last negative number is \(lastNegative).")
/// }
/// // Prints "The last negative number is -6."
///
/// - Parameter predicate: A closure that takes an element of the sequence as
/// its argument and returns a Boolean value indicating whether the
/// element is a match.
/// - Returns: The last element of the sequence that satisfies `predicate`,
/// or `nil` if there is no element that satisfies `predicate`.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public func last(
where predicate: (Element) throws -> Bool
) rethrows -> Element? {
return try lastIndex(where: predicate).map { self[$0] }
}
/// Returns the index of the last element in the collection that matches the
/// given predicate.
///
/// You can use the predicate to find an element of a type that doesn't
/// conform to the `Equatable` protocol or to find an element that matches
/// particular criteria. This example finds the index of the last name that
/// begins with the letter *A:*
///
/// let students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
/// if let i = students.lastIndex(where: { $0.hasPrefix("A") }) {
/// print("\(students[i]) starts with 'A'!")
/// }
/// // Prints "Akosua starts with 'A'!"
///
/// - Parameter predicate: A closure that takes an element as its argument
/// and returns a Boolean value that indicates whether the passed element
/// represents a match.
/// - Returns: The index of the last element in the collection that matches
/// `predicate`, or `nil` if no elements match.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public func lastIndex(
where predicate: (Element) throws -> Bool
) rethrows -> Index? {
var i = endIndex
while i != startIndex {
formIndex(before: &i)
if try predicate(self[i]) {
return i
}
}
return nil
}
}
extension BidirectionalCollection where Element: Equatable {
/// Returns the last index where the specified value appears in the
/// collection.
///
/// After using `lastIndex(of:)` to find the position of the last instance of
/// a particular element in a collection, you can use it to access the
/// element by subscripting. This example shows how you can modify one of
/// the names in an array of students.
///
/// var students = ["Ben", "Ivy", "Jordell", "Ben", "Maxime"]
/// if let i = students.lastIndex(of: "Ben") {
/// students[i] = "Benjamin"
/// }
/// print(students)
/// // Prints "["Ben", "Ivy", "Jordell", "Benjamin", "Max"]"
///
/// - Parameter element: An element to search for in the collection.
/// - Returns: The last index where `element` is found. If `element` is not
/// found in the collection, this method returns `nil`.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public func lastIndex(of element: Element) -> Index? {
if let result = _customLastIndexOfEquatableElement(element) {
return result
}
return lastIndex(where: { $0 == element })
}
}
//===----------------------------------------------------------------------===//
// partition(by:)
//===----------------------------------------------------------------------===//
extension MutableCollection {
/// Reorders the elements of the collection such that all the elements
/// that match the given predicate are after all the elements that don't
/// match.
///
/// After partitioning a collection, there is a pivot index `p` where
/// no element before `p` satisfies the `belongsInSecondPartition`
/// predicate and every element at or after `p` satisfies
/// `belongsInSecondPartition`. This operation isn't guaranteed to be
/// stable, so the relative ordering of elements within the partitions might
/// change.
///
/// In the following example, an array of numbers is partitioned by a
/// predicate that matches elements greater than 30.
///
/// var numbers = [30, 40, 20, 30, 30, 60, 10]
/// let p = numbers.partition(by: { $0 > 30 })
/// // p == 5
/// // numbers == [30, 10, 20, 30, 30, 60, 40]
///
/// The `numbers` array is now arranged in two partitions. The first
/// partition, `numbers[..<p]`, is made up of the elements that
/// are not greater than 30. The second partition, `numbers[p...]`,
/// is made up of the elements that *are* greater than 30.
///
/// let first = numbers[..<p]
/// // first == [30, 10, 20, 30, 30]
/// let second = numbers[p...]
/// // second == [60, 40]
///
/// Note that the order of elements in both partitions changed.
/// That is, `40` appears before `60` in the original collection,
/// but, after calling `partition(by:)`, `60` appears before `40`.
///
/// - Parameter belongsInSecondPartition: A predicate used to partition
/// the collection. All elements satisfying this predicate are ordered
/// after all elements not satisfying it.
/// - Returns: The index of the first element in the reordered collection
/// that matches `belongsInSecondPartition`. If no elements in the
/// collection match `belongsInSecondPartition`, the returned index is
/// equal to the collection's `endIndex`.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public mutating func partition(
by belongsInSecondPartition: (Element) throws -> Bool
) rethrows -> Index {
return try _halfStablePartition(isSuffixElement: belongsInSecondPartition)
}
/// Moves all elements satisfying `isSuffixElement` into a suffix of the
/// collection, returning the start position of the resulting suffix.
///
/// - Complexity: O(*n*) where n is the length of the collection.
@inlinable
internal mutating func _halfStablePartition(
isSuffixElement: (Element) throws -> Bool
) rethrows -> Index {
guard var i = try firstIndex(where: isSuffixElement)
else { return endIndex }
var j = index(after: i)
while j != endIndex {
if try !isSuffixElement(self[j]) { swapAt(i, j); formIndex(after: &i) }
formIndex(after: &j)
}
return i
}
}
extension MutableCollection where Self: BidirectionalCollection {
/// Reorders the elements of the collection such that all the elements
/// that match the given predicate are after all the elements that don't
/// match.
///
/// After partitioning a collection, there is a pivot index `p` where
/// no element before `p` satisfies the `belongsInSecondPartition`
/// predicate and every element at or after `p` satisfies
/// `belongsInSecondPartition`. This operation isn't guaranteed to be
/// stable, so the relative ordering of elements within the partitions might
/// change.
///
/// In the following example, an array of numbers is partitioned by a
/// predicate that matches elements greater than 30.
///
/// var numbers = [30, 40, 20, 30, 30, 60, 10]
/// let p = numbers.partition(by: { $0 > 30 })
/// // p == 5
/// // numbers == [30, 10, 20, 30, 30, 60, 40]
///
/// The `numbers` array is now arranged in two partitions. The first
/// partition, `numbers[..<p]`, is made up of the elements that
/// are not greater than 30. The second partition, `numbers[p...]`,
/// is made up of the elements that *are* greater than 30.
///
/// let first = numbers[..<p]
/// // first == [30, 10, 20, 30, 30]
/// let second = numbers[p...]
/// // second == [60, 40]
///
/// Note that the order of elements in both partitions changed.
/// That is, `40` appears before `60` in the original collection,
/// but, after calling `partition(by:)`, `60` appears before `40`.
///
/// - Parameter belongsInSecondPartition: A predicate used to partition
/// the collection. All elements satisfying this predicate are ordered
/// after all elements not satisfying it.
/// - Returns: The index of the first element in the reordered collection
/// that matches `belongsInSecondPartition`. If no elements in the
/// collection match `belongsInSecondPartition`, the returned index is
/// equal to the collection's `endIndex`.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public mutating func partition(
by belongsInSecondPartition: (Element) throws -> Bool
) rethrows -> Index {
let maybeOffset = try withContiguousMutableStorageIfAvailable {
(bufferPointer) -> Int in
let unsafeBufferPivot = try bufferPointer._partitionImpl(
by: belongsInSecondPartition)
return unsafeBufferPivot - bufferPointer.startIndex
}
if let offset = maybeOffset {
return index(startIndex, offsetBy: offset)
} else {
return try _partitionImpl(by: belongsInSecondPartition)
}
}
@inlinable
internal mutating func _partitionImpl(
by belongsInSecondPartition: (Element) throws -> Bool
) rethrows -> Index {
var lo = startIndex
var hi = endIndex
while true {
// Invariants at this point:
//
// * `lo <= hi`
// * all elements in `startIndex ..< lo` belong in the first partition
// * all elements in `hi ..< endIndex` belong in the second partition
// Find next element from `lo` that may not be in the right place.
while true {
guard lo < hi else { return lo }
if try belongsInSecondPartition(self[lo]) { break }
formIndex(after: &lo)
}
// Find next element down from `hi` that we can swap `lo` with.
while true {
formIndex(before: &hi)
guard lo < hi else { return lo }
if try !belongsInSecondPartition(self[hi]) { break }
}
swapAt(lo, hi)
formIndex(after: &lo)
}
}
}
//===----------------------------------------------------------------------===//
// _indexedStablePartition / _partitioningIndex
//===----------------------------------------------------------------------===//
extension MutableCollection {
/// Moves all elements at the indices satisfying `belongsInSecondPartition`
/// into a suffix of the collection, preserving their relative order, and
/// returns the start of the resulting suffix.
///
/// - Complexity: O(*n* log *n*) where *n* is the number of elements.
/// - Precondition:
/// `n == distance(from: range.lowerBound, to: range.upperBound)`
internal mutating func _indexedStablePartition(
count n: Int,
range: Range<Index>,
by belongsInSecondPartition: (Index) throws-> Bool
) rethrows -> Index {
if n == 0 { return range.lowerBound }
if n == 1 {
return try belongsInSecondPartition(range.lowerBound)
? range.lowerBound
: range.upperBound
}
let h = n / 2, i = index(range.lowerBound, offsetBy: h)
let j = try _indexedStablePartition(
count: h,
range: range.lowerBound..<i,
by: belongsInSecondPartition)
let k = try _indexedStablePartition(
count: n - h,
range: i..<range.upperBound,
by: belongsInSecondPartition)
return _rotate(in: j..<k, shiftingToStart: i)
}
}
//===----------------------------------------------------------------------===//
// _partitioningIndex(where:)
//===----------------------------------------------------------------------===//
extension Collection {
/// Returns the index of the first element in the collection that matches
/// the predicate.
///
/// The collection must already be partitioned according to the predicate.
/// That is, there should be an index `i` where for every element in
/// `collection[..<i]` the predicate is `false`, and for every element
/// in `collection[i...]` the predicate is `true`.
///
/// - Parameter predicate: A predicate that partitions the collection.
/// - Returns: The index of the first element in the collection for which
/// `predicate` returns `true`.
///
/// - Complexity: O(log *n*), where *n* is the length of this collection if
/// the collection conforms to `RandomAccessCollection`, otherwise O(*n*).
internal func _partitioningIndex(
where predicate: (Element) throws -> Bool
) rethrows -> Index {
var n = count
var l = startIndex
while n > 0 {
let half = n / 2
let mid = index(l, offsetBy: half)
if try predicate(self[mid]) {
n = half
} else {
l = index(after: mid)
n -= half + 1
}
}
return l
}
}
//===----------------------------------------------------------------------===//
// shuffled()/shuffle()
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns the elements of the sequence, shuffled using the given generator
/// as a source for randomness.
///
/// You use this method to randomize the elements of a sequence when you are
/// using a custom random number generator. For example, you can shuffle the
/// numbers between `0` and `9` by calling the `shuffled(using:)` method on
/// that range:
///
/// let numbers = 0...9
/// let shuffledNumbers = numbers.shuffled(using: &myGenerator)
/// // shuffledNumbers == [8, 9, 4, 3, 2, 6, 7, 0, 5, 1]
///
/// - Parameter generator: The random number generator to use when shuffling
/// the sequence.
/// - Returns: An array of this sequence's elements in a shuffled order.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
/// - Note: The algorithm used to shuffle a sequence may change in a future
/// version of Swift. If you're passing a generator that results in the
/// same shuffled order each time you run your program, that sequence may
/// change when your program is compiled using a different version of
/// Swift.
@inlinable
public func shuffled<T: RandomNumberGenerator>(
using generator: inout T
) -> [Element] {
var result = ContiguousArray(self)
result.shuffle(using: &generator)
return Array(result)
}
/// Returns the elements of the sequence, shuffled.
///
/// For example, you can shuffle the numbers between `0` and `9` by calling
/// the `shuffled()` method on that range:
///
/// let numbers = 0...9
/// let shuffledNumbers = numbers.shuffled()
/// // shuffledNumbers == [1, 7, 6, 2, 8, 9, 4, 3, 5, 0]
///
/// This method is equivalent to calling `shuffled(using:)`, passing in the
/// system's default random generator.
///
/// - Returns: A shuffled array of this sequence's elements.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public func shuffled() -> [Element] {
var g = SystemRandomNumberGenerator()
return shuffled(using: &g)
}
}
extension MutableCollection where Self: RandomAccessCollection {
/// Shuffles the collection in place, using the given generator as a source
/// for randomness.
///
/// You use this method to randomize the elements of a collection when you
/// are using a custom random number generator. For example, you can use the
/// `shuffle(using:)` method to randomly reorder the elements of an array.
///
/// var names = ["Alejandro", "Camila", "Diego", "Luciana", "Luis", "Sofía"]
/// names.shuffle(using: &myGenerator)
/// // names == ["Sofía", "Alejandro", "Camila", "Luis", "Diego", "Luciana"]
///
/// - Parameter generator: The random number generator to use when shuffling
/// the collection.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
/// - Note: The algorithm used to shuffle a collection may change in a future
/// version of Swift. If you're passing a generator that results in the
/// same shuffled order each time you run your program, that sequence may
/// change when your program is compiled using a different version of
/// Swift.
@inlinable
public mutating func shuffle<T: RandomNumberGenerator>(
using generator: inout T
) {
guard count > 1 else { return }
var amount = count
var currentIndex = startIndex
while amount > 1 {
let random = Int.random(in: 0 ..< amount, using: &generator)
amount -= 1
swapAt(
currentIndex,
index(currentIndex, offsetBy: random)
)
formIndex(after: ¤tIndex)
}
}
/// Shuffles the collection in place.
///
/// Use the `shuffle()` method to randomly reorder the elements of an array.
///
/// var names = ["Alejandro", "Camila", "Diego", "Luciana", "Luis", "Sofía"]
/// names.shuffle()
/// // names == ["Luis", "Camila", "Luciana", "Sofía", "Alejandro", "Diego"]
///
/// This method is equivalent to calling `shuffle(using:)`, passing in the
/// system's default random generator.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public mutating func shuffle() {
var g = SystemRandomNumberGenerator()
shuffle(using: &g)
}
}
|
apache-2.0
|
b9292f95d71a30eba96740e847cec61e
| 37.137324 | 82 | 0.599991 | 4.348053 | false | false | false | false |
ZekeSnider/Jared
|
JaredFramework/Action.swift
|
1
|
1237
|
//
// main.swift
// Jared 3.0 - Swiftified
//
// Created by Zeke Snider on 4/3/16.
// Copyright © 2016 Zeke Snider. All rights reserved.
//
import Foundation
public struct Action: Encodable, Equatable {
enum CodingKeys : String, CodingKey{
case type
case targetGUID
case event
}
public enum ActionEvent: String {
case placed = "placed"
case removed = "removed"
}
public var type: ActionType
public var event: ActionEvent
public var targetGUID: String
public init(actionTypeInt: Int, targetGUID: String) {
if (actionTypeInt >= 3000) {
event = .removed
self.type = ActionType(fromActionTypeInt: actionTypeInt - 1000)
} else {
event = .placed
self.type = ActionType(fromActionTypeInt: actionTypeInt)
}
self.targetGUID = targetGUID
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(type.rawValue, forKey: .type)
try container.encode(targetGUID, forKey: .targetGUID)
try container.encode(event.rawValue, forKey: .event)
}
}
|
apache-2.0
|
eef432452b8584af03b6f3abd5c22cd5
| 26.466667 | 75 | 0.616505 | 4.321678 | false | false | false | false |
Zane6w/MoreColorButton
|
ColorfulButton/ColorfulButton/SQLite.swift
|
1
|
13155
|
//
// SQLite.swift
// MoreSQL
//
// Created by zhi zhou on 2017/1/17.
// Copyright © 2017年 zhi zhou. All rights reserved.
//
import UIKit
import FMDB
class SQLite: NSObject {
// MARK:- 属性
static let shared = SQLite()
/// 是否开启打印
var isPrint = true
/// 表名称
fileprivate var tableName: String?
/// 路径
fileprivate var dbPath: String?
/// 数据库
fileprivate var db: FMDatabase?
// MARK:- 方法
// MARK: >>> 开启数据库
/// 开启数据库
/// - parameter pathName: 数据库存放路径
/// - parameter tableName: 表名
func openDB(pathName: String? = nil, tableName: String) -> Bool {
if let pathName = pathName {
return packOpen(pathName, tableName)
} else {
return packOpen("data", tableName)
}
}
// 封装开启方法
fileprivate func packOpen(_ pathName: String, _ tableName: String) -> Bool {
var path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
path = path + "/" + pathName + ".sqlite"
dbPath = path
db = FMDatabase(path: path)
if (db?.open())! {
self.tableName = tableName
_ = createTable()
remind("数据库开启成功")
return true
} else {
remind("数据库开启失败")
return false
}
}
// MARK: >>> 创建表
/// 创建表
fileprivate func createTable() -> Bool {
db?.open()
// "CREATE TABLE IF NOT EXISTS \(tableName!) (id INTEGER PRIMARY KEY AUTOINCREMENT,btnID TEXT,status TEXT,remark TEXT,title TEXT);"
let sql = "CREATE TABLE IF NOT EXISTS \(tableName!) (id INTEGER PRIMARY KEY AUTOINCREMENT,btnID TEXT,status BLOB,remarks BLOB,title TEXT);"
if (db?.executeUpdate(sql, withArgumentsIn: nil))! {
remind("创建表成功")
db?.close()
return true
} else {
remind("创建表失败")
db?.close()
return false
}
}
// MARK: >>> 插入数据
/// 插入数据
/// - parameter objc: 传入非自定义类型
/// - parameter inTable: 需要操作的表名
func insert(id: String, statusDict: Any, remarksDict: Any, inTable: String? = nil) -> Bool {
db?.open()
db?.beginTransaction()
var sql: String?
if inTable == nil {
sql = "INSERT INTO \(tableName!) (btnID,status,remarks,title) VALUES (?,?,?,?);"
} else {
sql = "INSERT INTO \(inTable!) (btnID,status,remarks,title) VALUES (?,?,?,?);"
}
let title = "nil"
let status = toJson(objc: statusDict)
let remarks = toJson(objc: remarksDict)
if (db?.executeUpdate(sql, withArgumentsIn: [id, status!, remarks!, title]))! {
remind("插入按钮数据成功")
db?.commit()
db?.close()
return true
} else {
remind("插入按钮数据失败")
db?.rollback()
db?.close()
return false
}
}
func insert(title: String, inTable: String? = nil) -> Bool {
db?.open()
db?.beginTransaction()
var sql: String?
if inTable == nil {
sql = "INSERT INTO \(tableName!) (title) VALUES (?);"
} else {
sql = "INSERT INTO \(inTable!) (title) VALUES (?);"
}
if (db?.executeUpdate(sql, withArgumentsIn: [title]))! {
remind("插入 Title 数据成功")
db?.commit()
db?.close()
return true
} else {
remind("插入 Title 数据失败")
db?.rollback()
db?.close()
return false
}
}
// MARK: >>> 查询数据
/// 查询所有数据
/// - parameter inTable: 需要操作的表名
func queryAll(inTable: String? = nil) -> [Any]? {
var sql: String?
if inTable == nil {
sql = "SELECT btnID,status,remarks FROM \(tableName!);"
} else {
sql = "SELECT btnID,status,remarks FROM \(inTable!);"
}
return packQuery(sql: sql!)
}
func queryAllTitle(inTable: String? = nil) -> [Any]? {
var sql: String?
if inTable == nil {
sql = "SELECT title FROM \(tableName!);"
} else {
sql = "SELECT title FROM \(inTable!);"
}
return packQuery(sql: sql!, isFull: false)
}
/// 查询符合ID条件的数据
/// - parameter inTable: 需要操作的表名
/// - parameter id: 查询ID符合条件的数据
func query(inTable: String? = nil, id: String) -> [Any]? {
var sql: String?
if inTable == nil {
sql = "SELECT btnID,status,remarks FROM \(tableName!) WHERE btnID = '\(id)';"
} else {
sql = "SELECT btnID,status,remarks FROM \(inTable!) WHERE btnID = '\(id)';"
}
return packQuery(sql: sql!, isFull: true)
}
/// 封装查询
/// - parameter sql: 查询语句
/// - parameter isFull: 是否获取全部数据(默认:true)
fileprivate func packQuery(sql: String, isFull: Bool = true) -> [Any]? {
db?.open()
let set = db?.executeQuery(sql, withArgumentsIn: nil)
guard set != nil else {
return nil
}
var tempArray = [Any]()
while set!.next() {
let id = set?.object(forColumnName: "btnID")
let status = set?.object(forColumnName: "status")
let remark = set?.object(forColumnName: "remarks")
let title = set?.object(forColumnName: "title")
if let id = id, let status = status, let remarks = remark, let title = title {
if isFull {
let statusDict = jsonToAny(json: status as! String)
let remarksDict = jsonToAny(json: remarks as! String)
tempArray.append(id)
tempArray.append(statusDict!)
tempArray.append(remarksDict!)
} else {
if title as! String != "nil" {
tempArray.append(title)
}
}
}
}
db?.close()
return tempArray
}
// MARK: >>> 更新数据
/// 根据ID更新某个数据
/// - parameter newValue: 传入非自定义类型
/// - parameter inTable: 需要操作的表名
func update(id: String, statusDict: Any, remarksDict: Any, inTable: String? = nil) -> Bool {
db?.open()
db?.beginTransaction()
let status = toJson(objc: statusDict)
let remarks = toJson(objc: remarksDict)
// e.g.: 更新 ID = 6 的数据
// "UPDATE \(tableName) SET js = '\(js!)'; WHERE ID = 6"
// "UPDATE \(tableName!) SET js = '\(js!)' WHERE btnID = 'zz123';"
var sql: String?
if inTable == nil {
sql = "UPDATE \(tableName!) SET status = ?, remarks = ? WHERE btnID = ?;"
} else {
sql = "UPDATE \(inTable!) SET status = ?, remarks = ? WHERE btnID = ?;"
}
if (db?.executeUpdate(sql, withArgumentsIn: [status!, remarks!, id]))! {
remind("根据 ID 修改成功")
db?.commit()
db?.close()
return true
} else {
remind("根据 ID 修改失败 -> \(db?.lastErrorMessage() ?? "未知 ID 修改错误")")
db?.rollback()
db?.close()
return false
}
}
// MARK: >>> 删除数据 (全部)
/// 删除 (全部) 数据
/// - parameter inTable: 需要操作的表名
func deleteAll(inTable: String? = nil) -> Bool {
db?.open()
// 删除所有 或 where ..... 来进行判断筛选删除
var sql: String?
if inTable == nil {
sql = "DELETE FROM \(tableName!);"
} else {
sql = "DELETE FROM \(inTable!);"
}
if (db?.executeUpdate(sql, withArgumentsIn: nil))! {
remind("删除全部数据成功")
db?.close()
return true
} else {
remind("删除全部数据失败")
db?.close()
return false
}
}
/// 根据 ID 删除数据
func delete(id: String, inTable: String? = nil) -> Bool {
db?.open()
var sql: String?
if inTable == nil {
sql = "DELETE FROM \(tableName!) WHERE btnID = ?;"
} else {
sql = "DELETE FROM \(inTable!) WHERE btnID = ?;"
}
if (db?.executeUpdate(sql, withArgumentsIn: [id]))! {
remind("根据 ID 删除成功")
db?.close()
return true
} else {
remind("根据 ID 删除失败 -> \(db?.lastErrorMessage() ?? "未知 ID 删除错误")")
db?.close()
return false
}
}
/// 根据 Title 删除标题数据
func delete(title: String, inTable: String? = nil) -> Bool {
db?.open()
var sql: String?
if inTable == nil {
sql = "DELETE FROM \(tableName!) WHERE title = ?;"
} else {
sql = "DELETE FROM \(inTable!) WHERE title = ?;"
}
if (db?.executeUpdate(sql, withArgumentsIn: [title]))! {
remind("根据 Title 删除成功")
db?.close()
return true
} else {
remind("根据 Title 删除失败 -> \(db?.lastErrorMessage() ?? "未知 Title 删除错误")")
db?.close()
return false
}
}
}
// MARK:- 本地数据大小
extension SQLite {
/// 本地数据大小
func dataSize() -> String {
var dataSize: Int = 0
if let dbPath = dbPath {
if FileManager.default.fileExists(atPath: dbPath) {
if let dict = try? FileManager.default.attributesOfItem(atPath: dbPath) {
dataSize += dict[FileAttributeKey("NSFileSize")] as! Int
}
}
}
// KB
let sizeKB = dataSize / 1024
if sizeKB < 1024 {
return "\(sizeKB)KB"
} else if sizeKB >= 1024, sizeKB < 1024 * 1024 {
// MB
let sizeMB = simplification(value: sizeKB)
return "\(String(format: "%.2f", sizeMB))MB"
} else {
// GB ~
let sizeHuge = simplification(value: sizeKB)
return "\(String(format: "%.2f", sizeHuge))GB"
}
}
/// 简化显示
fileprivate func simplification(value: Int) -> Double {
if value < 1000 {
return Double(value)
} else {
let simplificationValue = Double(value) * 0.001
return simplificationValue
}
}
}
// MARK:- JSON、ANY 转换
extension SQLite {
/// **Any** 转换为 **JSON** 类型
/// - parameter objc: 传入非自定义类型
func toJson(objc: Any) -> String? {
let data = try? JSONSerialization.data(withJSONObject: objc, options: .prettyPrinted)
if let data = data {
return String(data: data, encoding: .utf8)
} else {
return nil
}
}
/// **JSON** 转换为 **Any** 类型
/// - parameter json: String 类型数据
func jsonToAny(json: String) -> Any? {
let data = json.data(using: .utf8)
if let data = data {
let anyObjc = try? JSONSerialization.jsonObject(with: data, options: .allowFragments)
if let anyObjc = anyObjc {
return anyObjc
} else {
return nil
}
} else {
return nil
}
}
}
// MARK:- 自定义 print 打印
extension SQLite {
/// 根据 **isPrint** 的值来决定是否打印
/// - parameter message: 打印信息
fileprivate func remind(_ message: String) {
if isPrint {
printDBug(message, isDetail: false)
}
}
/// 仅在 Debug 模式下打印
/// - parameter info: 打印信息
/// - parameter fileName: 打印所在的swift文件
/// - parameter methodName: 打印所在文件的类名
/// - parameter lineNumber: 打印事件发生在哪一行
/// - parameter isDetail: 是否打印详细信息 (默认: true)
fileprivate func printDBug<T>(_ info: T, fileName: String = #file, methodName: String = #function, lineNumber: Int = #line, isDetail: Bool = true) {
let file = (fileName as NSString).pathComponents.last!
#if DEBUG
if isDetail {
print("\(file) -> \(methodName) [line \(lineNumber)]: \(info)")
} else {
print(info)
}
#endif
}
}
|
apache-2.0
|
f5ae2e3a72d9374cae40978375cc02d4
| 28.623188 | 152 | 0.489074 | 4.283619 | false | false | false | false |
lukevanin/onthemap
|
OnTheMap/LocationLookupViewController.swift
|
1
|
5168
|
//
// LocationLookupViewController.swift
// OnTheMap
//
// Created by Luke Van In on 2017/01/13.
// Copyright © 2017 Luke Van In. All rights reserved.
//
// Screen 1 of 2 for adding a location.
//
// Allows the user to look up geo location coordinates from a text address.
//
import UIKit
import MapKit
class LocationLookupViewController: UIViewController {
enum State {
case pending
case busy
}
private let locationService = NativeLocationService()
private let dismissSegue = "dismiss"
private let infoSegue = "info"
private var state: State = .pending {
didSet {
updateState()
}
}
// MARK: Outlets
@IBOutlet weak var locationTextField: UITextField!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var findButton: UIButton!
// MARK: Actions
//
// "Find on map" tapped. Dismiss the keyboard and geocode the address.
//
@IBAction func onFindButtonAction(_ sender: Any) {
locationTextField.resignFirstResponder()
state = .busy
performLookup()
}
//
// Cancel button tapped. Dismiss the modal and return to the presenting view controller.
//
@IBAction func onCancelButtonAction(_ sender: Any) {
performSegue(withIdentifier: dismissSegue, sender: sender)
}
// MARK: View controller life cycle
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
updateState()
}
// MARK: State management
//
// Update the UI to display the current state. Disables UI input and shows activity indicator while geocoding is in
// progress
//
private func updateState() {
switch state {
case .pending:
configureUI(inputEnabled: true, activityVisible: false)
case .busy:
configureUI(inputEnabled: false, activityVisible: true)
}
}
//
// Configure UI. Disable/enable textfield and button input. Show/hide activity indicator.
//
private func configureUI(inputEnabled: Bool, activityVisible: Bool) {
locationTextField.isEnabled = inputEnabled
findButton.isHidden = !inputEnabled
if activityVisible {
activityIndicator.startAnimating()
}
else {
activityIndicator.stopAnimating()
}
}
// MARK: Location
//
// Retrieve coordinates for a given address. An error alert is shown if the address field is blank, or if geocoding
// fails. Transitions to the next screen on successfully geocoding the address.
//
private func performLookup() {
// Get address entry. If no address is entered, then show an error and focus the location text field.
guard let location = locationTextField.text, !location.isEmpty else {
state = .pending
let message = "Please enter your location."
showAlert(forErrorMessage: message) { [weak self] in
self?.locationTextField.becomeFirstResponder()
}
return
}
// Lookup the location.
locationService.lookupAddress(location) { [weak self] result in
DispatchQueue.main.async {
guard let `self` = self else {
return
}
switch result {
// Geocoding was successful, continue to student info view controller.
case .success(let location):
self.state = .pending
self.performSegue(withIdentifier: self.infoSegue, sender: location.first)
// Location lookup failed.
case .failure(let error):
// An error was reported, show the alert, then go to the pending state.
self.showAlert(forError: error) { [weak self] in
self?.state = .pending
}
}
}
}
}
// MARK: View controller life cycle
//
// Configure view controllers before presentation.
//
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
switch segue.destination {
// Segue to student info view controller.
case let viewController as StudentInfoViewController:
let coordinate = (sender as? CLPlacemark)?.location?.coordinate
viewController.coordinate = coordinate
viewController.address = locationTextField.text
// Unexpected view controller.
default:
break
}
}
}
//
// Text field delegate for location lookup view controller.
//
extension LocationLookupViewController: UITextFieldDelegate {
//
// Called when done/return keyboard button is tapped. Dismiss the keyboard.
//
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
|
mit
|
aa9c3a143b1eeb99fc4d5cbdb4e03103
| 28.867052 | 120 | 0.59551 | 5.410471 | false | false | false | false |
RebornSoul/YNImageAsync
|
Demo/Source/ListDataProvider.swift
|
2
|
2429
|
//
// YNDataProvider.swift
// ImageAsyncTest
//
// Created by Yury Nechaev on 15.10.16.
// Copyright © 2016 Yury Nechaev. All rights reserved.
//
import Foundation
public struct ListObject: ListCellObjectProtocol {
public var imageUrl: String
public var imageTitle: String
init(imageUrl: String, imageTitle: String) {
self.imageUrl = imageUrl
self.imageTitle = imageTitle
}
}
let url = URL(string:"https://s3.amazonaws.com/work-project-image-loading/images.json")
public typealias DataCompletionClosure = ((_ result: Array<ListObject>?, _ error: NSError?) -> Void)
public class ListDataProvider {
var completionClosure: DataCompletionClosure
public init(completionClosure com: @escaping DataCompletionClosure) {
self.completionClosure = com
loadItunesInfo(url!)
}
func loadItunesInfo(_ itunesUrl: URL) -> Void {
let session = URLSession.shared
let task = session.dataTask(with: itunesUrl, completionHandler: self.apiHandler)
task.resume()
}
func apiHandler(data: Data?, response: URLResponse?, error: Error?) -> Void {
if let apiError = error {
print("API error: \(apiError)")
}
guard let apiData = data else { return }
do {
let json = try JSONSerialization.jsonObject(with: apiData, options:JSONSerialization.ReadingOptions(rawValue: 0))
guard let dict: NSDictionary = json as? NSDictionary else {
print("Parsed json object is not a Dictionary type")
return
}
processRequestResult(dict)
}
catch let JSONError as NSError {
print("\(JSONError)")
}
}
func processRequestResult(_ response: NSDictionary) {
var temp: Array <ListObject> = []
if let root = response["images"] as? Array<AnyObject> {
for obj in root {
if let url = obj["url"] as? String, let title = obj["title"] as? String {
let listObject = ListObject(imageUrl: url, imageTitle: title)
temp.append(listObject)
}
}
DispatchQueue.main.async(execute: { () -> Void in
self.completionClosure(temp, nil)
})
} else {
self.completionClosure(nil, nil)
}
}
}
|
mit
|
2c0ba6173a76c68c5d7151edcc104ae5
| 30.532468 | 125 | 0.591021 | 4.696325 | false | false | false | false |
heshamMassoud/RouteMe
|
RouteMe/Constants.swift
|
1
|
7745
|
//
// Constants.swift
// RouteMe
//
// Created by Hesham Massoud on 25/05/16.
// Copyright © 2016 Hesham Massoud. All rights reserved.
//
import Foundation
import UIKit
struct API {
static let Path = "http://routeme-api.us-east-1.elasticbeanstalk.com/api/"
struct SearchEndpoint {
static let Path = "\(API.Path)search"
struct Parameter {
static let StartPoint = "startPoint"
static let EndPoint = "endPoint"
static let UserId = "userId"
}
struct Key {
static let RouteResults = "routeResults"
static let PredictionIoId = "predictionIoId"
static let IsTransit = "transit"
static let Summary = "routeSummary"
static let Steps = "steps"
static let Polyline = "overviewPolyLine"
static let StartAddress = "startAddress"
static let EndAddress = "endAddress"
static let TransportationMode = "transportationMode"
static let Distance = "distance"
static let HTMLInstruction = "htmlInstruction"
static let TransportationVehicleShortName = "transportationVehicleShortName"
static let TransportationLineColorCode = "transportationLineColorCode"
static let TransportationLineHeadSign = "transportationLineHeadSign"
static let StartStation = "startStation"
static let EndStation = "endStation"
static let Duration = "duration"
static let StartTime = "startTime"
static let EndTime = "endTime"
static let Explanations = "explanations"
static let StartLocationLat = "startLocationLat"
static let StartLocationLng = "startLocationLng"
static let EndLocationLat = "endLocationLat"
static let EndLocationLng = "endLocationLng"
static let Liked = "liked"
}
struct Response {
static let Ok = 200
}
}
struct UserEndpoint {
static let Path = "\(API.Path)users/"
struct Parameter {
static let Username = "username"
static let Email = "email"
static let Password = "password"
}
struct Key {
static let Id = "id"
static let Username = "username"
static let Email = "email"
static let Password = "password"
}
struct Response {
static let Created = 201
}
}
struct LoginEndpoint {
static let Path = "\(API.UserEndpoint.Path)login"
struct Parameter {
static let Email = "email"
static let Password = "password"
}
struct Key {
static let Id = "id"
static let Username = "username"
static let Email = "email"
static let Password = "password"
static let LikedRoutes = "likedRoutes"
static let TravelModePreference = "travelModePreference"
static let RouteTypePreference = "routeTypePreference"
}
struct Response {
static let Found = 302
}
}
struct SetPreferenceEndpoint {
static let Path = "\(API.UserEndpoint.Path)setpreference"
struct Parameter {
static let Id = "id"
static let TravelModePreference = "travelModePreference"
static let RouteTypePreference = "routeTypePreference"
}
struct Response {
static let CREATED = 201
}
}
struct LikeRouteEndpoint {
static let Path = "\(API.UserEndpoint.Path)like"
struct Parameter {
static let UserId = "userId"
static let TargetEntityId = "targetEntityId"
}
struct Response {
static let CREATED = 201
}
}
struct DislikeRouteEndpoint {
static let Path = "\(API.UserEndpoint.Path)dislike"
}
}
struct Form {
struct Error {
static let Email = "Please enter a valid e-mail address"
static let Password = "Password must be greater than 1 character"
static let ConfirmationPassword = "Passwords don't match"
}
struct Field {
static let Email = "E-mail"
static let Password = "Password"
static let ConfirmationPassword = "Confirmation Password"
}
struct AlertButton {
static let Ok = "Ok"
}
}
struct GoogleMapsAPI {
static let APIKey = "AIzaSyCZk6CWRY-2b1rONt5YKnfqchNxa1F7YiQ"
struct Autocomplete {
static let BiasCountry = "de"
}
}
struct Transportation {
static let Bus = "Bus"
static let Ubahn = "U-bahn"
static let Tram = "Tram"
static let Sbahn = "S-bahn"
static let Driving = "DRIVING"
static let Bicycling = "BICYCLING"
static let Walking = "WALKING"
static let RE = "Long distance train"
static let ICE = "High speed train"
static let Modes: [String] = [Bus, Ubahn, Tram, Sbahn, Driving, Bicycling, Walking]
static let ImagePaths: [String: String] = [Walking: "walking.png",
Bus: "bus.png",
Sbahn: "sbahn.png",
Ubahn: "ubahn.png",
Tram: "tram.png",
Driving: "car.png",
Bicycling: "bike.png",
RE: "bahn.png",
ICE: "bahn.png"
]
}
struct Explanations {
static let ImagePaths: [String: String] = ["LIKED": "like-icon.png",
"HYBRID_RECOMMENDER": "collab-icon.png",
"POPULARITY": "popular-icon.png",
"LIKES_PREFERENCES": "like-pref-icon.png",
"PREFERENCES": "pref-icon.png"]
}
struct RouteTypePreference {
static let LeastChanges = "leastChanges"
static let LeastTime = "leastTime"
}
struct Image {
struct Background {
static let Signup = "seat_routeme.JPG"
static let Home = "bus_routeme.jpeg"
static let Login = "city_routeme.jpg"
}
}
struct Style {
struct Font {
static let RouteDetailCells = UIFont(name: "HelveticaNeue-Thin", size: 15)!
static let AutocompleteResults = UIFont(name: "HelveticaNeue-Thin", size: 20)!
}
struct Height {
static let RouteDetailCells: CGFloat = 100.0
static let RouteDetailMapView: CGFloat = 200
static let LikeSectionVerticalPadding: CGFloat = 14
static let RouteSearchResultsCells: CGFloat = 100.0
}
struct HTML {
static let InstructionBoldTagOpenning = "<b>"
static let InstructionBoldTagClosing = "</b>"
static let InstructionBoldSpanTagOpenning = "<span style='font-family: HelveticaNeue-Light !important; font-size: 15px'>"
static let InstructionSpanTagOpenning = "<span style='font-family: HelveticaNeue-Thin !important; font-size: 15px'>"
static let InstructionSpanTagClosing = "</span>"
}
struct ColorPallete {
static let Blue = "#4F5D73"
static let Yellow = "#F5CF87"
static let RED = "#C75C5C"
static let GREY = "#E0E0D1"
}
}
struct Placeholder {
struct Title {
static let RouteDetails = "Route details"
static let RouteTypePreference = "Please choose your route type preference"
}
}
|
apache-2.0
|
c0724e2698e3509e9ec887fb3d7bb9b7
| 34.045249 | 129 | 0.561983 | 4.637126 | false | false | false | false |
EdwinSaenz/Calculator
|
StanfordCalculator/CalculatorBrain.swift
|
1
|
5765
|
//
// CalculatorBrain.swift
// StanfordCalculator
//
// Created by Edwin Aaron Saenz on 2/18/15.
// Copyright (c) 2015 Edwin Aaron Saenz. All rights reserved.
//
import Foundation
class CalculatorBrain {
private enum Op: Printable {
case Operand(Double)
case UnaryOperation(String, Double -> Double)
case BinaryOperation(String, Int, (Double, Double) -> Double)
case Constant(String, Double)
case Variable(String)
var description: String {
get {
switch self {
case .Operand(let operand):
return "\(operand)"
case .UnaryOperation(let symbol, _):
return symbol
case .BinaryOperation(let symbol, _, _):
return symbol
case .Constant(let symbol, _):
return "\(symbol)"
case .Variable(let symbol):
return "\(symbol)"
}
}
}
}
var variableValues = Dictionary<String,Double>()
private var opStack = [Op]()
private var knownOps = [String:Op]()
init() {
func learnOp(op: Op) {
knownOps[op.description] = op
}
learnOp(Op.BinaryOperation("×", Int.max, *))
learnOp(Op.BinaryOperation("÷", Int.max) { $1 / $0 })
learnOp(Op.BinaryOperation("+", 1, +))
learnOp(Op.BinaryOperation("-", 1) { $1 - $0 })
learnOp(Op.UnaryOperation("√", sqrt))
learnOp(Op.UnaryOperation("sin", sin))
learnOp(Op.UnaryOperation("cos", cos))
learnOp(Op.UnaryOperation("ᐩ/-") { $0 * -1 })
learnOp(Op.Constant("π", M_PI))
}
var description: String {
get {
var description = ""
var evaluation = evaluateDescription(opStack)
while(evaluation.result != "?") {
description = "\(evaluation.result), \(description)"
evaluation = evaluateDescription(evaluation.remainingOps)
}
let lastIndex = advance(description.endIndex, -2)
return description[description.startIndex..<lastIndex]
}
}
func clear() {
opStack = [Op]()
}
func evaluate() -> Double? {
let (result, remainder) = evaluate(opStack)
println("\(opStack) = \(result) with \(remainder) left over")
return result
}
func pushOperand(operand: Double) -> Double? {
opStack.append(Op.Operand(operand))
return evaluate()
}
func pushOperand(symbol: String) -> Double? {
opStack.append(Op.Variable(symbol))
return evaluate()
}
func performOperation(symbol: String) -> Double? {
if let operation = knownOps[symbol] {
opStack.append(operation)
}
return evaluate()
}
private func evaluate(ops: [Op]) -> (result: Double?, remainingOps: [Op]) {
if !ops.isEmpty {
var remainingOps = ops
let op = remainingOps.removeLast()
switch op {
case .Operand(let operand):
return (operand, remainingOps)
case .UnaryOperation(_, let operation):
let operandEvaluation = evaluate(remainingOps)
if let operand = operandEvaluation.result {
return (operation(operand), operandEvaluation.remainingOps)
}
case .BinaryOperation(_, _, let operation):
let op1Evaluation = evaluate(remainingOps)
if let operand1 = op1Evaluation.result {
let op2Evaluation = evaluate(op1Evaluation.remainingOps)
if let operand2 = op2Evaluation.result {
return (operation(operand1, operand2), op2Evaluation.remainingOps)
}
}
case .Constant(_, let constant):
return (constant, remainingOps)
case .Variable(let symbol):
let value = variableValues[symbol]
return (value, remainingOps)
}
}
return (nil, ops)
}
private func evaluateDescription(ops: [Op]) -> (result: String, opPrecedence: Int, remainingOps: [Op]) {
if !ops.isEmpty {
var remainingOps = ops
let op = remainingOps.removeLast()
switch op {
case .UnaryOperation(let symbol, _):
let description = evaluateDescription(remainingOps)
return ("\(symbol)(\(description.result))", Int.max, description.remainingOps)
case .BinaryOperation(let symbol, let precedence, _):
let evaluation = evaluateDescription(remainingOps)
let evaluation2 = evaluateDescription(evaluation.remainingOps)
var evaluationsPrecedenceIsLower = evaluation.opPrecedence < precedence
if evaluationsPrecedenceIsLower {
return ("\(evaluation2.result) " + symbol + " (\(evaluation.result))", precedence, evaluation2.remainingOps)
} else {
return ("\(evaluation2.result) " + symbol + " \(evaluation.result)", precedence, evaluation2.remainingOps)
}
case .Operand(let operand):
return ("\(operand)", Int.max, remainingOps)
case .Constant(let constant, _):
return ("\(constant)", Int.max, remainingOps)
case .Variable(let variable):
return ("\(variable)", Int.max, remainingOps)
}
}
return ("?", Int.max, ops)
}
}
|
mit
|
502f8d92375c2e44d38a326d763ebc09
| 34.770186 | 128 | 0.533866 | 4.972366 | false | false | false | false |
touchbar/Touch-Bar-Preview
|
Touch Bar Preview/Touch Bar Preview/ViewController.swift
|
1
|
4938
|
//
// ViewController.swift
// Touch Bar Preview
//
// This Software is released under the MIT License
//
// Copyright (c) 2017 Alexander Käßner
//
// 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.
//
// For more information see: https://github.com/touchbar/Touch-Bar-Preview
//
import Cocoa
class ViewController: NSViewController {
@IBOutlet var dropDestinationView: DropDestinationView!
@IBOutlet weak var imagePreviewView: NSImageView!
@IBOutlet weak var bottomBarInfoLable: NSTextField!
@IBOutlet weak var bottomBarAlertImageWidth: NSLayoutConstraint!
public var windowDelegate: WindowController? = nil
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
dropDestinationView.delegate = self
// "hide" alert icon in bottom bar
bottomBarAlertImageWidth.constant = 0.0
NotificationCenter.default.addObserver(self, selector: #selector(handleDockIconDrop), name: NSNotification.Name("dropFileOnDock"), object: nil)
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
@objc func handleDockIconDrop(notification: Notification) {
let fileName = notification.object as! String
let urlString = fileName.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? fileName
let url = URL(string: "file://\(urlString)")
if (url != nil) {
processImageURLs([url!])
// hide the drag and drop icon
NotificationCenter.default.post(name: NSNotification.Name("hideDragAndDropIcon"), object: nil)
}else {
print("could not import image from icon drag")
}
}
}
// MARK: - DropDestinationViewDelegate
extension ViewController: DropDestinationViewDelegate {
func processImageURLs(_ urls: [URL]) {
for (_,url) in urls.enumerated() {
// pass URL to Window Controller
if #available(OSX 10.12.2, *) {
windowDelegate?.showImageInTouchBar(url)
}
// create the image from the content URL
if let image = NSImage(contentsOf:url) {
imagePreviewView.image = image
//print(image.size.width)
// check if the image has the touch bar size (2170x60px)
// and inform the user
if image.size.width > TouchBarSizes.fullWidth || image.size.height > TouchBarSizes.fullHeight {
bottomBarInfoLable.stringValue = "Image is too big! Should be 2170×60px."
bottomBarInfoLable.toolTip = "The image is \(Int(image.size.width))x\(Int(image.size.height))px."
// show alert icon in bottom bar
bottomBarAlertImageWidth.constant = 20.0
} else if image.size.width == TouchBarSizes.fullWidth && image.size.height == TouchBarSizes.fullHeight || image.size.width == TouchBarSizes.fullWidth/2 && image.size.height == TouchBarSizes.fullHeight/2 {
bottomBarInfoLable.stringValue = "✓ Image is correct!"
bottomBarInfoLable.toolTip = nil
// "hide" alert icon in bottom bar
bottomBarAlertImageWidth.constant = 0.0
} else {
bottomBarInfoLable.stringValue = "Image should be 2170×60px"
bottomBarInfoLable.toolTip = nil
// "hide" alert icon in bottom bar
bottomBarAlertImageWidth.constant = 0.0
}
}
}
}
}
|
mit
|
66e6cff4e089fe89d159a9246c9ebc55
| 38.774194 | 220 | 0.61841 | 5.007107 | false | false | false | false |
AdaptiveMe/adaptive-arp-api-lib-darwin
|
Pod/Classes/Sources.Api/Acceleration.swift
|
1
|
6271
|
/**
--| ADAPTIVE RUNTIME PLATFORM |----------------------------------------------------------------------------------------
(C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>.
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 appli-
-cable 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.
Original author:
* Carlos Lozano Diez
<http://github.com/carloslozano>
<http://twitter.com/adaptivecoder>
<mailto:[email protected]>
Contributors:
* Ferran Vila Conesa
<http://github.com/fnva>
<http://twitter.com/ferran_vila>
<mailto:[email protected]>
* See source code files for contributors.
Release:
* @version v2.2.15
-------------------------------------------| aut inveniam viam aut faciam |--------------------------------------------
*/
import Foundation
/**
Structure representing the data of a single acceleration reading.
@author Carlos Lozano Diez
@since v2.0
@version 1.0
*/
public class Acceleration : APIBean {
/**
Timestamp of the acceleration reading.
*/
var timestamp : Int64?
/**
X-axis component of the acceleration.
*/
var x : Double?
/**
Y-axis component of the acceleration.
*/
var y : Double?
/**
Z-axis component of the acceleration.
*/
var z : Double?
/**
Default constructor
@since v2.0
*/
public override init() {
super.init()
}
/**
Constructor with fields
@param x X Coordinate
@param y Y Coordinate
@param z Z Coordinate
@param timestamp Timestamp
@since v2.0
*/
public init(x: Double, y: Double, z: Double, timestamp: Int64) {
super.init()
self.x = x
self.y = y
self.z = z
self.timestamp = timestamp
}
/**
Timestamp Getter
@return Timestamp
@since v2.0
*/
public func getTimestamp() -> Int64? {
return self.timestamp
}
/**
Timestamp Setter
@param timestamp Timestamp
@since v2.0
*/
public func setTimestamp(timestamp: Int64) {
self.timestamp = timestamp
}
/**
X Coordinate Getter
@return X-axis component of the acceleration.
@since v2.0
*/
public func getX() -> Double? {
return self.x
}
/**
X Coordinate Setter
@param x X-axis component of the acceleration.
@since v2.0
*/
public func setX(x: Double) {
self.x = x
}
/**
Y Coordinate Getter
@return Y-axis component of the acceleration.
@since v2.0
*/
public func getY() -> Double? {
return self.y
}
/**
Y Coordinate Setter
@param y Y-axis component of the acceleration.
@since v2.0
*/
public func setY(y: Double) {
self.y = y
}
/**
Z Coordinate Getter
@return Z-axis component of the acceleration.
@since v2.0
*/
public func getZ() -> Double? {
return self.z
}
/**
Z Coordinate Setter
@param z Z Coordinate
@since v2.0
*/
public func setZ(z: Double) {
self.z = z
}
/**
JSON Serialization and deserialization support.
*/
public struct Serializer {
public static func fromJSON(json : String) -> Acceleration {
let data:NSData = json.dataUsingEncoding(NSUTF8StringEncoding)!
let dict = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
return fromDictionary(dict!)
}
static func fromDictionary(dict : NSDictionary) -> Acceleration {
let resultObject : Acceleration = Acceleration()
if let value : AnyObject = dict.objectForKey("timestamp") {
if "\(value)" as NSString != "<null>" {
let numValue = value as? NSNumber
resultObject.timestamp = numValue?.longLongValue
}
}
if let value : AnyObject = dict.objectForKey("x") {
if "\(value)" as NSString != "<null>" {
resultObject.x = (value as! Double)
}
}
if let value : AnyObject = dict.objectForKey("y") {
if "\(value)" as NSString != "<null>" {
resultObject.y = (value as! Double)
}
}
if let value : AnyObject = dict.objectForKey("z") {
if "\(value)" as NSString != "<null>" {
resultObject.z = (value as! Double)
}
}
return resultObject
}
public static func toJSON(object: Acceleration) -> String {
let jsonString : NSMutableString = NSMutableString()
// Start Object to JSON
jsonString.appendString("{ ")
// Fields.
object.timestamp != nil ? jsonString.appendString("\"timestamp\": \(object.timestamp!), ") : jsonString.appendString("\"timestamp\": null, ")
object.x != nil ? jsonString.appendString("\"x\": \(object.x!), ") : jsonString.appendString("\"x\": null, ")
object.y != nil ? jsonString.appendString("\"y\": \(object.y!), ") : jsonString.appendString("\"y\": null, ")
object.z != nil ? jsonString.appendString("\"z\": \(object.z!)") : jsonString.appendString("\"z\": null")
// End Object to JSON
jsonString.appendString(" }")
return jsonString as String
}
}
}
/**
------------------------------------| Engineered with ♥ in Barcelona, Catalonia |--------------------------------------
*/
|
apache-2.0
|
f0d3ed64d5d41d8ffda59d71ec73a546
| 26.138528 | 153 | 0.538044 | 4.778201 | false | false | false | false |
koscida/Kos_AMAD_Spring2015
|
Fall_16/Life/Life/CustomScrollView.swift
|
1
|
5871
|
//
// CustomScrollView.swift
// Life
//
// Created by Brittany Kos on 11/6/16.
// Copyright © 2016 Kode Studios. All rights reserved.
//
// All code here copied directly from:
// http://stackoverflow.com/questions/34229839/how-to-create-a-vertical-scrolling-menu-in-spritekit
//
// Creates a sustom scrolling screen (skscene)
//
import Foundation
import SpriteKit
/// Scroll direction
enum ScrollDirection {
case vertical // cases start with small letters as I am following Swift 3 guildlines.
case horizontal
}
class CustomScrollView: UIScrollView {
// MARK: - Static Properties
/// Touches allowed
static var disabledTouches = false
/// Scroll view
private static var scrollView: UIScrollView!
// MARK: - Properties
/// Current scene
private let currentScene: SKScene
/// Moveable node
private let moveableNode: SKNode
/// Scroll direction
private let scrollDirection: ScrollDirection
/// Touched nodes
private var nodesTouched = [AnyObject]()
// MARK: - Init
init(frame: CGRect, scene: SKScene, moveableNode: SKNode, scrollDirection: ScrollDirection) {
self.currentScene = scene
self.moveableNode = moveableNode
self.scrollDirection = scrollDirection
super.init(frame: frame)
CustomScrollView.scrollView = self
self.frame = frame
delegate = self
indicatorStyle = .White
scrollEnabled = true
userInteractionEnabled = true
//canCancelContentTouches = false
//self.minimumZoomScale = 1
//self.maximumZoomScale = 3
if scrollDirection == .horizontal {
let flip = CGAffineTransformMakeScale(-1,-1)
transform = flip
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - Touches
extension CustomScrollView {
/// Began
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
print("---------- TOUCHES BEGAN (CustomScrollView) ----------")
for touch in touches {
let location = touch.locationInNode(currentScene)
guard !CustomScrollView.disabledTouches else { return }
/// Call touches began in current scene
currentScene.touchesBegan(touches, withEvent: event)
/// Call touches began in all touched nodes in the current scene
nodesTouched = currentScene.nodesAtPoint(location)
for node in nodesTouched {
node.touchesBegan(touches, withEvent: event)
}
}
}
/// Moved
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
print("---------- TOUCHES MOVED (CustomScrollView) ----------")
for touch in touches {
let location = touch.locationInNode(currentScene)
guard !CustomScrollView.disabledTouches else { return }
/// Call touches moved in current scene
currentScene.touchesMoved(touches, withEvent: event)
/// Call touches moved in all touched nodes in the current scene
nodesTouched = currentScene.nodesAtPoint(location)
for node in nodesTouched {
node.touchesMoved(touches, withEvent: event)
}
}
}
/// Ended
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
print("---------- TOUCHES ENDED (CustomScrollView) ----------")
for touch in touches {
let location = touch.locationInNode(currentScene)
guard !CustomScrollView.disabledTouches else { return }
/// Call touches ended in current scene
currentScene.touchesEnded(touches, withEvent: event)
/// Call touches ended in all touched nodes in the current scene
nodesTouched = currentScene.nodesAtPoint(location)
for node in nodesTouched {
node.touchesEnded(touches, withEvent: event)
}
}
}
/// Cancelled
override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
print("---------- TOUCHES CANCELLED (CustomScrollView) ----------")
for touch in touches! {
let location = touch.locationInNode(currentScene)
guard !CustomScrollView.disabledTouches else { return }
/// Call touches cancelled in current scene
currentScene.touchesCancelled(touches, withEvent: event)
/// Call touches cancelled in all touched nodes in the current scene
nodesTouched = currentScene.nodesAtPoint(location)
for node in nodesTouched {
node.touchesCancelled(touches, withEvent: event)
}
}
}
}
// MARK: - Touch Controls
extension CustomScrollView {
/// Disable
class func disable() {
CustomScrollView.scrollView?.userInteractionEnabled = false
CustomScrollView.disabledTouches = true
}
/// Enable
class func enable() {
CustomScrollView.scrollView?.userInteractionEnabled = true
CustomScrollView.disabledTouches = false
}
}
// MARK: - Delegates
extension CustomScrollView: UIScrollViewDelegate {
func scrollViewDidScroll(scrollView: UIScrollView) {
if scrollDirection == .horizontal {
moveableNode.position.x = scrollView.contentOffset.x
} else {
moveableNode.position.y = scrollView.contentOffset.y
}
}
}
|
gpl-3.0
|
bf2575b50042fce699e33e395466591a
| 29.9 | 99 | 0.59983 | 5.430157 | false | false | false | false |
ynaoto/VSidoConnectTest
|
VsidoTest3/VsidoTest3/IKParamsViewController.swift
|
1
|
1276
|
//
// IKParamsViewController.swift
// VsidoTest3
//
// Created by Naoto Yoshioka on 2015/04/12.
// Copyright (c) 2015年 Naoto Yoshioka. All rights reserved.
//
import Cocoa
class IKParamsViewController: NSViewController {
@IBOutlet weak var 有効チェック: NSButton!
var 名前: String!
var kid: UInt8!
var 有効: Bool = false
var 目標値設定_位置x: Int8 = 0
var 目標値設定_位置y: Int8 = 0
var 目標値設定_位置z: Int8 = 0
var 目標値設定_姿勢x: Int8 = 0
var 目標値設定_姿勢y: Int8 = 0
var 目標値設定_姿勢z: Int8 = 0
var 目標値設定_トルクx: Int8 = 0
var 目標値設定_トルクy: Int8 = 0
var 目標値設定_トルクz: Int8 = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
var topLevelObjects: NSArray?
let result = NSBundle.mainBundle().loadNibNamed("IKParamsViewController", owner: self, topLevelObjects: &topLevelObjects)
assert(result, "could not load XIB file")
for obj in topLevelObjects! as Array {
if let view = obj as? NSView {
self.view.addSubview(view)
}
}
有効チェック.title = 名前
}
}
|
mit
|
4db3f7c4e23fa9923451d97fbe1737c0
| 25.333333 | 129 | 0.610307 | 3.196532 | false | false | false | false |
peaks-cc/iOS11_samplecode
|
chapter_02/common/ARPlaneAnchor+Visualize.swift
|
1
|
1732
|
//
// ARPlaneAnchor+Visualize.swift
//
// Created by Shuichi Tsutsumi on 2017/08/29.
// Copyright © 2017 Shuichi Tsutsumi. All rights reserved.
//
import Foundation
import ARKit
extension ARPlaneAnchor {
func addPlaneNode(on node: SCNNode, color: UIColor) {
// 平面ジオメトリを作成
let geometry = SCNPlane(width: CGFloat(extent.x), height: CGFloat(extent.z))
geometry.materials.first?.diffuse.contents = color
// 平面ジオメトリを持つノードを作成
let planeNode = SCNNode(geometry: geometry)
planeNode.transform = SCNMatrix4MakeRotation(-Float.pi / 2.0, 1, 0, 0)
DispatchQueue.main.async(execute: {
node.addChildNode(planeNode)
})
}
func updatePlaneNode(on node: SCNNode) {
DispatchQueue.main.async(execute: {
for childNode in node.childNodes {
guard let plane = childNode.geometry as? SCNPlane else {continue}
guard !PlaneSizeEqualToExtent(plane: plane, extent: self.extent) else {continue}
// 平面ジオメトリのサイズを更新
print("current plane size: (\(plane.width), \(plane.height))")
plane.width = CGFloat(self.extent.x)
plane.height = CGFloat(self.extent.z)
print("updated plane size: (\(plane.width), \(plane.height))")
break
}
})
}
}
fileprivate func PlaneSizeEqualToExtent(plane: SCNPlane, extent: vector_float3) -> Bool {
if plane.width != CGFloat(extent.x) || plane.height != CGFloat(extent.z) {
return false
} else {
return true
}
}
|
mit
|
4bab66f8528185c2ece239e176643674
| 30.150943 | 96 | 0.591763 | 4.179747 | false | false | false | false |
coderMONSTER/iosstar
|
iOSStar/General/Base/BaseTableViewController.swift
|
4
|
5692
|
//
// BaseTableViewController.swift
// viossvc
//
// Created by yaowang on 2016/10/27.
// Copyright © 2016年 ywwlcom.yundian. All rights reserved.
//
import Foundation
import SVProgressHUD
class BaseTableViewController: UITableViewController , TableViewHelperProtocol {
var tableViewHelper:TableViewHelper = TableViewHelper();
override func viewDidLoad() {
super.viewDidLoad();
if tableView.tableFooterView == nil {
tableView.tableFooterView = UIView(frame:CGRect(x: 0,y: 0,width: 0,height: 0.5));
}
}
//友盟页面统计
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// MobClick.beginLogPageView(NSStringFromClass(self.classForCoder))
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// MobClick.beginLogPageView(NSStringFromClass(self.classForCoder))
SVProgressHUD.dismiss()
// NotificationCenter.default.removeObserver(self, name: Notification.Name.init(rawValue: AppConst.NoticeKey.onlyLogin.rawValue), object: nil)
}
//MARK:TableViewHelperProtocol
func isCacheCellHeight() -> Bool {
return false;
}
func isCalculateCellHeight() ->Bool {
return isCacheCellHeight();
}
func isSections() ->Bool {
return false;
}
func tableView(_ tableView:UITableView ,cellIdentifierForRowAtIndexPath indexPath: IndexPath) -> String? {
return tableViewHelper.tableView(tableView, cellIdentifierForRowAtIndexPath: indexPath, controller: self);
}
func tableView(_ tableView:UITableView ,cellDataForRowAtIndexPath indexPath: IndexPath) -> AnyObject? {
return nil;
}
//MARK: -UITableViewDelegate
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell:UITableViewCell? = super.tableView(tableView,cellForRowAt:indexPath);
if cell == nil {
cell = tableViewHelper.tableView(tableView, cellForRowAtIndexPath: indexPath, controller: self);
}
return cell!;
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
tableViewHelper.tableView(tableView, willDisplayCell: cell, forRowAtIndexPath: indexPath, controller: self);
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if( isCalculateCellHeight() ) {
let cellHeight:CGFloat = tableViewHelper.tableView(tableView, heightForRowAtIndexPath: indexPath, controller: self);
if( cellHeight != CGFloat.greatestFiniteMagnitude ) {
return cellHeight;
}
}
return super.tableView(tableView, heightForRowAt: indexPath);
}
}
class BaseRefreshTableViewController :BaseTableViewController {
override func viewDidLoad() {
super.viewDidLoad();
self.setupRefreshControl();
}
internal func completeBlockFunc()->CompleteBlock {
return { [weak self] (obj) in
self?.didRequestComplete(obj)
}
}
internal func didRequestComplete(_ data:AnyObject?) {
endRefreshing()
self.tableView.reloadData()
}
override func didRequestError(_ error:NSError) {
self.endRefreshing()
super.didRequestError(error)
}
deinit {
performSelectorRemoveRefreshControl();
}
}
class BaseListTableViewController :BaseRefreshTableViewController {
internal var dataSource:Array<AnyObject>?;
override func didRequestComplete(_ data: AnyObject?) {
dataSource = data as? Array<AnyObject>;
super.didRequestComplete(dataSource as AnyObject?);
}
//MARK: -UITableViewDelegate
override func numberOfSections(in tableView: UITableView) -> Int {
var count:Int = dataSource != nil ? 1 : 0;
if isSections() && count != 0 {
count = dataSource!.count;
}
return count;
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var datas:Array<AnyObject>? = dataSource;
if dataSource != nil && isSections() {
datas = dataSource![section] as? Array<AnyObject>;
}
return datas == nil ? 0 : datas!.count;
}
//MARK:TableViewHelperProtocol
override func tableView(_ tableView:UITableView ,cellDataForRowAtIndexPath indexPath: IndexPath) -> AnyObject? {
var datas:Array<AnyObject>? = dataSource;
if dataSource != nil && isSections() {
datas = dataSource![indexPath.section] as? Array<AnyObject>;
}
return (datas != nil && datas!.count > indexPath.row ) ? datas![indexPath.row] : nil;
}
}
class BasePageListTableViewController :BaseListTableViewController {
override func viewDidLoad() {
super.viewDidLoad();
setupLoadMore();
}
override func didRequestComplete(_ data: AnyObject?) {
tableViewHelper.didRequestComplete(&self.dataSource,
pageDatas: data as? Array<AnyObject>, controller: self);
super.didRequestComplete(self.dataSource as AnyObject?);
}
override func didRequestError(_ error:NSError) {
if (!(self.pageIndex == 1) ) {
self.errorLoadMore()
}
self.setIsLoadData(true)
super.didRequestError(error)
}
deinit {
removeLoadMore();
}
}
|
gpl-3.0
|
59865b7950934f2c18294b3ef2511e2f
| 31.255682 | 149 | 0.644707 | 5.295709 | false | false | false | false |
JasonChen2015/Paradise-Lost
|
Paradise Lost/Classes/Models/ForecastManager.swift
|
3
|
1773
|
//
// JsonParser.swift
// Paradise Lost
//
// Created by jason on 21/4/2017.
// Copyright © 2017 Jason Chen. All rights reserved.
//
import Foundation
import CoreLocation
class ForecastManager {
static let shareInstance = ForecastManager()
// MARK: https://darksky.net
private let darkskyLink = "https://api.darksky.net/forecast/"
private let darkskyKey = "cb16118455c632ec0de548eda02d6570"
private var darksky: Forecast?
func setJSON(data: Data?) {
do {
let darkskyJSON = try JSONSerialization.jsonObject(with: data!, options:[]) as! [String: AnyObject]
darksky = Forecast(fromJSON: darkskyJSON)
} catch {
// handle error
print(error)
}
}
func getDarkSkyLink(_ latitude: Double, _ longitude: Double) -> String {
return darkskyLink + darkskyKey + "/" + String(latitude) + "," + String(longitude)
}
// MARK: temperature conversion
func fahrenheitToCelsius(temp: Double) -> Double {
return (temp - 32) * 5 / 9
}
func celsiusToFahrenheit(temp: Double) -> Double {
return temp * 1.8 + 32
}
// MARK: getters and setters
func getWeatherIcon() -> String? {
return darksky?.icon
}
func getTime() -> Date? {
return darksky?.time
}
func getSummary() -> String? {
return darksky?.summary
}
func getTemperature(inCelsius: Bool) -> Double? {
if inCelsius {
if let t = darksky?.temperature {
return fahrenheitToCelsius(temp: t)
} else {
return nil
}
} else {
return darksky?.temperature
}
}
}
|
mit
|
e4d262a2c02af2edc97e48431a0e3ff9
| 23.273973 | 111 | 0.562641 | 4.280193 | false | false | false | false |
alobanov/ALFormBuilder
|
FormBuilder/vendors/Atlantis.swift
|
2
|
23042
|
//
// Atlantis.swift
// Atlantis
//
// Created by Andrew Aquino on 9/29/15.
// Copyright © 2015 Andrew Aquino. All rights reserved.
//
import Foundation
import UIKit
import CoreData
public let log = Atlantis.Logger()
@objc
public class Atlantis: NSObject {
@objc
public static var logger: Atlantis.Logger { get { return log } }
public enum LogLevel: Int {
case verbose = 5
case info = 4
case warning = 3
case debug = 2
case error = 1
case none = 0
}
@objc
public class Configuration: NSObject {
// Reserved Variables
fileprivate struct Reserved {
fileprivate static let ESCAPE = "\u{001b}["
fileprivate static let RESET_FG = ESCAPE + "fg;" // Clear any foreground color
fileprivate static let RESET_BG = ESCAPE + "bg;" // Clear any background color
fileprivate static let RESET = ESCAPE + ";" // Clear any foreground or background color
}
// Color Configurations
public struct logColors {
fileprivate static var _verbose: XCodeColor = XCodeColor.purple
public static var verbose: XCodeColor? {
get { return _verbose }
set {
if let newValue = newValue {
_verbose = newValue
} else {
_verbose = XCodeColor.purple
}
}
}
fileprivate static var _info: XCodeColor = XCodeColor.green
public static var info: XCodeColor? {
get { return _info }
set {
if let newValue = newValue {
_info = newValue
} else {
_info = XCodeColor.green
}
}
}
fileprivate static var _warning: XCodeColor = XCodeColor.yellow
public static var warning: XCodeColor? {
get { return _warning }
set {
if let newValue = newValue {
_warning = newValue
} else {
_warning = XCodeColor.yellow
}
}
}
fileprivate static var _debug: XCodeColor = XCodeColor.blue
public static var debug: XCodeColor? {
get { return _debug}
set {
if let newValue = newValue {
_debug = newValue
} else {
_debug = XCodeColor.blue
}
}
}
fileprivate static var _error: XCodeColor = XCodeColor.red
public static var error: XCodeColor? {
get { return _error}
set {
if let newValue = newValue {
_error = newValue
} else {
_error = XCodeColor.red
}
}
}
}
// configured log level
public static var logLevel: LogLevel = .verbose
public static var hasWhiteBackground: Bool = false
public static var hasColoredLogs: Bool = false
public static var hasColoredPrints: Bool = false
public static var showExtraInfo: Bool = true
public static var filteredErrorCodes: [Int] = [-999]
public static var highlightsErrors: Bool = false
public static var coloredLogLevels: [Atlantis.LogLevel] = [.verbose, .info, .warning, .debug, .error]
public static var alignmentThreshold: Int = 5
}
fileprivate struct Singleton {
fileprivate static let LogQueue = DispatchQueue(label: "Atlantis.LogQueue")
}
public struct XCodeColor {
fileprivate static let escape = "\u{001b}["
fileprivate static let resetFg = "\u{001b}[fg;"
fileprivate static let resetBg = "\u{001b}[bg;"
fileprivate static let reset = "\u{001b}[;"
fileprivate var fg: (Int, Int, Int)? = nil
fileprivate var bg: (Int, Int, Int)? = nil
fileprivate mutating func whiteBG() -> XCodeColor {
if Configuration.hasWhiteBackground {
bg = (255, 255, 255)
}
return self
}
fileprivate mutating func forceWhiteBG() -> XCodeColor {
bg = (255, 255, 255)
return self
}
fileprivate func format() -> String {
var format = ""
if fg == nil && bg == nil {
// neither set, return reset value
return XCodeColor.reset
}
if let fg = fg {
format += "\(XCodeColor.escape)fg\(fg.0),\(fg.1),\(fg.2);"
}
else {
format += XCodeColor.resetFg
}
if let bg = bg {
format += "\(XCodeColor.escape)bg\(bg.0),\(bg.1),\(bg.2);"
}
else {
format += XCodeColor.resetBg
}
return format
}
public init(fg: (Int, Int, Int)? = nil, bg: (Int, Int, Int)? = nil) {
self.fg = fg
self.bg = bg
}
#if os(iOS)
public init(fg: UIColor, bg: UIColor? = nil) {
var redComponent: CGFloat = 0
var greenComponent: CGFloat = 0
var blueComponent: CGFloat = 0
var alphaComponent: CGFloat = 0
fg.getRed(&redComponent, green: &greenComponent, blue: &blueComponent, alpha:&alphaComponent)
self.fg = (Int(redComponent * 255), Int(greenComponent * 255), Int(blueComponent * 255))
if let bg = bg {
bg.getRed(&redComponent, green: &greenComponent, blue: &blueComponent, alpha:&alphaComponent)
self.bg = (Int(redComponent * 255), Int(greenComponent * 255), Int(blueComponent * 255))
}
else {
self.bg = nil
}
}
#else
public init(fg: NSColor, bg: NSColor? = nil) {
if let fgColorSpaceCorrected = fg.colorUsingColorSpaceName(NSCalibratedRGBColorSpace) {
self.fg = (Int(fgColorSpaceCorrected.redComponent * 255), Int(fgColorSpaceCorrected.greenComponent * 255), Int(fgColorSpaceCorrected.blueComponent * 255))
}
else {
self.fg = nil
}
if let bg = bg,
let bgColorSpaceCorrected = bg.colorUsingColorSpaceName(NSCalibratedRGBColorSpace) {
self.bg = (Int(bgColorSpaceCorrected.redComponent * 255), Int(bgColorSpaceCorrected.greenComponent * 255), Int(bgColorSpaceCorrected.blueComponent * 255))
}
else {
self.bg = nil
}
}
#endif
public static let red: XCodeColor = {
return XCodeColor(fg: (255, 0, 0))
}()
public static let green: XCodeColor = {
return XCodeColor(fg: (0, 255, 0))
}()
public static let blue: XCodeColor = {
// actual blue is 0, 0, 255
// dodger blue
return XCodeColor(fg: (30, 144, 255))
}()
public static let black: XCodeColor = {
return XCodeColor(fg: (0, 0, 0))
}()
public static let white: XCodeColor = {
return XCodeColor(fg: (255, 255, 255))
}()
public static let lightGrey: XCodeColor = {
return XCodeColor(fg: (211, 211, 211))
}()
public static let darkGrey: XCodeColor = {
return XCodeColor(fg: (169, 169, 169))
}()
public static let orange: XCodeColor = {
return XCodeColor(fg: (255, 165, 0))
}()
public static let whiteOnRed: XCodeColor = {
return XCodeColor(fg: (255, 255, 255), bg: (255, 0, 0))
}()
public static let darkGreen: XCodeColor = {
return XCodeColor(fg: (0, 128, 0))
}()
public static let purple: XCodeColor = {
return XCodeColor(fg: (160, 32, 240))
}()
public static let yellow: XCodeColor = {
return XCodeColor(fg: (255, 255, 0))
}()
}
@objc
public class Logger: NSObject {
fileprivate let logQueue = Singleton.LogQueue
fileprivate
typealias closure = () -> Void
fileprivate typealias void = Void
fileprivate static var maxCharCount: Int = 0
fileprivate static var smallerCountOccurances: Int = 0
fileprivate struct LogSettings {
fileprivate var logLevel: LogLevel
fileprivate var functionName: String
fileprivate var fileName: String
fileprivate var lineNumber: Int
init(logLevel: LogLevel, _ functionName: String, _ fileName: String, _ lineNumber: Int) {
self.logLevel = logLevel
self.functionName = functionName
self.fileName = fileName
self.lineNumber = lineNumber
}
fileprivate func sourceString() -> String {
if Configuration.showExtraInfo {
let array = fileName.components(separatedBy: "/")
var name: String = ""
if let string = array.last {
name = string
}
// date
let date = Date()
let formatter = DateFormatter()
formatter.dateStyle = .short
formatter.timeStyle = .short
formatter.timeZone = TimeZone(identifier: "PT")
let dateString = formatter.string(from: date)
.replacingOccurrences(of: " ", with: "")
.replacingOccurrences(of: ",", with: "@")
let string = "\(dateString)/\(name)/\(functionName)/line:\(lineNumber)"
return string
}
return ""
}
}
fileprivate static func acceptableLogLevel(_ logSettings: Atlantis.Logger.LogSettings) -> Bool {
return logSettings.logLevel.rawValue <= Atlantis.Configuration.logLevel.rawValue
}
public let tap = Tap()
public struct Tap {
public func verbose(_ arg: Any, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) -> Any {
Singleton.LogQueue.async {
let logSettings = LogSettings(logLevel: .verbose, functionName,fileName, lineNumber)
if Logger.acceptableLogLevel(logSettings) {
Logger.log(arg, logSettings)
}
}
return arg
}
public func info(_ arg: Any, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) -> Any {
Singleton.LogQueue.async {
let logSettings = LogSettings(logLevel: .info, functionName,fileName, lineNumber)
if Logger.acceptableLogLevel(logSettings) {
Logger.log(arg, logSettings)
}
}
return arg
}
public func warning(_ arg: Any, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) -> Any {
Singleton.LogQueue.async {
let logSettings = LogSettings(logLevel: .warning, functionName,fileName, lineNumber)
if Logger.acceptableLogLevel(logSettings) {
Logger.log(arg, logSettings)
}
}
return arg
}
public func debug(_ arg: Any, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) -> Any {
Singleton.LogQueue.async {
let logSettings = LogSettings(logLevel: .debug, functionName,fileName, lineNumber)
if Logger.acceptableLogLevel(logSettings) {
Logger.log(arg, logSettings)
}
}
return arg
}
public func error(_ arg: Any, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) -> Any {
Singleton.LogQueue.async {
let logSettings = LogSettings(logLevel: .error, functionName,fileName, lineNumber)
if Logger.acceptableLogLevel(logSettings) {
Logger.log(arg, logSettings)
}
}
return arg
}
}
public func verbose(_ args: Any?..., functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) {
logQueue.async {
let logSettings = LogSettings(logLevel: .verbose, functionName,fileName, lineNumber)
if Logger.acceptableLogLevel(logSettings) {
for arg in args {
Logger.log(arg, logSettings)
}
}
}
}
public func info(_ args: Any?..., functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) {
logQueue.async {
let logSettings = LogSettings(logLevel: .info, functionName,fileName, lineNumber)
if Logger.acceptableLogLevel(logSettings) {
for arg in args {
Logger.log(arg, logSettings)
}
}
}
}
public func warning(_ args: Any?..., functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) {
logQueue.async {
let logSettings = LogSettings(logLevel: .warning, functionName,fileName, lineNumber)
if Logger.acceptableLogLevel(logSettings) {
for arg in args {
Logger.log(arg, logSettings)
}
}
}
}
public func debug(_ args: Any?..., functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) {
logQueue.async {
let logSettings = LogSettings(logLevel: .debug, functionName,fileName, lineNumber)
if Logger.acceptableLogLevel(logSettings) {
for arg in args {
Logger.log(arg, logSettings)
}
}
}
}
public func error(_ args: Any?..., functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) {
logQueue.async {
let logSettings = LogSettings(logLevel: .error, functionName,fileName, lineNumber)
if Logger.acceptableLogLevel(logSettings) {
for arg in args {
Logger.log(arg, logSettings)
}
}
}
}
fileprivate static func getEscapeString() -> String {
if Configuration.hasColoredLogs { return Configuration.Reserved.ESCAPE }
else { return "" }
}
fileprivate static func getResetString() -> String {
if Configuration.hasColoredLogs { return Configuration.Reserved.RESET }
else { return "" }
}
fileprivate static func getRGBString(_ logLevel: LogLevel) -> String {
if Configuration.hasColoredLogs {
switch logLevel {
case .verbose:
if Atlantis.Configuration.coloredLogLevels.contains(.verbose) {
return Configuration.logColors._verbose.whiteBG().format()
}
break
case .info:
if Atlantis.Configuration.coloredLogLevels.contains(.info) {
return Configuration.logColors._info.whiteBG().format()
}
break
case .warning:
if Atlantis.Configuration.coloredLogLevels.contains(.warning) {
return Configuration.logColors._warning.whiteBG().format()
}
break
case .debug:
if Atlantis.Configuration.coloredLogLevels.contains(.debug) {
return Configuration.logColors._debug.whiteBG().format()
}
break
case .error:
if Atlantis.Configuration.coloredLogLevels.contains(.error) {
return Configuration.logColors._error.whiteBG().format()
}
break
case .none:
break
}
} else if Configuration.highlightsErrors {
switch logLevel {
case .error:
return Configuration.logColors._error.whiteBG().format()
default:
break
}
}
return ""
}
fileprivate static func getLogLevelString(_ logLevel: LogLevel) -> String {
let level: String = "\(logLevel)"
let tab1: String = ": "
let tab2: String = ": "
let tab3: String = ": "
switch logLevel {
case .verbose: return level + tab1
case .info: return level + tab2
case .warning: return level + tab1
case .debug: return level + tab3
case .error: return level + tab3
case .none: return level
}
}
fileprivate static func toPrettyJSONString(_ object: Any?) -> String? {
guard let object = object else { return nil }
do {
if JSONSerialization.isValidJSONObject(object) {
let data = try JSONSerialization.data(withJSONObject: object, options: .prettyPrinted)
if let string = NSString(data: data, encoding: String.Encoding.utf8.rawValue) as String? {
return "\n" + string
}
}
throw NSError(domain: "unable to parse json object", code: 400, userInfo: nil)
}
catch { return nil }
}
fileprivate static func addDash(_ value: Any?) -> String {
var string = "nil"
if let value = value { string = "\(value)" }
if Configuration.showExtraInfo { return "- " + (string.isEmpty ? "\"\"" : string) }
return string
}
fileprivate static func calculateLegibleWhitespace(_ log: String, startString: String, endString: String, logLevel: LogLevel) -> String {
let charCount = startString.debugDescription.count
maxCharCount = maxCharCount > charCount ? maxCharCount : charCount
smallerCountOccurances = (charCount < maxCharCount) ? (smallerCountOccurances + 1) : 0
if smallerCountOccurances > Atlantis.Configuration.alignmentThreshold {
maxCharCount = 0 // reset the max char count
return log + endString
} else {
var whitespace: String = ""
if maxCharCount - charCount > 0 {
for _ in 0 ..< maxCharCount - charCount {
whitespace += " "
}
}
let string: String = log + whitespace + endString
return string
}
}
fileprivate static func log(_ value: Any?, _ logSettings: LogSettings) {
// get the type name
var type: String!; if let value = value {
type = String(describing: Mirror(reflecting: value).subjectType).trimmingCharacters(in: CharacterSet.letters.inverted)
}; type = type ?? ""
let logLevel = logSettings.logLevel
var jsonString: String? = nil
if let value = value {
switch value {
// regular data types
case _ as Int: break
case _ as Double: break
case _ as Float: break
case _ as String: break
case _ as Bool: break
// arrays
case let array as NSArray: jsonString = toPrettyJSONString(NSObject.reflect(objects: array)); break
// dictionaries
case let dict as NSDictionary: jsonString = toPrettyJSONString(dict) ?? "\n\(dict)"; break
// errors
case let error as NSError:
// filter out errors based in filtered error code configurations
if Atlantis.Configuration.filteredErrorCodes.contains(error.code) { return }
let properties: [String: Any] = [
"domain": error.domain,
"code": error.code,
"localizedDescription": error.localizedDescription,
"userInfo": error.userInfo
]
jsonString = toPrettyJSONString(properties)
break
// objects
case let object as NSObject:
let dictionary = NSObject.reflect(object: object)
if !dictionary.isEmpty { jsonString = toPrettyJSONString(dictionary) }
break
default:
break
}
}
let string = jsonString ?? addDash(value)
let color = getRGBString(logLevel)
let reset = getResetString()
let level = getLogLevelString(logLevel)
let source = "[\(logSettings.sourceString())/type:\(type ?? "nil")] "
let coloredString: String = Atlantis.Configuration.hasColoredPrints ? (color + string + reset) : string
let log: String = "\(color)\(level)\(reset)\(source)"
let prettyLog: String = calculateLegibleWhitespace(log, startString: "\(level)\(source)", endString: coloredString, logLevel: logLevel)
DispatchQueue.main.async { print(prettyLog) }
}
}
}
extension NSObject {
public class func reflect(objects: NSArray?) -> [Any] {
guard let objects = objects else { return [] }
return objects.map { value -> Any in
// strings
if let value = value as? String { return value }
else if let value = value as? [String] { return value }
// booleans
else if value is Bool { return value }
// numbers
else if let value = value as? Int { return value }
else if let value = value as? [Int] { return value }
else if let value = value as? Float { return value }
else if let value = value as? [Float] { return value }
else if let value = value as? Double { return value }
else if let value = value as? [Double] { return value }
// dictionaries
else if let value = value as? NSDictionary { return value }
// arrays
else if let value = value as? NSArray { return NSObject.reflect(objects: value) }
// objects
else { return NSObject.reflect(object: value) }
}
}
public class func reflect(object: Any?) -> [String: Any] {
guard let object = object else { return [:] }
var dictionary: [String: Any] = [:]
Mirror(reflecting: object).children.forEach { label, value in
// strings
if let key = label, let value = value as? String { dictionary.updateValue(value, forKey: key) }
else if let key = label, let value = value as? [String] { dictionary.updateValue(value, forKey: key) }
// numbers
else if let key = label, let value = value as? Int { dictionary.updateValue(value, forKey: key) }
else if let key = label, let value = value as? [Int] { dictionary.updateValue(value, forKey: key) }
else if let key = label, let value = value as? Float { dictionary.updateValue(value, forKey: key) }
else if let key = label, let value = value as? [Float] { dictionary.updateValue(value, forKey: key) }
else if let key = label, let value = value as? Double { dictionary.updateValue(value, forKey: key) }
else if let key = label, let value = value as? [Double] { dictionary.updateValue(value, forKey: key) }
// booleans
else if let key = label, let value = value as? Bool { dictionary.updateValue(value, forKey: key) }
else if let key = label, let value = value as? [Bool] { dictionary.updateValue(value, forKey: key) }
// dictionaries
else if let key = label, let value = value as? NSDictionary { dictionary.updateValue(value, forKey: key) }
// objects
else if let key = label, let value = value as? NSArray {
let objects = NSObject.reflect(objects: value)
if objects.isEmpty { dictionary.updateValue("null", forKey: key) }
else { dictionary.updateValue(objects, forKey: key) }
} else if let key = label, let value = value as? NSObject {
let object = NSObject.reflect(object: value)
if object.isEmpty { dictionary.updateValue(value, forKey: key) }
else { dictionary.updateValue(object, forKey: key) }
} else if let key = label {
let object = NSObject.reflect(object: value)
if object.isEmpty { dictionary.updateValue("null", forKey: key) }
else { dictionary.updateValue(object, forKey: key) }
}
}
return dictionary
}
}
|
mit
|
ac827e56ec1afb440eb9bb24eca0e536
| 32.248196 | 158 | 0.588603 | 4.692668 | false | false | false | false |
ryanbooker/SwiftCheck
|
SwiftCheck/WitnessedArbitrary.swift
|
1
|
10618
|
//
// WitnessedArbitrary.swift
// SwiftCheck
//
// Created by Robert Widmann on 12/15/15.
// Copyright © 2015 Robert Widmann. All rights reserved.
//
extension Array where Element : Arbitrary {
public static var arbitrary : Gen<Array<Element>> {
return Gen.sized { n in
return Gen<Int>.choose((0, n)).flatMap { k in
if k == 0 {
return Gen.pure([])
}
return sequence((0...k).map { _ in Element.arbitrary })
}
}
}
public static func shrink(bl : Array<Element>) -> [[Element]] {
let rec : [[Element]] = shrinkOne(bl)
return Int.shrink(bl.count).reverse().flatMap({ k in removes(k.successor(), n: bl.count, xs: bl) }) + rec
}
}
extension Array : WitnessedArbitrary {
public typealias Param = Element
public static func forAllWitnessed<A : Arbitrary>(wit : A -> Element, pf : ([Element] -> Testable)) -> Property {
return forAllShrink([A].arbitrary, shrinker: [A].shrink, f: { bl in
return pf(bl.map(wit))
})
}
}
extension AnyBidirectionalCollection where Element : Arbitrary {
public static var arbitrary : Gen<AnyBidirectionalCollection<Element>> {
return AnyBidirectionalCollection.init <^> [Element].arbitrary
}
public static func shrink(bl : AnyBidirectionalCollection<Element>) -> [AnyBidirectionalCollection<Element>] {
return [Element].shrink([Element](bl)).map(AnyBidirectionalCollection.init)
}
}
extension AnyBidirectionalCollection : WitnessedArbitrary {
public typealias Param = Element
public static func forAllWitnessed<A : Arbitrary>(wit : A -> Element, pf : (AnyBidirectionalCollection<Element> -> Testable)) -> Property {
return forAllShrink(AnyBidirectionalCollection<A>.arbitrary, shrinker: AnyBidirectionalCollection<A>.shrink, f: { bl in
return pf(AnyBidirectionalCollection<Element>(bl.map(wit)))
})
}
}
extension AnySequence where Element : Arbitrary {
public static var arbitrary : Gen<AnySequence<Element>> {
return AnySequence.init <^> [Element].arbitrary
}
public static func shrink(bl : AnySequence<Element>) -> [AnySequence<Element>] {
return [Element].shrink([Element](bl)).map(AnySequence.init)
}
}
extension AnySequence : WitnessedArbitrary {
public typealias Param = Element
public static func forAllWitnessed<A : Arbitrary>(wit : A -> Element, pf : (AnySequence<Element> -> Testable)) -> Property {
return forAllShrink(AnySequence<A>.arbitrary, shrinker: AnySequence<A>.shrink, f: { bl in
return pf(AnySequence<Element>(bl.map(wit)))
})
}
}
extension ArraySlice where Element : Arbitrary {
public static var arbitrary : Gen<ArraySlice<Element>> {
return ArraySlice.init <^> [Element].arbitrary
}
public static func shrink(bl : ArraySlice<Element>) -> [ArraySlice<Element>] {
return [Element].shrink([Element](bl)).map(ArraySlice.init)
}
}
extension ArraySlice : WitnessedArbitrary {
public typealias Param = Element
public static func forAllWitnessed<A : Arbitrary>(wit : A -> Element, pf : (ArraySlice<Element> -> Testable)) -> Property {
return forAllShrink(ArraySlice<A>.arbitrary, shrinker: ArraySlice<A>.shrink, f: { bl in
return pf(ArraySlice<Element>(bl.map(wit)))
})
}
}
extension CollectionOfOne where Element : Arbitrary {
public static var arbitrary : Gen<CollectionOfOne<Element>> {
return CollectionOfOne.init <^> Element.arbitrary
}
}
extension CollectionOfOne : WitnessedArbitrary {
public typealias Param = Element
public static func forAllWitnessed<A : Arbitrary>(wit : A -> Element, pf : (CollectionOfOne<Element> -> Testable)) -> Property {
return forAllShrink(CollectionOfOne<A>.arbitrary, shrinker: { _ in [] }, f: { (bl : CollectionOfOne<A>) -> Testable in
return pf(CollectionOfOne<Element>(wit(bl[.Zero])))
})
}
}
/// Generates an Optional of arbitrary values of type A.
extension Optional where Wrapped : Arbitrary {
public static var arbitrary : Gen<Optional<Wrapped>> {
return Gen<Optional<Wrapped>>.frequency([
(1, Gen<Optional<Wrapped>>.pure(.None)),
(3, liftM(Optional<Wrapped>.Some, Wrapped.arbitrary)),
])
}
public static func shrink(bl : Optional<Wrapped>) -> [Optional<Wrapped>] {
if let x = bl {
let rec : [Optional<Wrapped>] = Wrapped.shrink(x).map(Optional<Wrapped>.Some)
return [.None] + rec
}
return []
}
}
extension Optional : WitnessedArbitrary {
public typealias Param = Wrapped
public static func forAllWitnessed<A : Arbitrary>(wit : A -> Wrapped, pf : (Optional<Wrapped> -> Testable)) -> Property {
return forAllShrink(Optional<A>.arbitrary, shrinker: Optional<A>.shrink, f: { bl in
return pf(bl.map(wit))
})
}
}
extension ContiguousArray where Element : Arbitrary {
public static var arbitrary : Gen<ContiguousArray<Element>> {
return ContiguousArray.init <^> [Element].arbitrary
}
public static func shrink(bl : ContiguousArray<Element>) -> [ContiguousArray<Element>] {
return [Element].shrink([Element](bl)).map(ContiguousArray.init)
}
}
extension ContiguousArray : WitnessedArbitrary {
public typealias Param = Element
public static func forAllWitnessed<A : Arbitrary>(wit : A -> Element, pf : (ContiguousArray<Element> -> Testable)) -> Property {
return forAllShrink(ContiguousArray<A>.arbitrary, shrinker: ContiguousArray<A>.shrink, f: { bl in
return pf(ContiguousArray<Element>(bl.map(wit)))
})
}
}
/// Generates an dictionary of arbitrary keys and values.
extension Dictionary where Key : Arbitrary, Value : Arbitrary {
public static var arbitrary : Gen<Dictionary<Key, Value>> {
return [Key].arbitrary.flatMap { k in
return [Value].arbitrary.flatMap { v in
return Gen.pure(Dictionary(Zip2Sequence(k, v)))
}
}
}
public static func shrink(d : Dictionary<Key, Value>) -> [Dictionary<Key, Value>] {
return d.map { Dictionary(Zip2Sequence(Key.shrink($0), Value.shrink($1))) }
}
}
extension Dictionary {
init<S : SequenceType where S.Generator.Element == Element>(_ pairs : S) {
self.init()
var g = pairs.generate()
while let (k, v): (Key, Value) = g.next() {
self[k] = v
}
}
}
extension EmptyCollection : Arbitrary {
public static var arbitrary : Gen<EmptyCollection<Element>> {
return Gen.pure(EmptyCollection())
}
}
extension HalfOpenInterval where Bound : protocol<Comparable, Arbitrary> {
public static var arbitrary : Gen<HalfOpenInterval<Bound>> {
return Bound.arbitrary.flatMap { l in
return Bound.arbitrary.flatMap { r in
return Gen.pure(HalfOpenInterval(min(l, r), max(l, r)))
}
}
}
public static func shrink(bl : HalfOpenInterval<Bound>) -> [HalfOpenInterval<Bound>] {
return zip(Bound.shrink(bl.start), Bound.shrink(bl.end)).map(HalfOpenInterval.init)
}
}
extension ImplicitlyUnwrappedOptional where Wrapped : Arbitrary {
public static var arbitrary : Gen<ImplicitlyUnwrappedOptional<Wrapped>> {
return ImplicitlyUnwrappedOptional.init <^> Optional<Wrapped>.arbitrary
}
public static func shrink(bl : ImplicitlyUnwrappedOptional<Wrapped>) -> [ImplicitlyUnwrappedOptional<Wrapped>] {
return Optional<Wrapped>.shrink(bl).map(ImplicitlyUnwrappedOptional.init)
}
}
extension ImplicitlyUnwrappedOptional : WitnessedArbitrary {
public typealias Param = Wrapped
public static func forAllWitnessed<A : Arbitrary>(wit : A -> Wrapped, pf : (ImplicitlyUnwrappedOptional<Wrapped> -> Testable)) -> Property {
return forAllShrink(ImplicitlyUnwrappedOptional<A>.arbitrary, shrinker: ImplicitlyUnwrappedOptional<A>.shrink, f: { bl in
return pf(bl.map(wit))
})
}
}
extension LazyCollection where Base : protocol<CollectionType, Arbitrary>, Base.Index : ForwardIndexType {
public static var arbitrary : Gen<LazyCollection<Base>> {
return LazyCollection<Base>.arbitrary
}
}
extension LazySequence where Base : protocol<SequenceType, Arbitrary> {
public static var arbitrary : Gen<LazySequence<Base>> {
return LazySequence<Base>.arbitrary
}
}
extension Range where Element : protocol<ForwardIndexType, Comparable, Arbitrary> {
public static var arbitrary : Gen<Range<Element>> {
return Element.arbitrary.flatMap { l in
return Element.arbitrary.flatMap { r in
return Gen.pure(Range(start: min(l, r), end: max(l, r)))
}
}
}
public static func shrink(bl : Range<Element>) -> [Range<Element>] {
return Zip2Sequence(Element.shrink(bl.startIndex), Element.shrink(bl.endIndex)).map(Range.init)
}
}
extension Repeat where Element : Arbitrary {
public static var arbitrary : Gen<Repeat<Element>> {
return Repeat.init <^> Gen<Any>.zip(Int.arbitrary, Element.arbitrary)
}
}
extension Repeat : WitnessedArbitrary {
public typealias Param = Element
public static func forAllWitnessed<A : Arbitrary>(wit : A -> Element, pf : (Repeat<Element> -> Testable)) -> Property {
return forAllShrink(Repeat<A>.arbitrary, shrinker: { _ in [] }, f: { bl in
let xs = bl.map(wit)
return pf(Repeat<Element>(count: xs.count, repeatedValue: xs.first!))
})
}
}
extension Set where Element : protocol<Arbitrary, Hashable> {
public static var arbitrary : Gen<Set<Element>> {
return Gen.sized { n in
return Gen<Int>.choose((0, n)).flatMap { k in
if k == 0 {
return Gen.pure(Set([]))
}
return Set.init <^> sequence(Array((0...k)).map { _ in Element.arbitrary })
}
}
}
public static func shrink(s : Set<Element>) -> [Set<Element>] {
return [Element].shrink([Element](s)).map(Set.init)
}
}
extension Set : WitnessedArbitrary {
public typealias Param = Element
public static func forAllWitnessed<A : Arbitrary>(wit : A -> Element, pf : (Set<Element> -> Testable)) -> Property {
return forAll { (xs : [A]) in
return pf(Set<Element>(xs.map(wit)))
}
}
}
// MARK: - Implementation Details Follow
private func bits<N : IntegerType>(n : N) -> Int {
if n / 2 == 0 {
return 0
}
return 1 + bits(n / 2)
}
private func removes<A : Arbitrary>(k : Int, n : Int, xs : [A]) -> [[A]] {
let xs1 : [A] = take(k, xs: xs)
let xs2 : [A] = drop(k, xs: xs)
if k > n {
return []
} else if xs2.isEmpty {
return [[]]
} else {
let rec : [[A]] = removes(k, n: n - k, xs: xs2).map({ xs1 + $0 })
return [xs2] + rec
}
}
private func take<T>(num : Int, xs : [T]) -> [T] {
let n = (num < xs.count) ? num : xs.count
return [T](xs[0..<n])
}
private func drop<T>(num : Int, xs : [T]) -> [T] {
let n = (num < xs.count) ? num : xs.count
return [T](xs[n..<xs.endIndex])
}
private func shrinkOne<A : Arbitrary>(xs : [A]) -> [[A]] {
if xs.isEmpty {
return [[A]]()
} else if let x : A = xs.first {
let xss = [A](xs[1..<xs.endIndex])
let a : [[A]] = A.shrink(x).map({ [$0] + xss })
let b : [[A]] = shrinkOne(xss).map({ [x] + $0 })
return a + b
}
fatalError("Array could not produce a first element")
}
|
mit
|
3315563cc18ef959b2141110f1d11d87
| 30.134897 | 141 | 0.693416 | 3.522561 | false | false | false | false |
damienpontifex/SwiftOpenCL
|
Sources/SwiftOpenCL/Buffer.swift
|
1
|
1541
|
import OpenCL
public class Buffer<T> {
public var buffer: cl_mem
var size: Int
var count: Int
public init(context: Context, memFlags: cl_mem_flags, data: [T]) throws {
count = data.count
size = MemoryLayout<T>.size * count
var err: cl_int = CL_SUCCESS
var localData = data
buffer = clCreateBuffer(context.context, memFlags, size, &localData, &err)
try ClError.check(err)
}
public convenience init(context: Context, readOnlyData: [T]) throws {
try self.init(context: context, memFlags: cl_mem_flags(CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR), data: readOnlyData)
}
public init(context: Context, count: Int) throws {
size = MemoryLayout<T>.size * count
self.count = count
var err: cl_int = CL_SUCCESS
buffer = clCreateBuffer(context.context, cl_mem_flags(CL_MEM_WRITE_ONLY), size, nil, &err)
try ClError.check(err)
}
public func enqueueRead(_ queue: CommandQueue) -> [T] {
let elements = UnsafeMutablePointer<T>.allocate(capacity: count)
clEnqueueReadBuffer(queue.queue, buffer, cl_bool(CL_TRUE), 0, size, elements, 0, nil, nil)
let array = Array<T>(UnsafeBufferPointer(start: elements, count: count))
elements.deallocate(capacity: count)
return array
}
public func enqueueWrite(_ queue: CommandQueue, data: [T]) {
// clEnqueueWriteBuffer(queue.queue, buffer, <#T##cl_bool#>, <#T##Int#>, <#T##Int#>, <#T##UnsafePointer<Void>#>, <#T##cl_uint#>, <#T##UnsafePointer<cl_event>#>, <#T##UnsafeMutablePointer<cl_event>#>)
}
deinit {
clReleaseMemObject(buffer)
}
}
|
mit
|
529ac1a61856bbd871f3843d3bafdf7c
| 29.215686 | 202 | 0.686567 | 3.138493 | false | false | false | false |
hughbe/swift
|
test/Generics/invalid.swift
|
3
|
3182
|
// RUN: %target-typecheck-verify-swift
func bet() where A : B {} // expected-error {{'where' clause cannot be attached to a non-generic declaration}}
typealias gimel where A : B // expected-error {{'where' clause cannot be attached to a non-generic declaration}}
// expected-error@-1 {{expected '=' in type alias declaration}}
class dalet where A : B {} // expected-error {{'where' clause cannot be attached to a non-generic declaration}}
protocol he where A : B { // expected-error 2 {{use of undeclared type 'A'}}
// expected-error@-1 {{use of undeclared type 'B'}}
associatedtype vav where A : B // expected-error{{use of undeclared type 'A'}}
// expected-error@-1 {{use of undeclared type 'B'}}
}
struct Lunch<T> {
struct Dinner<U> {
var leftovers: T
var transformation: (T) -> U
}
}
class Deli<Spices> {
class Pepperoni {}
struct Sausage {}
}
struct Pizzas<Spices> {
class NewYork {
}
class DeepDish {
}
}
class HotDog {
}
struct Pepper {}
struct ChiliFlakes {}
func eatDinnerConcrete(d: Pizzas<ChiliFlakes>.NewYork,
t: Deli<ChiliFlakes>.Pepperoni) {
}
func eatDinnerConcrete(d: Pizzas<Pepper>.DeepDish,
t: Deli<Pepper>.Pepperoni) {
}
func badDiagnostic1() {
_ = Lunch<Pizzas<Pepper>.NewYork>.Dinner<HotDog>(
leftovers: Pizzas<ChiliFlakes>.NewYork(), // expected-error {{cannot convert value of type 'Pizzas<ChiliFlakes>.NewYork' to expected argument type 'Pizzas<Pepper>.NewYork'}}
transformation: { _ in HotDog() })
}
func badDiagnostic2() {
let firstCourse = Pizzas<ChiliFlakes>.NewYork()
var dinner = Lunch<Pizzas<ChiliFlakes>.NewYork>.Dinner<HotDog>(
leftovers: firstCourse,
transformation: { _ in HotDog() })
let topping = Deli<Pepper>.Pepperoni()
eatDinnerConcrete(d: firstCourse, t: topping)
// expected-error@-1 {{cannot invoke 'eatDinnerConcrete' with an argument list of type '(d: Pizzas<ChiliFlakes>.NewYork, t: Deli<Pepper>.Pepperoni)'}}
// expected-note@-2 {{overloads for 'eatDinnerConcrete' exist with these partially matching parameter lists: (d: Pizzas<ChiliFlakes>.NewYork, t: Deli<ChiliFlakes>.Pepperoni), (d: Pizzas<Pepper>.DeepDish, t: Deli<Pepper>.Pepperoni)}}
}
// Real error is that we cannot infer the generic parameter from context
func takesAny(_ a: Any) {}
func badDiagnostic3() {
takesAny(Deli.self) // expected-error {{argument type 'Deli<_>.Type' does not conform to expected type 'Any'}}
}
// Crash with missing nested type inside concrete type
class OuterGeneric<T> {
class InnerGeneric<U> where U:OuterGeneric<T.NoSuchType> {
// expected-error@-1 {{'NoSuchType' is not a member type of 'T'}}
func method() {
_ = method
}
}
}
// Crash with missing types in requirements.
protocol P1 {
associatedtype A where A == ThisTypeDoesNotExist
// expected-error@-1{{use of undeclared type 'ThisTypeDoesNotExist'}}
associatedtype B where ThisTypeDoesNotExist == B
// expected-error@-1{{use of undeclared type 'ThisTypeDoesNotExist'}}
associatedtype C where ThisTypeDoesNotExist == ThisTypeDoesNotExist
// expected-error@-1 2{{use of undeclared type 'ThisTypeDoesNotExist'}}
}
|
apache-2.0
|
64c1886d1c01419b9f4c45f12de59dd0
| 29.893204 | 234 | 0.694532 | 3.933251 | false | false | false | false |
modocache/swift
|
test/decl/func/throwing_functions_without_try.swift
|
8
|
1422
|
// RUN: %target-parse-verify-swift -enable-throw-without-try
// Test the -enable-throw-without-try option. Throwing function calls should
// not require annotation with 'try'.
// rdar://21444103 - only at the top level
func foo() throws -> Int { return 0 }
// That applies to global "script" code.
var global: Int = 0
global = foo() // no error
global = try foo() // still no error
var global2: Int = foo() // no error
var global3: Int = try foo() // no error
// That includes autoclosures.
func doLazy(_ fn: @autoclosure () throws -> Int) {}
doLazy(foo())
// It doesn't include explicit closures.
var closure: () -> () = {
var x = foo() // expected-error {{call can throw, but it is not marked with 'try' and the error is not handled}}
doLazy(foo()) // expected-error {{call can throw but is not marked with 'try'}}
}
// Or any other sort of structure.
struct A {
static var lazyCache: Int = foo() // expected-error {{call can throw, but errors cannot be thrown out of a global variable initializer}}
}
func baz() throws -> Int {
var x: Int = 0
x = foo() // expected-error{{call can throw but is not marked with 'try'}}
x = try foo() // no error
return x
}
func baz2() -> Int {
var x: Int = 0
x = foo() // expected-error{{call can throw, but it is not marked with 'try' and the error is not handled}}
x = try foo() // expected-error{{errors thrown from here are not handled}}
return x
}
|
apache-2.0
|
5ace503e46504fd162cce4e81b30599a
| 29.255319 | 138 | 0.661041 | 3.468293 | false | false | false | false |
sadawi/ModelKit
|
ModelKit/RemoteModelStore/RemoteModelStore.swift
|
1
|
14723
|
//
// RemoteServer.swift
// APIKit
//
// Created by Sam Williams on 11/7/15.
// Copyright © 2015 Sam Williams. All rights reserved.
//
import Alamofire
import PromiseKit
public typealias Parameters = [String: AnyObject]
public enum RemoteModelStoreError: Error {
case unknownError(message: String)
case deserializationFailure
case serializationFailure
case invalidResponse
case noModelPath(model: Model)
case noModelCollectionPath(modelClass: Model.Type)
var description: String {
switch(self) {
case .deserializationFailure:
return "Could not deserialize model"
case .serializationFailure:
return "Could not serialize"
case .invalidResponse:
return "Invalid response value"
case .noModelPath(let model):
return "No path for model of type \(type(of: model))"
case .unknownError(let message):
return message
case .noModelCollectionPath(let modelClass):
return "No path for model collection of type \(modelClass)"
}
}
}
open class RemoteModelStore: ModelStore, ListableModelStore {
open var baseURL:URL
open var delegate:ModelStoreDelegate?
open var router = RESTRouter()
public init(baseURL:URL) {
self.baseURL = baseURL
}
/**
The transformer context to use when (un)serializing models.
*/
public var valueTransformerContext: ModelValueTransformerContext = .defaultModelContext
/**
Creates a closure that deserializes a model and returns a Promise.
Useful in promise chaining as an argument to .then
- parameter modelClass: The Model subclass to be instantiated
- returns: A Promise yielding a Model instance
*/
open func instantiateModel<T:Model>(_ modelClass:T.Type) -> ((Response<AttributeDictionary>) -> Promise<T>){
return { (response:Response<AttributeDictionary>) in
if let data = response.data, let model = self.deserializeModel(modelClass, parameters: data) {
return Promise(value: model)
} else {
return Promise(error: RemoteModelStoreError.deserializationFailure)
}
}
}
open func instantiateModels<T:Model>(_ modelClass:T.Type) -> ((Response<[AttributeDictionary]>) -> Promise<[T]>) {
return { (response:Response<[AttributeDictionary]>) in
// TODO: any of the individual models could fail to deserialize, and we're just silently ignoring them.
// Not sure what the right behavior should be.
if let values = response.data {
let models = values.map { value -> T? in
let model:T? = self.deserializeModel(modelClass, parameters: value)
return model
}.flatMap{$0}
return Promise(value: models)
} else {
return Promise(value: [])
}
}
}
// MARK: - Helper methods that subclasses might want to override
private func url(path:String) -> URL {
return self.baseURL.appendingPathComponent(path)
}
open func defaultHeaders() -> [String:String] {
return [:]
}
open func formatPayload(_ payload:AttributeDictionary) -> AttributeDictionary {
return payload
}
open func serializeModel(_ model:Model, fields:[FieldType]?=nil) -> AttributeDictionary {
return model.dictionaryValue(fields: fields, in: self.valueTransformerContext)
}
open func deserializeModel<T:Model>(_ modelClass:T.Type, parameters:AttributeDictionary) -> T? {
// TODO: would rather use value transformer here instead, but T is Model instead of modelClass and it doesn't get deserialized properly
// return ModelValueTransformer<T>().importValue(parameters)
let model = modelClass.from(dictionaryValue: parameters, in: self.valueTransformerContext)
model?.loadState = .loaded
return model
}
open func handleError(_ error:Error, model:Model?=nil) {
// Override
}
/**
Retrieves the data payload from the Alamofire response and attempts to cast it to the correct type.
Override this to allow for an intermediate "data" key, for example.
Note: T is only specified by type inference from the return value.
Note: errors aren't processed from the response. Subclasses should handle that for a specific API response format.
- parameter apiResponse: The JSON response object from an Alamofire request
- returns: A Response object with its payload cast to the specified type
*/
open func constructResponse<T>(_ apiResponse:Alamofire.DataResponse<Any>) -> Response<T>? {
let response = Response<T>()
response.data = apiResponse.result.value as? T
return response
}
// MARK: - Generic requests
open func encodingForMethod(_ method: Alamofire.HTTPMethod) -> ParameterEncoding {
return URLEncoding()
}
/**
A placeholder method in which you can attempt to restore your session (refreshing your oauth token, for example) before each request.
*/
open func restoreSession() -> Promise<Void> {
return Promise<Void>(value: ())
}
/**
The core request method, basically a Promise wrapper around an Alamofire.request call
Parameterized by the T, the expected data payload type (typically either a dictionary or an array of dictionaries)
TODO: At the moment T is only specified by type inference from the return value, which is awkward since it's a promise.
Consider specifying as a param.
- returns: A Promise parameterized by the data payload type of the response
*/
open func request<T>(
_ method: Alamofire.HTTPMethod,
path: String,
parameters: AttributeDictionary?=nil,
headers: [String:String]=[:],
encoding: ParameterEncoding?=nil,
model: Model?=nil,
timeoutInterval: TimeInterval?=nil,
cachePolicy: NSURLRequest.CachePolicy?=nil,
requireSession: Bool = true
) -> Promise<Response<T>> {
let url = self.url(path: path)
let encoding = encoding ?? self.encodingForMethod(method)
let action = { () -> Promise<Response<T>> in
return Promise { fulfill, reject in
// Compute headers *after* the session has been restored.
let headers = self.defaultHeaders() + headers
// Manually recreating what Alamofire.request does so we have access to the URLRequest object:
var mutableRequest = URLRequest(url: url)
for (field, value) in headers {
mutableRequest.setValue(value, forHTTPHeaderField: field)
}
if let timeoutInterval = timeoutInterval {
mutableRequest.timeoutInterval = timeoutInterval
}
if let cachePolicy = cachePolicy {
mutableRequest.cachePolicy = cachePolicy
}
mutableRequest.httpMethod = method.rawValue
guard let encodedRequest = try? encoding.encode(mutableRequest, with: parameters) else { reject(RemoteModelStoreError.serializationFailure); return }
Alamofire.request(encodedRequest).responseJSON { response in
switch response.result {
case .success:
if let value:Response<T> = self.constructResponse(response) {
if let error=value.error {
// the request might have succeeded, but we found an error when constructing the Response object
self.handleError(error, model:model)
reject(error)
} else {
fulfill(value)
}
} else {
let error = RemoteModelStoreError.invalidResponse
self.handleError(error)
reject(error)
}
case .failure(let error):
self.handleError(error as Error, model:model)
reject(error)
}
}
}
}
if requireSession {
return self.restoreSession().then(on: .global(), execute: action)
} else {
return action()
}
}
// MARK: - CRUD operations (ModelStore protocol methods)
open func create<T:Model>(_ model: T, fields: [FieldType]?) -> Promise<T> {
return self.create(model, fields: fields, parameters: nil)
}
open func create<T:Model>(_ model: T, fields: [FieldType]?, parameters: Parameters?) -> Promise<T> {
model.resetValidationState()
model.beforeSave()
var requestParameters = self.formatPayload(self.serializeModel(model, fields: fields))
if let parameters = parameters {
for (k,v) in parameters {
requestParameters[k] = v
}
}
// See MemoryModelStore for an explanation [1]
let modelModel = model as Model
if let collectionPath = self.router.collectionPath(for: model) {
return self.request(.post, path: collectionPath, parameters: requestParameters, model:model).then(on: .global(), execute: self.instantiateModel(type(of: modelModel))).then(on: .global()) { model in
model.afterCreate()
return Promise(value: model as! T)
}
}else {
return Promise(error: RemoteModelStoreError.noModelCollectionPath(modelClass: type(of: modelModel)))
}
}
open func update<T:Model>(_ model: T, fields: [FieldType]?) -> Promise<T> {
return self.update(model, fields: fields, parameters: nil)
}
open func update<T:Model>(_ model: T, fields: [FieldType]?, parameters: Parameters?) -> Promise<T> {
model.resetValidationState()
model.beforeSave()
let modelModel = model as Model
if let path = self.router.instancePath(for: model) {
var requestParameters = self.formatPayload(self.serializeModel(model, fields: fields))
if let parameters = parameters {
for (k,v) in parameters {
requestParameters[k] = v
}
}
return self.request(.patch, path: path, parameters: requestParameters, model:model).then(on: .global(), execute: self.instantiateModel(type(of: modelModel))).then(on: .global()) { model -> Promise<T> in
// Dancing around to get the type inference to work
return Promise<T>(value: model as! T)
}
} else {
return Promise(error: RemoteModelStoreError.noModelPath(model: model))
}
}
open func delete<T:Model>(_ model: T) -> Promise<T> {
if let path = self.router.instancePath(for: model) {
return self.request(.delete, path: path).then(on: .global()) { (response:Response<T>) -> Promise<T> in
model.afterDelete()
return Promise(value: model)
}
} else {
return Promise(error: RemoteModelStoreError.noModelPath(model: model))
}
}
open func deleteAll<T : Model>(_ field: ModelArrayField<T>) -> Promise<Void> {
if let path = self.router.path(to: field) {
return self.request(.delete, path: path).then(on: .global()) { (response:Response<T>) -> Promise<Void> in
for model in field.value ?? [] {
model.afterDelete()
}
return Promise(value: ())
}
} else {
return Promise(error: RemoteModelStoreError.noModelCollectionPath(modelClass: T.self))
}
}
open func read<T : Model>(_ model: T) -> Promise<T> {
if let path = self.router.instancePath(for: model) {
return self.read(T.self, path: path)
} else {
return Promise(error: RemoteModelStoreError.noModelPath(model: model))
}
}
open func read<T: Model>(_ modelClass:T.Type, identifier:String, parameters: Parameters?) -> Promise<T> {
let model = modelClass.init() as T
model.identifier = identifier
if let path = self.router.instancePath(for: model) {
return self.read(modelClass, path: path)
} else {
return Promise(error: RemoteModelStoreError.noModelPath(model: model))
}
}
/**
Reads a single model from the specified path.
*/
open func read<T: Model>(_ modelClass: T.Type, path: String, parameters: Parameters?=nil) -> Promise<T> {
return self.request(.get, path: path, parameters: parameters).then(on: .global(), execute: self.instantiateModel(modelClass))
}
public func list<T: Model>(_ modelClass:T.Type) -> Promise<[T]> {
return self.list(modelClass, parameters: nil)
}
public func list<T : Model>(_ field: ModelArrayField<T>) -> Promise<[T]> {
return self.list(field, parameters: nil)
}
public func list<T : Model>(_ field: ModelArrayField<T>, parameters:Parameters?=nil) -> Promise<[T]> {
guard let path = self.router.path(to: field) else { return Promise(error: RemoteModelStoreError.noModelCollectionPath(modelClass: T.self)) }
return self.list(T.self, path: path, parameters: parameters)
}
/**
Retrieves a list of models, with customization of the request path and parameters.
- parameter modelClass: The model class to instantiate
- parameter path: An optional path. Defaults to modelClass.path
- parameter parameters: Request parameters to pass along in the request.
*/
open func list<T: Model>(_ modelClass:T.Type, path:String?=nil, parameters:Parameters?) -> Promise<[T]> {
if let collectionPath = path ?? self.router.path(to: modelClass) {
return self.request(.get, path: collectionPath, parameters: parameters).then(on: .global(), execute: self.instantiateModels(modelClass))
} else {
return Promise(error: RemoteModelStoreError.noModelCollectionPath(modelClass: modelClass))
}
}
}
|
mit
|
2e6c040ce7f0aad54dd9b07c1e3b232b
| 40.122905 | 214 | 0.599035 | 4.85394 | false | false | false | false |
furuya02/CybersourceSampleSwift
|
CybersourceSampleSwift/ViewController.swift
|
1
|
3247
|
//
// ViewController.swift
// CybersourceSampleSwift
//
// Created by hirauchi.shinichi on 2016/02/19.
// Copyright © 2016年 SAPPOROWORKS. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
var API_KEY = "{put your api key here}"
var SHARED_SECRET = "{put your shared secret here}"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func tapButton(sender: AnyObject) {
let baseUri = "cybersource/"
let resourcePath = "payments/v1/authorizations"
let url = "https://sandbox.api.visa.com/\(baseUri)\(resourcePath)?apikey=\(API_KEY)"
let body = "{\"amount\": \"0\", \"currency\": \"USD\", \"payment\": { \"cardNumber\": \"4111111111111111\", \"cardExpirationMonth\": \"10\", \"cardExpirationYear\": \"2016\" }}"
let xPayToken = getXPayToken(resourcePath, queryString: "apikey=\(API_KEY)", requestBody: body) as String
let request = NSMutableURLRequest(URL: NSURL(string: url)!)
request.HTTPMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue(xPayToken, forHTTPHeaderField: "x-pay-token")
let postBody = NSMutableData()
postBody.appendData(body.dataUsingEncoding(NSUTF8StringEncoding)!)
request.HTTPBody = postBody
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) {
(
let data, let response, let error) in
guard let _:NSData = data, let _:NSURLResponse = response where error == nil else {
print("Error")
return
}
let responseString:NSString = NSString(data: data!, encoding: NSUTF8StringEncoding)!
print(responseString)
dispatch_async(
dispatch_get_main_queue(),
{
self.textView.text = responseString as String
}
);
}
task.resume()
}
func getXPayToken(apiNameURI:NSString, queryString:NSString, requestBody:NSString) -> NSString {
let timestamp = getTimestamp()
let sourceString = "\(SHARED_SECRET)\(timestamp)\(apiNameURI)\(queryString)\(requestBody)"
let hash = getDigest(sourceString)
return "x:\(timestamp):\(hash)"
}
func getTimestamp() -> NSString {
let date = NSDate().timeIntervalSince1970
return NSString(format: "%.0f", date)
}
func getDigest(date:NSString) -> NSString {
if let d = date.dataUsingEncoding(NSASCIIStringEncoding) {
var bytes = [UInt8](count: 64, repeatedValue: 0)
CC_SHA256(d.bytes, CC_LONG(d.length), &bytes)
let digest = NSMutableString(capacity: 64)
for var i=0; i<32; i++ {
digest.appendFormat("%02x", bytes[i])
}
return digest
}
return ""
}
}
|
mit
|
492a083df402cf6d61921c1a43896029
| 33.510638 | 185 | 0.606967 | 4.634286 | false | false | false | false |
hulinSun/MyRx
|
MyRx/MyRx/Classes/Core/Category/Raduis.swift
|
1
|
5209
|
////
//// Raduis.swift
//// MyRx
////
//// Created by Hony on 2017/1/9.
//// Copyright © 2017年 Hony. All rights reserved.
////
//
//import Foundation
//import UIKit
//
//private func roundbyunit(_ num: Double, _ unit: inout Double) -> Double {
// let remain = modf(num, &unit)
// if (remain > unit / 2.0) {
// return ceilbyunit(num, &unit)
// } else {
// return floorbyunit(num, &unit)
// }
//}
//private func ceilbyunit(_ num: Double, _ unit: inout Double) -> Double {
// return num - modf(num, &unit) + unit
//}
//
//private func floorbyunit(_ num: Double, _ unit: inout Double) -> Double {
// return num - modf(num, &unit)
//}
//
//private func pixel(num: Double) -> Double {
// var unit: Double
// switch Int(UIScreen.main.scale) {
// case 1: unit = 1.0 / 1.0
// case 2: unit = 1.0 / 2.0
// case 3: unit = 1.0 / 3.0
// default: unit = 0.0
// }
// return roundbyunit(num, &unit)
//}
//
//extension UIView {
//
// func kt_addCorner(radius: CGFloat) {
// self.kt_addCorner(radius: radius, borderWidth: 1, backgroundColor: UIColor.clear, borderColor: UIColor.black)
// }
//
// func kt_addCorner( radius: CGFloat,
// borderWidth: CGFloat,
// backgroundColor: UIColor,
// borderColor: UIColor) {
// let imageView = UIImageView(image: kt_drawRectWithRoundedCorner(radius: radius,
// borderWidth: borderWidth,
// backgroundColor: backgroundColor,
// borderColor: borderColor))
// self.insertSubview(imageView, at: 0)
// }
//
// func kt_drawRectWithRoundedCorner( radius: CGFloat,
// borderWidth: CGFloat,
// backgroundColor: UIColor,
// borderColor: UIColor) -> UIImage {
//
// let sizeToFit = CGSize(width: pixel(num: Double(self.bounds.size.width)), height: Double(self.bounds.size.height))
// let halfBorderWidth = CGFloat(borderWidth / 2.0)
//
// UIGraphicsBeginImageContextWithOptions(sizeToFit, false, UIScreen.main.scale)
// let context = UIGraphicsGetCurrentContext()
//
// context?.setLineWidth(borderWidth)
// context?.setStrokeColor(borderColor.cgColor)
// context?.setFillColor(backgroundColor.cgColor)
//
// let width = sizeToFit.width, height = sizeToFit.height
// // 开始坐标右边开始
// context?.move(to: CGPoint(x: width - halfBorderWidth, y: radius + halfBorderWidth))
// context?.addArc(center: <#T##CGPoint#>, radius: <#T##CGFloat#>, startAngle: <#T##CGFloat#>, endAngle: <#T##CGFloat#>, clockwise: <#T##Bool#>)
//
// CGContextAddArcToPoint(context, width - halfBorderWidth, height - halfBorderWidth, width - radius - halfBorderWidth, height - halfBorderWidth, radius) // 右下角角度
// CGContextAddArcToPoint(context, halfBorderWidth, height - halfBorderWidth, halfBorderWidth, height - radius - halfBorderWidth, radius) // 左下角角度
// CGContextAddArcToPoint(context, halfBorderWidth, halfBorderWidth, width - halfBorderWidth, halfBorderWidth, radius) // 左上角
// CGContextAddArcToPoint(context, width - halfBorderWidth, halfBorderWidth, width - halfBorderWidth, radius + halfBorderWidth, radius) // 右上角
//
// CGContextDrawPath(UIGraphicsGetCurrentContext(), .FillStroke)
// let output = UIGraphicsGetImageFromCurrentImageContext()
// UIGraphicsEndImageContext()
// return output
// }
//}
//
//extension UIImageView {
// /**
// / !!!只有当 imageView 不为nil 时,调用此方法才有效果
//
// :param: radius 圆角半径
// */
// override func kt_addCorner(radius radius: CGFloat) {
// // 被注释的是图片添加圆角的 OC 写法
// // self.image = self.image?.imageAddCornerWithRadius(radius, andSize: self.bounds.size)
// self.image = self.image?.kt_drawRectWithRoundedCorner(radius: radius, self.bounds.size)
// }
//}
//
//extension UIImage {
// func kt_drawRectWithRoundedCorner(radius radius: CGFloat, _ sizetoFit: CGSize) -> UIImage {
// let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: sizetoFit)
//
// UIGraphicsBeginImageContextWithOptions(rect.size, false, UIScreen.mainScreen().scale)
// CGContextAddPath(UIGraphicsGetCurrentContext(),
// UIBezierPath(roundedRect: rect, byRoundingCorners: UIRectCorner.AllCorners,
// cornerRadii: CGSize(width: radius, height: radius)).CGPath)
// CGContextClip(UIGraphicsGetCurrentContext())
//
// self.drawInRect(rect)
// CGContextDrawPath(UIGraphicsGetCurrentContext(), .FillStroke)
// let output = UIGraphicsGetImageFromCurrentImageContext()
// UIGraphicsEndImageContext()
//
// return output
// }
//}
|
mit
|
af015c6c7260810f4f5ee57d2218d8d2
| 42.135593 | 170 | 0.588016 | 4.144951 | false | false | false | false |
lorentey/swift
|
test/Frontend/skip-non-inlinable-function-bodies.swift
|
4
|
8846
|
// RUN: %empty-directory(%t)
// 1. Make sure you can't -emit-ir or -c when you're skipping non-inlinable function bodies
// RUN: not %target-swift-frontend -emit-ir %s -experimental-skip-non-inlinable-function-bodies %s 2>&1 | %FileCheck %s --check-prefix ERROR
// RUN: not %target-swift-frontend -c %s -experimental-skip-non-inlinable-function-bodies %s 2>&1 | %FileCheck %s --check-prefix ERROR
// ERROR: -experimental-skip-non-inlinable-function-bodies does not support emitting IR
// 2. Emit the SIL for a module and check it against the expected strings in function bodies.
// If we're doing the right skipping, then the strings that are CHECK-NOT'd won't have been typechecked or SILGen'd.
// RUN: %target-swift-frontend -emit-sil -O -experimental-skip-non-inlinable-function-bodies -emit-sorted-sil %s 2>&1 | %FileCheck %s --check-prefixes CHECK,CHECK-SIL-ONLY
// 3. Emit the module interface while skipping non-inlinable function bodies. Check it against the same set of strings.
// RUN: %target-swift-frontend -typecheck %s -enable-library-evolution -emit-module-interface-path %t/Module.skipping.swiftinterface -experimental-skip-non-inlinable-function-bodies
// RUN: %FileCheck %s --check-prefixes CHECK,CHECK-INTERFACE-ONLY < %t/Module.skipping.swiftinterface
// 4. Emit the module interface normally. Also check it against the same set of strings.
// RUN: %target-swift-frontend -typecheck %s -enable-library-evolution -emit-module-interface-path %t/Module.swiftinterface
// RUN: %FileCheck %s --check-prefixes CHECK,CHECK-INTERFACE-ONLY < %t/Module.swiftinterface
// 5. The module interfaces should be exactly the same.
// RUN: diff -u %t/Module.skipping.swiftinterface %t/Module.swiftinterface
@usableFromInline
@inline(never)
func _blackHole(_ s: String) {}
// NOTE: The order of the checks below is important. The checks try to be
// logically grouped, but sometimes -emit-sorted-sil needs to break the logical
// order.
@inlinable public func inlinableFunc() {
_blackHole("@inlinable func body") // CHECK: "@inlinable func body"
}
@_fixed_layout
public class InlinableDeinit {
@inlinable deinit {
_blackHole("@inlinable deinit body") // CHECK: "@inlinable deinit body"
}
}
@_fixed_layout
public class InlineAlwaysDeinit {
@inline(__always) deinit {
_blackHole("@inline(__always) deinit body") // CHECK-NOT: "@inline(__always) deinit body"
}
}
public class NormalDeinit {
deinit {
_blackHole("regular deinit body") // CHECK-NOT: "regular deinit body"
}
}
@_transparent public func transparentFunc() {
_blackHole("@_transparent func body") // CHECK: "@_transparent func body"
}
@inline(__always) public func inlineAlwaysFunc() {
_blackHole("@inline(__always) func body") // CHECK-NOT: "@inline(__always) func body"
}
func internalFunc() {
_blackHole("internal func body") // CHECK-NOT: "internal func body"
}
public func publicFunc() {
_blackHole("public func body") // CHECK-NOT: "public func body"
}
private func privateFunc() {
_blackHole("private func body") // CHECK-NOT: "private func body"
}
@inline(__always) public func inlineAlwaysLocalTypeFunc() {
typealias InlineAlwaysLocalType = Int
_blackHole("@inline(__always) func body with local type") // CHECK-NOT: "@inline(__always) func body with local type"
func takesInlineAlwaysLocalType(_ x: InlineAlwaysLocalType) {
_blackHole("nested func body inside @inline(__always) func body taking local type") // CHECK-NOT: "nested func body inside @inline(__always) func body taking local type"
}
takesInlineAlwaysLocalType(0)
}
public func publicLocalTypeFunc() {
typealias LocalType = Int
_blackHole("public func body with local type") // CHECK-NOT: "public func body with local type"
func takesLocalType(_ x: LocalType) {
_blackHole("nested func body inside public func body taking local type") // CHECK-NOT: "nested func body inside public func body taking local type"
}
takesLocalType(0)
}
@inlinable
public func inlinableLocalTypeFunc() {
typealias InlinableLocalType = Int
_blackHole("@inlinable func body with local type") // CHECK: "@inlinable func body with local type"
func takesInlinableLocalType(_ x: InlinableLocalType) {
_blackHole("nested func body inside @inlinable func body taking local type") // CHECK: "nested func body inside @inlinable func body taking local type"
}
takesInlinableLocalType(0)
}
@_transparent public func _transparentLocalTypeFunc() {
typealias TransparentLocalType = Int
_blackHole("@_transparent func body with local type") // CHECK: "@_transparent func body with local type"
func takesTransparentLocalType(_ x: TransparentLocalType) {
_blackHole("nested func body inside @_transparent func body taking local type") // CHECK: "nested func body inside @_transparent func body taking local type"
}
takesTransparentLocalType(0)
}
@inlinable
public func inlinableNestedLocalTypeFunc() {
func nestedFunc() {
_blackHole("nested func body inside @inlinable func body") // CHECK: "nested func body inside @inlinable func body"
typealias InlinableNestedLocalType = Int
func takesLocalType(_ x: InlinableNestedLocalType) {
_blackHole("nested func body inside @inlinable func body taking local type") // CHECK: "nested func body inside @inlinable func body taking local type"
}
takesLocalType(0)
}
nestedFunc()
}
public struct Struct {
@inlinable public var inlinableVar: Int {
_blackHole("@inlinable getter body") // CHECK: "@inlinable getter body"
return 0
}
@inlinable public func inlinableFunc() {
_blackHole("@inlinable method body") // CHECK: "@inlinable method body"
}
@inline(__always)
public func inlineAlwaysFunc() {
_blackHole("@inline(__always) method body") // CHECK-NOT: "@inline(__always) method body"
}
@_transparent public var transparentVar: Int {
_blackHole("@_transparent getter body") // CHECK: "@_transparent getter body"
return 0
}
public var inlinableSetter: Int {
get { 0 }
@inlinable set {
_blackHole("@inlinable setter body") // CHECK: "@inlinable setter body"
}
}
@_transparent
public func transparentFunc() {
_blackHole("@_transparent method body") // CHECK: "@_transparent method body"
}
func internalFunc() {
_blackHole("internal method body") // CHECK-NOT: "internal method body"
}
public func publicFunc() {
_blackHole("public method body") // CHECK-NOT: "public method body"
}
private func privateFunc() {
_blackHole("private method body") // CHECK-NOT: "private method body"
}
@_transparent public init(b: Int) {
_blackHole("@_transparent init body") // CHECK: "@_transparent init body"
}
@inlinable public init() {
_blackHole("@inlinable init body") // CHECK: "@inlinable init body"
}
@inline(__always) public init(a: Int) {
_blackHole("@inline(__always) init body") // CHECK-NOT: "@inline(__always) init body"
}
init(c: Int) {
_blackHole("internal init body") // CHECK-NOT: "internal init body"
}
public init(d: Int) {
_blackHole("public init body") // CHECK-NOT: "public init body"
}
private init(e: Int) {
_blackHole("private init body") // CHECK-NOT: "private init body"
}
@inlinable public subscript() -> Int {
_blackHole("@inlinable subscript getter") // CHECK: "@inlinable subscript getter"
return 0
}
@inline(__always) public subscript(a: Int, b: Int) -> Int {
_blackHole("@inline(__always) subscript getter") // CHECK-NOT: "@inline(__always) subscript getter"
return 0
}
public subscript(a: Int, b: Int, c: Int) -> Int {
@_transparent get {
_blackHole("@_transparent subscript getter") // CHECK: "@_transparent subscript getter"
return 0
}
}
subscript(a: Int, b: Int, c: Int, d: Int) -> Int {
_blackHole("internal subscript getter") // CHECK-NOT: "internal subscript getter"
return 0
}
public subscript(a: Int, b: Int, c: Int, d: Int, e: Int) -> Int {
_blackHole("public subscript getter") // CHECK-NOT: "public subscript getter"
return 0
}
private subscript(e: Int) -> Int {
_blackHole("private subscript getter") // CHECK-NOT: "private subscript getter"
return 0
}
@inline(__always) public var inlineAlwaysVar: Int {
_blackHole("@inline(__always) getter body") // CHECK-NOT: "@inline(__always) getter body"
return 0
}
public var publicVar: Int {
_blackHole("public getter body") // CHECK-NOT: "public getter body"
return 0
}
public var inlineAlwaysSetter: Int {
get { 0 }
@inline(__always) set {
_blackHole("@inline(__always) setter body") // CHECK-NOT: "@inline(__always) setter body"
}
}
public var regularSetter: Int {
get { 0 }
set {
_blackHole("@inline(__always) setter body") // CHECK-NOT: "regular setter body"
}
}
}
|
apache-2.0
|
ff1c98560b65cc15844013e683e00794
| 33.964427 | 181 | 0.694551 | 3.910698 | false | false | false | false |
joshaber/SwiftBox
|
SwiftBox/Node.swift
|
1
|
4155
|
//
// Node.swift
// SwiftBox
//
// Created by Josh Abernathy on 2/6/15.
// Copyright (c) 2015 Josh Abernathy. All rights reserved.
//
import Foundation
public struct Edges {
public let left: CGFloat
public let right: CGFloat
public let bottom: CGFloat
public let top: CGFloat
fileprivate var asTuple: (Float, Float, Float, Float) {
return (Float(left), Float(top), Float(right), Float(bottom))
}
public init(left: CGFloat = 0, right: CGFloat = 0, bottom: CGFloat = 0, top: CGFloat = 0) {
self.left = left
self.right = right
self.bottom = bottom
self.top = top
}
public init(uniform: CGFloat) {
self.left = uniform
self.right = uniform
self.bottom = uniform
self.top = uniform
}
}
public enum Direction: UInt32 {
case column = 0
case row = 1
}
public enum Justification: UInt32 {
case flexStart = 0
case center = 1
case flexEnd = 2
case spaceBetween = 3
case spaceAround = 4
}
public enum ChildAlignment: UInt32 {
case flexStart = 1
case center = 2
case flexEnd = 3
case stretch = 4
}
public enum SelfAlignment: UInt32 {
case auto = 0
case flexStart = 1
case center = 2
case flexEnd = 3
case stretch = 4
}
/// A node in a layout hierarchy.
public struct Node {
/// Indicates that the value is undefined, for the flexbox algorithm to
/// fill in.
public static let Undefined: CGFloat = nan("SwiftBox.Node.Undefined")
public let size: CGSize
public let children: [Node]
public let direction: Direction
public let margin: Edges
public let padding: Edges
public let wrap: Bool
public let justification: Justification
public let selfAlignment: SelfAlignment
public let childAlignment: ChildAlignment
public let flex: CGFloat
public let measure: ((CGFloat) -> CGSize)?
public init(size: CGSize = CGSize(width: Undefined, height: Undefined), children: [Node] = [], direction: Direction = .column, margin: Edges = Edges(), padding: Edges = Edges(), wrap: Bool = false, justification: Justification = .flexStart, selfAlignment: SelfAlignment = .auto, childAlignment: ChildAlignment = .stretch, flex: CGFloat = 0, measure: ((CGFloat) -> CGSize)? = nil) {
self.size = size
self.children = children
self.direction = direction
self.margin = margin
self.padding = padding
self.wrap = wrap
self.justification = justification
self.selfAlignment = selfAlignment
self.childAlignment = childAlignment
self.flex = flex
self.measure = measure
}
fileprivate func createUnderlyingNode() -> NodeImpl {
let node = NodeImpl()
node.node.pointee.style.dimensions = (Float(size.width), Float(size.height))
node.node.pointee.style.margin = margin.asTuple
node.node.pointee.style.padding = padding.asTuple
node.node.pointee.style.flex = Float(flex)
node.node.pointee.style.flex_direction = css_flex_direction_t(direction.rawValue)
node.node.pointee.style.flex_wrap = css_wrap_type_t(wrap ? 1 : 0)
node.node.pointee.style.justify_content = css_justify_t(justification.rawValue)
node.node.pointee.style.align_self = css_align_t(selfAlignment.rawValue)
node.node.pointee.style.align_items = css_align_t(childAlignment.rawValue)
if let measure = measure {
node.measure = measure
}
node.children = children.map { $0.createUnderlyingNode() }
return node
}
/// Lay out the receiver and all its children with an optional max width.
public func layout(maxWidth: CGFloat? = nil) -> Layout {
let node = createUnderlyingNode()
if let maxWidth = maxWidth {
node.layout(withMaxWidth: maxWidth)
} else {
node.layout()
}
let children = createLayoutsFromChildren(node)
return Layout(frame: node.frame, children: children)
}
}
private func createLayoutsFromChildren(_ node: NodeImpl) -> [Layout] {
return node.children.map {
let child = $0 as! NodeImpl
let frame = child.frame
return Layout(frame: frame, children: createLayoutsFromChildren(child))
}
}
public extension CGPoint {
var isUndefined: Bool {
return x.isNaN || y.isNaN
}
}
public extension CGSize {
var isUndefined: Bool {
return width.isNaN || height.isNaN
}
}
public extension CGRect {
var isUndefined: Bool {
return origin.isUndefined || size.isUndefined
}
}
|
bsd-3-clause
|
916dd97df2f9c6a0a2770719dd04822c
| 26.335526 | 382 | 0.719615 | 3.345411 | false | false | false | false |
stubbornnessness/EasySwift
|
Carthage/Checkouts/RainbowNavigation/RainbowNavigation/UINavigationBar+Rainbow.swift
|
2
|
2345
|
//
// UINavigationBar+Rainbow.swift
// Pods
//
// Created by Danis on 15/11/25.
//
//
import Foundation
private var kBackgroundViewKey = "kBackgroundViewKey"
private var kStatusBarMaskKey = "kStatusBarMaskKey"
extension UINavigationBar {
public func df_setStatusBarMaskColor(_ color: UIColor) {
if statusBarMask == nil {
statusBarMask = UIView(frame: CGRect(x: 0, y: -20, width: UIScreen.main.bounds.width, height: 20))
statusBarMask?.autoresizingMask = [.flexibleWidth,.flexibleHeight]
if let tempBackgroundView = backgroundView {
insertSubview(statusBarMask!, aboveSubview: tempBackgroundView)
}else {
insertSubview(statusBarMask!, at: 0)
}
}
statusBarMask?.backgroundColor = color
}
public func df_setBackgroundColor(_ color: UIColor) {
if backgroundView == nil {
setBackgroundImage(UIImage(), for: UIBarMetrics.default)
shadowImage = UIImage()
backgroundView = UIView(frame: CGRect(x: 0, y: -20, width: UIScreen.main.bounds.width, height: 64))
backgroundView?.isUserInteractionEnabled = false
backgroundView?.autoresizingMask = [.flexibleHeight,.flexibleWidth]
insertSubview(backgroundView!, at: 0)
}
backgroundView?.backgroundColor = color
for subview in subviews {
if subview != backgroundView {
self.bringSubview(toFront: subview)
}
}
}
public func df_reset() {
setBackgroundImage(nil, for: .default)
shadowImage = nil
backgroundView?.removeFromSuperview()
backgroundView = nil
}
// MARK: Properties
fileprivate var backgroundView:UIView? {
get {
return objc_getAssociatedObject(self, &kBackgroundViewKey) as? UIView
}
set {
objc_setAssociatedObject(self, &kBackgroundViewKey, newValue, .OBJC_ASSOCIATION_RETAIN)
}
}
fileprivate var statusBarMask:UIView? {
get {
return objc_getAssociatedObject(self, &kStatusBarMaskKey) as? UIView
}
set {
objc_setAssociatedObject(self, &kStatusBarMaskKey, newValue, .OBJC_ASSOCIATION_RETAIN)
}
}
}
|
apache-2.0
|
01bdaf93404856b85ea12bcaa9e454c6
| 31.569444 | 111 | 0.612367 | 5.010684 | false | false | false | false |
zapdroid/RXWeather
|
Pods/Alamofire/Source/TaskDelegate.swift
|
1
|
15430
|
//
// TaskDelegate.swift
//
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// The task delegate is responsible for handling all delegate callbacks for the underlying task as well as
/// executing all operations attached to the serial operation queue upon task completion.
open class TaskDelegate: NSObject {
// MARK: Properties
/// The serial operation queue used to execute all operations after the task completes.
open let queue: OperationQueue
/// The data returned by the server.
public var data: Data? { return nil }
/// The error generated throughout the lifecyle of the task.
public var error: Error?
var task: URLSessionTask? {
didSet { reset() }
}
var initialResponseTime: CFAbsoluteTime?
var credential: URLCredential?
var metrics: AnyObject? // URLSessionTaskMetrics
// MARK: Lifecycle
init(task: URLSessionTask?) {
self.task = task
queue = {
let operationQueue = OperationQueue()
operationQueue.maxConcurrentOperationCount = 1
operationQueue.isSuspended = true
operationQueue.qualityOfService = .utility
return operationQueue
}()
}
func reset() {
error = nil
initialResponseTime = nil
}
// MARK: URLSessionTaskDelegate
var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)?
var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))?
var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> InputStream?)?
var taskDidCompleteWithError: ((URLSession, URLSessionTask, Error?) -> Void)?
@objc(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:)
func urlSession(
_ session: URLSession,
task: URLSessionTask,
willPerformHTTPRedirection response: HTTPURLResponse,
newRequest request: URLRequest,
completionHandler: @escaping (URLRequest?) -> Void) {
var redirectRequest: URLRequest? = request
if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection {
redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request)
}
completionHandler(redirectRequest)
}
@objc(URLSession:task:didReceiveChallenge:completionHandler:)
func urlSession(
_ session: URLSession,
task: URLSessionTask,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling
var credential: URLCredential?
if let taskDidReceiveChallenge = taskDidReceiveChallenge {
(disposition, credential) = taskDidReceiveChallenge(session, task, challenge)
} else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
let host = challenge.protectionSpace.host
if
let serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicy(forHost: host),
let serverTrust = challenge.protectionSpace.serverTrust {
if serverTrustPolicy.evaluate(serverTrust, forHost: host) {
disposition = .useCredential
credential = URLCredential(trust: serverTrust)
} else {
disposition = .cancelAuthenticationChallenge
}
}
} else {
if challenge.previousFailureCount > 0 {
disposition = .rejectProtectionSpace
} else {
credential = self.credential ?? session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace)
if credential != nil {
disposition = .useCredential
}
}
}
completionHandler(disposition, credential)
}
@objc(URLSession:task:needNewBodyStream:)
func urlSession(
_ session: URLSession,
task: URLSessionTask,
needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) {
var bodyStream: InputStream?
if let taskNeedNewBodyStream = taskNeedNewBodyStream {
bodyStream = taskNeedNewBodyStream(session, task)
}
completionHandler(bodyStream)
}
@objc(URLSession:task:didCompleteWithError:)
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
if let taskDidCompleteWithError = taskDidCompleteWithError {
taskDidCompleteWithError(session, task, error)
} else {
if let error = error {
if self.error == nil { self.error = error }
if
let downloadDelegate = self as? DownloadTaskDelegate,
let resumeData = (error as NSError).userInfo[NSURLSessionDownloadTaskResumeData] as? Data {
downloadDelegate.resumeData = resumeData
}
}
queue.isSuspended = false
}
}
}
// MARK: -
class DataTaskDelegate: TaskDelegate, URLSessionDataDelegate {
// MARK: Properties
var dataTask: URLSessionDataTask { return task as! URLSessionDataTask }
override var data: Data? {
if dataStream != nil {
return nil
} else {
return mutableData
}
}
var progress: Progress
var progressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)?
var dataStream: ((_ data: Data) -> Void)?
private var totalBytesReceived: Int64 = 0
private var mutableData: Data
private var expectedContentLength: Int64?
// MARK: Lifecycle
override init(task: URLSessionTask?) {
mutableData = Data()
progress = Progress(totalUnitCount: 0)
super.init(task: task)
}
override func reset() {
super.reset()
progress = Progress(totalUnitCount: 0)
totalBytesReceived = 0
mutableData = Data()
expectedContentLength = nil
}
// MARK: URLSessionDataDelegate
var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> URLSession.ResponseDisposition)?
var dataTaskDidBecomeDownloadTask: ((URLSession, URLSessionDataTask, URLSessionDownloadTask) -> Void)?
var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)?
var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)?
func urlSession(
_ session: URLSession,
dataTask: URLSessionDataTask,
didReceive response: URLResponse,
completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
var disposition: URLSession.ResponseDisposition = .allow
expectedContentLength = response.expectedContentLength
if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse {
disposition = dataTaskDidReceiveResponse(session, dataTask, response)
}
completionHandler(disposition)
}
func urlSession(
_ session: URLSession,
dataTask: URLSessionDataTask,
didBecome downloadTask: URLSessionDownloadTask) {
dataTaskDidBecomeDownloadTask?(session, dataTask, downloadTask)
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
if let dataTaskDidReceiveData = dataTaskDidReceiveData {
dataTaskDidReceiveData(session, dataTask, data)
} else {
if let dataStream = dataStream {
dataStream(data)
} else {
mutableData.append(data)
}
let bytesReceived = Int64(data.count)
totalBytesReceived += bytesReceived
let totalBytesExpected = dataTask.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown
progress.totalUnitCount = totalBytesExpected
progress.completedUnitCount = totalBytesReceived
if let progressHandler = progressHandler {
progressHandler.queue.async { progressHandler.closure(self.progress) }
}
}
}
func urlSession(
_ session: URLSession,
dataTask: URLSessionDataTask,
willCacheResponse proposedResponse: CachedURLResponse,
completionHandler: @escaping (CachedURLResponse?) -> Void) {
var cachedResponse: CachedURLResponse? = proposedResponse
if let dataTaskWillCacheResponse = dataTaskWillCacheResponse {
cachedResponse = dataTaskWillCacheResponse(session, dataTask, proposedResponse)
}
completionHandler(cachedResponse)
}
}
// MARK: -
class DownloadTaskDelegate: TaskDelegate, URLSessionDownloadDelegate {
// MARK: Properties
var downloadTask: URLSessionDownloadTask { return task as! URLSessionDownloadTask }
var progress: Progress
var progressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)?
var resumeData: Data?
override var data: Data? { return resumeData }
var destination: DownloadRequest.DownloadFileDestination?
var temporaryURL: URL?
var destinationURL: URL?
var fileURL: URL? { return destination != nil ? destinationURL : temporaryURL }
// MARK: Lifecycle
override init(task: URLSessionTask?) {
progress = Progress(totalUnitCount: 0)
super.init(task: task)
}
override func reset() {
super.reset()
progress = Progress(totalUnitCount: 0)
resumeData = nil
}
// MARK: URLSessionDownloadDelegate
var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> URL)?
var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)?
var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)?
func urlSession(
_: URLSession,
downloadTask: URLSessionDownloadTask,
didFinishDownloadingTo location: URL) {
temporaryURL = location
guard
let destination = destination,
let response = downloadTask.response as? HTTPURLResponse
else { return }
let result = destination(location, response)
let destinationURL = result.destinationURL
let options = result.options
self.destinationURL = destinationURL
do {
if options.contains(.removePreviousFile), FileManager.default.fileExists(atPath: destinationURL.path) {
try FileManager.default.removeItem(at: destinationURL)
}
if options.contains(.createIntermediateDirectories) {
let directory = destinationURL.deletingLastPathComponent()
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
}
try FileManager.default.moveItem(at: location, to: destinationURL)
} catch {
self.error = error
}
}
func urlSession(
_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didWriteData bytesWritten: Int64,
totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64) {
if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
if let downloadTaskDidWriteData = downloadTaskDidWriteData {
downloadTaskDidWriteData(
session,
downloadTask,
bytesWritten,
totalBytesWritten,
totalBytesExpectedToWrite
)
} else {
progress.totalUnitCount = totalBytesExpectedToWrite
progress.completedUnitCount = totalBytesWritten
if let progressHandler = progressHandler {
progressHandler.queue.async { progressHandler.closure(self.progress) }
}
}
}
func urlSession(
_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didResumeAtOffset fileOffset: Int64,
expectedTotalBytes: Int64) {
if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset {
downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes)
} else {
progress.totalUnitCount = expectedTotalBytes
progress.completedUnitCount = fileOffset
}
}
}
// MARK: -
class UploadTaskDelegate: DataTaskDelegate {
// MARK: Properties
var uploadTask: URLSessionUploadTask { return task as! URLSessionUploadTask }
var uploadProgress: Progress
var uploadProgressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)?
// MARK: Lifecycle
override init(task: URLSessionTask?) {
uploadProgress = Progress(totalUnitCount: 0)
super.init(task: task)
}
override func reset() {
super.reset()
uploadProgress = Progress(totalUnitCount: 0)
}
// MARK: URLSessionTaskDelegate
var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)?
func URLSession(
_ session: URLSession,
task: URLSessionTask,
didSendBodyData bytesSent: Int64,
totalBytesSent: Int64,
totalBytesExpectedToSend: Int64) {
if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
if let taskDidSendBodyData = taskDidSendBodyData {
taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend)
} else {
uploadProgress.totalUnitCount = totalBytesExpectedToSend
uploadProgress.completedUnitCount = totalBytesSent
if let uploadProgressHandler = uploadProgressHandler {
uploadProgressHandler.queue.async { uploadProgressHandler.closure(self.uploadProgress) }
}
}
}
}
|
mit
|
ac2d947c211f30449feb09893a3e945f
| 33.988662 | 149 | 0.668892 | 6.172 | false | false | false | false |
garethpaul/swift-sample-apps
|
swift-objects-example/swift-objects-example/AppDelegate.swift
|
1
|
2622
|
//
// AppDelegate.swift
// swift-objects-example
//
// Created by Gareth Paul Jones on 6/4/14.
// Copyright (c) 2014 Gareth Paul Jones. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
// Override point for customization after application launch.
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window!.backgroundColor = UIColor.whiteColor()
var rootViewController = ViewController()
var rootNavigationController = UINavigationController(rootViewController: rootViewController)
self.window!.rootViewController = rootNavigationController
self.window!.makeKeyAndVisible()
return true
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:.
}
}
|
apache-2.0
|
02531f91456c8b28be62030158774724
| 45.821429 | 285 | 0.735317 | 5.762637 | false | false | false | false |
mxcl/swift-package-manager
|
Sources/Utility/PkgConfig.swift
|
1
|
11328
|
/*
This source file is part of the Swift.org open source project
Copyright 2015 - 2016 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import Basic
import func POSIX.getenv
import func POSIX.popen
public enum PkgConfigError: Swift.Error {
case couldNotFindConfigFile
case parsingError(String)
case nonWhitelistedFlags(String)
}
/// Get search paths from pkg-config itself.
///
/// This is needed because on Linux machines, the search paths can be different
/// from the standard locations that we are currently searching.
private let pkgConfigSearchPaths: [AbsolutePath] = {
let searchPaths = try? POSIX.popen(["pkg-config", "--variable", "pc_path", "pkg-config"]).chomp()
return searchPaths?.characters.split(separator: ":").map{ AbsolutePath(String($0)) } ?? []
}()
/// Information on an individual `pkg-config` supported package.
public struct PkgConfig {
/// The name of the package.
public let name: String
/// The path to the definition file.
public let pcFile: AbsolutePath
/// The list of C compiler flags in the definition.
public let cFlags: [String]
/// The list of libraries to link.
public let libs: [String]
/// The built-in search path list.
///
/// By default, this is combined with the search paths infered from
/// `pkg-config` itself.
private static let searchPaths = [
AbsolutePath("/usr/local/lib/pkgconfig"),
AbsolutePath("/usr/local/share/pkgconfig"),
AbsolutePath("/usr/lib/pkgconfig"),
AbsolutePath("/usr/share/pkgconfig"),
]
/// Load the information for the named package.
///
/// - throws: PkgConfigError
public init(name: String) throws {
self.name = name
self.pcFile = try PkgConfig.locatePCFile(name: name)
var parser = PkgConfigParser(pcFile: pcFile)
try parser.parse()
var cFlags = parser.cFlags
var libs = parser.libs
// If parser found dependencies in pc file, get their flags too.
if !parser.dependencies.isEmpty {
for dep in parser.dependencies {
// FIXME: This is wasteful, we should be caching the PkgConfig result.
let pkg = try PkgConfig(name: dep)
cFlags += pkg.cFlags
libs += pkg.libs
}
}
self.cFlags = cFlags
self.libs = libs
}
private static var envSearchPaths: [AbsolutePath] {
if let configPath = getenv("PKG_CONFIG_PATH") {
return configPath.characters.split(separator: ":").map{ AbsolutePath(String($0)) }
}
return []
}
private static func locatePCFile(name: String) throws -> AbsolutePath {
// FIXME: We should consider building a registry for all items in the
// search paths, which is likely to be substantially more efficient if
// we end up searching for a reasonably sized number of packages.
for path in OrderedSet(pkgConfigSearchPaths + searchPaths + envSearchPaths) {
let pcFile = path.appending(component: name + ".pc")
if isFile(pcFile) {
return pcFile
}
}
throw PkgConfigError.couldNotFindConfigFile
}
}
/// Parser for the `pkg-config` `.pc` file format.
///
/// See: https://www.freedesktop.org/wiki/Software/pkg-config/
//
// FIXME: This is only internal so it can be unit tested.
struct PkgConfigParser {
private let pcFile: AbsolutePath
private(set) var variables = [String: String]()
var dependencies = [String]()
var cFlags = [String]()
var libs = [String]()
init(pcFile: AbsolutePath) {
precondition(isFile(pcFile))
self.pcFile = pcFile
}
mutating func parse() throws {
func removeComment(line: String) -> String {
if let commentIndex = line.characters.index(of: "#") {
return line[line.characters.startIndex..<commentIndex]
}
return line
}
let file = try fopen(self.pcFile, mode: .read)
for line in try file.readFileContents().components(separatedBy: "\n") {
// Remove commented or any trailing comment from the line.
let uncommentedLine = removeComment(line: line)
// Ignore any empty or whitespace line.
guard let line = uncommentedLine.chuzzle() else { continue }
if line.characters.contains(":") {
// Found a key-value pair.
try parseKeyValue(line: line)
} else if line.characters.contains("=") {
// Found a variable.
let (name, maybeValue) = line.split(around: "=")
let value = maybeValue?.chuzzle() ?? ""
variables[name.chuzzle() ?? ""] = try resolveVariables(value)
} else {
// Unexpected thing in the pc file, abort.
throw PkgConfigError.parsingError("Unexpected line: \(line) in \(pcFile)")
}
}
}
private mutating func parseKeyValue(line: String) throws {
precondition(line.characters.contains(":"))
let (key, maybeValue) = line.split(around: ":")
let value = try resolveVariables(maybeValue?.chuzzle() ?? "")
switch key {
case "Requires":
dependencies = try parseDependencies(value)
case "Libs":
libs = splitEscapingSpace(value)
case "Cflags":
cFlags = splitEscapingSpace(value)
default:
break
}
}
/// Parses `Requires: ` string into array of dependencies.
///
/// The dependency string has seperator which can be (multiple) space or a
/// comma. Additionally each there can be an optional version constaint to
/// a dependency.
private func parseDependencies(_ depString: String) throws -> [String] {
let operators = ["=", "<", ">", "<=", ">="]
let separators = [" ", ","]
// Look at a char at an index if present.
func peek(idx: Int) -> Character? {
guard idx <= depString.characters.count - 1 else { return nil }
return depString.characters[depString.characters.index(depString.characters.startIndex, offsetBy: idx)]
}
// This converts the string which can be seperated by comma or spaces
// into an array of string.
func tokenize() -> [String] {
var tokens = [String]()
var token = ""
for (idx, char) in depString.characters.enumerated() {
// Encountered a seperator, use the token.
if separators.contains(String(char)) {
// If next character is a space skip.
if let peeked = peek(idx: idx+1), peeked == " " { continue }
// Append to array of tokens and reset token variable.
tokens.append(token)
token = ""
} else {
token += String(char)
}
}
// Append the last collected token if present.
if !token.isEmpty { tokens += [token] }
return tokens
}
var deps = [String]()
var it = tokenize().makeIterator()
while let arg = it.next() {
// If we encounter an operator then we need to skip the next token.
if operators.contains(arg) {
// We should have a version number next, skip.
guard let _ = it.next() else {
throw PkgConfigError.parsingError("Expected version number after \(deps.last) \(arg) in \"\(depString)\" in \(pcFile)")
}
} else {
// Otherwise it is a dependency.
deps.append(arg)
}
}
return deps
}
/// Perform variable expansion on the line by processing the each fragment
/// of the string until complete.
///
/// Variables occur in form of ${variableName}, we search for a variable
/// linearly in the string and if found, lookup the value of the variable in
/// our dictionary and replace the variable name with its value.
private func resolveVariables(_ line: String) throws -> String {
typealias StringIndex = String.CharacterView.Index
// Returns variable name, start index and end index of a variable in a string if present.
// We make sure it of form ${name} otherwise it is not a variable.
func findVariable(_ fragment: String) -> (name: String, startIndex: StringIndex, endIndex: StringIndex)? {
guard let dollar = fragment.characters.index(of: "$") else { return nil }
guard dollar != fragment.endIndex && fragment.characters[fragment.index(after: dollar)] == "{" else { return nil }
guard let variableEndIndex = fragment.characters.index(of: "}") else { return nil }
return (fragment[fragment.index(dollar, offsetBy: 2)..<variableEndIndex], dollar, variableEndIndex)
}
var result = ""
var fragment = line
while !fragment.isEmpty {
// Look for a variable in our current fragment.
if let variable = findVariable(fragment) {
// Append the contents before the variable.
result += fragment[fragment.characters.startIndex..<variable.startIndex]
guard let variableValue = variables[variable.name] else {
throw PkgConfigError.parsingError("Expected variable in \(pcFile)")
}
// Append the value of the variable.
result += variableValue
// Update the fragment with post variable string.
fragment = fragment[fragment.index(after: variable.endIndex)..<fragment.characters.endIndex]
} else {
// No variable found, just append rest of the fragment to result.
result += fragment
fragment = ""
}
}
return result
}
/// Split line on unescaped spaces
///
/// Will break on space in "abc def" and "abc\\ def" but not in "abc\ def"
/// and ignore multiple spaces such that "abc def" will split into ["abc",
/// "def"].
private func splitEscapingSpace(_ line: String) -> [String] {
var splits = [String]()
var fragment = [Character]()
func saveFragment() {
if !fragment.isEmpty {
splits.append(String(fragment))
fragment.removeAll()
}
}
var it = line.characters.makeIterator()
while let char = it.next() {
if char == "\\" {
if let next = it.next() {
fragment.append(next)
}
} else if char == " " {
saveFragment()
} else {
fragment.append(char)
}
}
saveFragment()
return splits
}
}
|
apache-2.0
|
1376023f5c688e611deb69dcc8fdc001
| 37.662116 | 139 | 0.577419 | 4.755668 | false | true | false | false |
ulrikdamm/Sqlable
|
Sources/Sqlable/SqlValue.swift
|
1
|
2033
|
//
// SqlValue.swift
// Simplyture
//
// Created by Ulrik Damm on 27/10/2015.
// Copyright © 2015 Robocat. All rights reserved.
//
import Foundation
import SQLite3
/// A value which can be used to write to a sql row
public protocol SqlValue {
/// Bind the value of the type to a position in a write handle
func bind(_ db : OpaquePointer, handle : OpaquePointer, index : Int32) throws
}
extension Int : SqlValue {
public func bind(_ db : OpaquePointer, handle : OpaquePointer, index : Int32) throws {
if sqlite3_bind_int64(handle, index, Int64(self)) != SQLITE_OK {
try throwLastError(db)
}
}
}
extension String : SqlValue {
public func bind(_ db : OpaquePointer, handle : OpaquePointer, index : Int32) throws {
if sqlite3_bind_text(handle, index, self, -1, SqliteDatabase.SQLITE_TRANSIENT) != SQLITE_OK {
try throwLastError(db)
}
}
}
extension Date : SqlValue {
public func bind(_ db : OpaquePointer, handle : OpaquePointer, index : Int32) throws {
if sqlite3_bind_int64(handle, index, Int64(self.timeIntervalSince1970)) != SQLITE_OK {
try throwLastError(db)
}
}
}
extension Double : SqlValue {
public func bind(_ db : OpaquePointer, handle : OpaquePointer, index : Int32) throws {
if sqlite3_bind_double(handle, index, self) != SQLITE_OK {
try throwLastError(db)
}
}
}
extension Float : SqlValue {
public func bind(_ db : OpaquePointer, handle : OpaquePointer, index : Int32) throws {
if sqlite3_bind_double(handle, index, Double(self)) != SQLITE_OK {
try throwLastError(db)
}
}
}
extension Bool : SqlValue {
public func bind(_ db : OpaquePointer, handle : OpaquePointer, index : Int32) throws {
if sqlite3_bind_int(handle, index, Int32(self ? 1 : 0)) != SQLITE_OK {
try throwLastError(db)
}
}
}
/// A SQL null
public struct Null {
public init() {
}
}
extension Null : SqlValue {
public func bind(_ db : OpaquePointer, handle : OpaquePointer, index : Int32) throws {
if sqlite3_bind_null(handle, index) != SQLITE_OK {
try throwLastError(db)
}
}
}
|
mit
|
b9c543e9bef8eb584719190b98bb04e3
| 24.721519 | 95 | 0.688976 | 3.205047 | false | false | false | false |
urbn/URBNSwiftyConvenience
|
Sources/URBNSwiftyConvenience/QRCodeGenerator.swift
|
1
|
2377
|
//
// QRCodeGenerator.swift
// Pods
//
// Created by Nick DiStefano on 12/23/15.
//
//
import CoreImage
import UIKit
public extension String {
func qrImage(inputCorrection: String = "Q") -> CIImage? {
let data = self.data(using: String.Encoding.isoLatin1, allowLossyConversion: false)
let filter = CIFilter(name: "CIQRCodeGenerator")
filter?.setValue(data, forKey: "inputMessage")
filter?.setValue(inputCorrection, forKey: "inputCorrectionLevel")
return filter?.outputImage
}
/// 7.00 is default Min is 0 Max is 20
func barcode128(inputQuietSpace: NSNumber = 7.00) -> CIImage? {
let data = self.data(using: String.Encoding.isoLatin1, allowLossyConversion: false)
let filter = CIFilter(name: "CICode128BarcodeGenerator")
filter?.setValue(data, forKey: "inputMessage")
filter?.setValue(inputQuietSpace, forKey: "inputQuietSpace")
return filter?.outputImage
}
}
public extension UIImage {
static func createFromCIImage(_ ciImage: CIImage?, foregroundColor: UIColor, backgroundColor: UIColor, size: CGSize) -> UIImage? {
return ciImage?.scale(size)?.color(foregroundColor: foregroundColor, backgroundColor: backgroundColor)?.mapToUIImage()
}
}
public extension CIImage {
func mapToUIImage() -> UIImage? {
return UIImage(ciImage: self)
}
func scale(_ size: CGSize) -> CIImage? {
let scaleX = size.width / extent.size.width
let scaleY = size.height / extent.size.height
return transformed(by: CGAffineTransform(scaleX: scaleX, y: scaleY))
}
func color(foregroundColor: UIColor, backgroundColor: UIColor) -> CIImage? {
let foregroundCoreColor = CIColor(uiColor: foregroundColor)
let backgroundCoreColor = CIColor(uiColor: backgroundColor)
let colorFilter = CIFilter(name: "CIFalseColor", parameters: ["inputImage": self, "inputColor0":foregroundCoreColor, "inputColor1":backgroundCoreColor])
return colorFilter?.outputImage
}
}
extension CIColor {
convenience init(uiColor: UIColor) {
let foregroundColorRef = uiColor.cgColor
let foregroundColorString = CIColor(cgColor: foregroundColorRef).stringRepresentation
self.init(string: foregroundColorString)
}
}
|
mit
|
1103e416dbbec4fc04a0f442f42ec98c
| 32.957143 | 160 | 0.673117 | 4.706931 | false | false | false | false |
Recover-Now/iOS-App
|
Recover Now/Recover Now/Models/FirebaseStorage.swift
|
1
|
2410
|
//
// FirebaseStorage.swift
// True Pass
//
// Created by Cliff Panos on 6/14/17.
// Copyright © 2017 Clifford Panos. All rights reserved.
//
import UIKit
import FirebaseStorage
import Firebase
@objc class FirebaseStorage: NSObject {
///The shared FirebaseStorage object
static let shared = FirebaseStorage()
let storage: Storage
let storageRef: StorageReference
let TPProfilePictureMaxSize: Int64 = 4*1024*1024
let TPPassPictureMaxSize: Int64 = 4*1024*1024
override init() {
storage = Storage.storage()
storageRef = storage.reference()
super.init()
}
var usersDirectoryReference: StorageReference {
return storageRef.child("\(FirebaseEntity.RNUser)")
}
var pngMetadata: StorageMetadata {
let metadata = StorageMetadata()
metadata.contentType = "image/png"
return metadata
}
func uploadImage(data: Data, for entity: FirebaseEntity, withIdentifier identifier: String, _ handler: @escaping (StorageMetadata?, Error?) -> Void) {
let childRef = storageRef.child(entity.rawValue).child(identifier)
childRef.putData(data, metadata: pngMetadata) { metadata, error in
handler(metadata, error) }
}
func retrieveImageData(for identifier: String, entity: FirebaseEntity, handler: @escaping (Data?, Error?) -> Void) {
let reference = storageRef.child(entity.rawValue).child(identifier)
reference.getData(maxSize: TPPassPictureMaxSize, completion: handler)
}
func retrieveProfilePicture(for uid: String, _ handler: @escaping (Data?, Error?) -> Void) {
let childRef = usersDirectoryReference.child(uid)
childRef.getData(maxSize: TPProfilePictureMaxSize, completion: handler)
}
func retrieveProfilePictureForCurrentUser(_ handler: @escaping (Data?, Error?) -> Void) {
if let currentID = Accounts.userIdentifier {
retrieveProfilePicture(for: currentID, handler)
}
}
func deleteImage(forEntity entity: FirebaseEntity, withIdentifier identifier: String) {
guard entity == .RNUser || entity == .RNLocation || entity == .RNResource else {
print("This type of entity does not have image data")
return
}
storageRef.child(entity.rawValue).child(identifier).delete(completion: nil)
}
}
|
mit
|
6a9daa4bbf498aace89857579121ed3d
| 32.929577 | 154 | 0.665836 | 4.705078 | false | false | false | false |
xcodeswift/xcproj
|
Sources/XcodeProj/Objects/Files/PBXSourceTree.swift
|
1
|
3090
|
import Foundation
/// Specifies source trees for files
/// Corresponds to the "Location" dropdown in Xcode's File Inspector
public enum PBXSourceTree: CustomStringConvertible, Equatable, Decodable {
case none
case absolute
case group
case sourceRoot
case buildProductsDir
case sdkRoot
case developerDir
case custom(String)
private static let noneValue = ""
private static let absoluteValue = "<absolute>"
private static let groupValue = "<group>"
private static let sourceRootValue = "SOURCE_ROOT"
private static let buildProductsDirValue = "BUILT_PRODUCTS_DIR"
private static let sdkRootValue = "SDKROOT"
private static let developerDirValue = "DEVELOPER_DIR"
public init(value: String) {
switch value {
case PBXSourceTree.noneValue:
self = .none
case PBXSourceTree.absoluteValue:
self = .absolute
case PBXSourceTree.groupValue:
self = .group
case PBXSourceTree.sourceRootValue:
self = .sourceRoot
case PBXSourceTree.buildProductsDirValue:
self = .buildProductsDir
case PBXSourceTree.sdkRootValue:
self = .sdkRoot
case PBXSourceTree.developerDirValue:
self = .developerDir
default:
self = .custom(value)
}
}
public init(from decoder: Decoder) throws {
try self.init(value: decoder.singleValueContainer().decode(String.self))
}
public static func == (lhs: PBXSourceTree, rhs: PBXSourceTree) -> Bool {
switch (lhs, rhs) {
case (.none, .none),
(.absolute, .absolute),
(.group, .group),
(.sourceRoot, .sourceRoot),
(.buildProductsDir, .buildProductsDir),
(.sdkRoot, .sdkRoot),
(.developerDir, .developerDir):
return true
case let (.custom(lhsValue), .custom(rhsValue)):
return lhsValue == rhsValue
case (.none, _),
(.absolute, _),
(.group, _),
(.sourceRoot, _),
(.buildProductsDir, _),
(.sdkRoot, _),
(.developerDir, _),
(.custom, _):
return false
}
}
public var description: String {
switch self {
case .none:
return PBXSourceTree.noneValue
case .absolute:
return PBXSourceTree.absoluteValue
case .group:
return PBXSourceTree.groupValue
case .sourceRoot:
return PBXSourceTree.sourceRootValue
case .buildProductsDir:
return PBXSourceTree.buildProductsDirValue
case .sdkRoot:
return PBXSourceTree.sdkRootValue
case .developerDir:
return PBXSourceTree.developerDirValue
case let .custom(value):
return value
}
}
}
// MARK: - PBXSourceTree Extension (PlistValue)
extension PBXSourceTree {
func plist() -> PlistValue {
.string(CommentedString(String(describing: self)))
}
}
|
mit
|
af99f1fc5cff7bfe65cce4657132073b
| 29.294118 | 80 | 0.59288 | 4.783282 | false | false | false | false |
Marquis103/FitJourney
|
FitJourney/DiaryEntry.swift
|
1
|
1627
|
//
// DiaryEntry.swift
// FitJourney
//
// Created by Marquis Dennis on 4/19/16.
// Copyright © 2016 Marquis Dennis. All rights reserved.
//
import UIKit
import CoreData
class DiaryEntry: NSManagedObject {
var sectionName: String {
let entrySectionDate = NSDate(timeIntervalSince1970: self.date)
let formatter = NSDateFormatter()
formatter.dateFormat = "MMM yyyy"
return formatter.stringFromDate(entrySectionDate)
}
enum DiaryEntryMood: Int16 {
case Good = 0
case Average = 1
case Bad = 2
}
override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) {
super.init(entity: entity, insertIntoManagedObjectContext: context)
}
init(context: NSManagedObjectContext) {
let entryEntity = NSEntityDescription.entityForName("DiaryEntry", inManagedObjectContext: context)!
super.init(entity: entryEntity, insertIntoManagedObjectContext: context)
}
func saveEntry(context: NSManagedObjectContext) {
}
func saveEntry(withBody text:String, mood:Int16, image: UIImage?, location:String?) throws {
self.body = text
self.mood = mood
if self.date == 0.0 {
self.date = NSDate().timeIntervalSince1970
}
if self.location == nil {
self.location = location ?? "No Location"
}
if let image = image {
self.imageData = UIImageJPEGRepresentation(image, 0.80)
} else {
self.imageData = UIImageJPEGRepresentation(UIImage(named: "icn_noimage")!, 0.80)
}
do {
try self.managedObjectContext?.save()
} catch let error as NSError {
throw error
//print("show alert controller here \(error)")
}
}
}
|
gpl-3.0
|
affe907c9d61633626d9b948f0aab645
| 23.268657 | 110 | 0.718942 | 3.853081 | false | false | false | false |
google/GoogleSignIn-iOS
|
Samples/Swift/DaysUntilBirthday/Shared/Services/UserProfileImageLoader.swift
|
1
|
1952
|
/*
* 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.
*/
#if os(iOS)
typealias GIDImage = UIImage
#elseif os(macOS)
typealias GIDImage = NSImage
#endif
import Combine
import SwiftUI
import GoogleSignIn
/// An observable class for loading the current user's profile image.
final class UserProfileImageLoader: ObservableObject {
private let userProfile: GIDProfileData
private let imageLoaderQueue = DispatchQueue(label: "com.google.days-until-birthday")
/// A `UIImage` property containing the current user's profile image.
/// - note: This will default to a placeholder, and updates will be published to subscribers.
@Published var image = GIDImage(named: "PlaceholderAvatar")!
/// Creates an instance of this loader with provided user profile.
/// - note: The instance will asynchronously fetch the image data upon creation.
init(userProfile: GIDProfileData) {
self.userProfile = userProfile
guard userProfile.hasImage else {
return
}
imageLoaderQueue.async {
#if os(iOS)
let dimension = 45 * UIScreen.main.scale
#elseif os(macOS)
let dimension = 120
#endif
guard let url = userProfile.imageURL(withDimension: UInt(dimension)),
let data = try? Data(contentsOf: url),
let image = GIDImage(data: data) else {
return
}
DispatchQueue.main.async {
self.image = image
}
}
}
}
|
apache-2.0
|
3cb0ead3eb917e8f15e3497d3f3b1777
| 32.084746 | 95 | 0.70748 | 4.41629 | false | false | false | false |
rolson/arcgis-runtime-samples-ios
|
arcgis-ios-sdk-samples/Features/Feature layer query/FLQueryViewController.swift
|
1
|
4260
|
// Copyright 2016 Esri.
//
// 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 ArcGIS
class FLQueryViewController: UIViewController, UISearchBarDelegate {
@IBOutlet private weak var mapView:AGSMapView!
private var map:AGSMap!
private var featureTable:AGSServiceFeatureTable!
private var featureLayer:AGSFeatureLayer!
private var selectedFeatures = [AGSFeature]()
override func viewDidLoad() {
super.viewDidLoad()
//add the source code button item to the right of navigation bar
(self.navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["FLQueryViewController"]
//initialize map with topographic basemap
self.map = AGSMap(basemap: AGSBasemap.topographicBasemap())
//assign map to the map view
self.mapView.map = self.map
//create feature table using a url
self.featureTable = AGSServiceFeatureTable(URL: NSURL(string: "https://sampleserver6.arcgisonline.com/arcgis/rest/services/USA/MapServer/2")!)
//create feature layer using this feature table
self.featureLayer = AGSFeatureLayer(featureTable: self.featureTable)
//set a new renderer
let lineSymbol = AGSSimpleLineSymbol(style: .Solid, color: UIColor.blackColor(), width: 1)
let fillSymbol = AGSSimpleFillSymbol(style: .Solid, color: UIColor.yellowColor().colorWithAlphaComponent(0.5), outline: lineSymbol)
self.featureLayer.renderer = AGSSimpleRenderer(symbol: fillSymbol)
//add feature layer to the map
self.map.operationalLayers.addObject(self.featureLayer)
//zoom to a custom viewpoint
self.mapView.setViewpointCenter(AGSPoint(x: -11e6, y: 5e6, spatialReference: AGSSpatialReference.webMercator()), scale: 9e7, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func queryForState(state:String) {
//un select if any features already selected
if self.selectedFeatures.count > 0 {
self.featureLayer.unselectFeatures(self.selectedFeatures)
}
let queryParams = AGSQueryParameters()
queryParams.whereClause = "upper(STATE_NAME) LIKE '%\(state.uppercaseString)%'"
self.featureTable.queryFeaturesWithParameters(queryParams, completion: { [weak self] (result:AGSFeatureQueryResult?, error:NSError?) -> Void in
if let error = error {
print(error.localizedDescription)
//update selected features array
self?.selectedFeatures.removeAll(keepCapacity: false)
}
else if let features = result?.featureEnumerator().allObjects {
if features.count > 0 {
self?.featureLayer.selectFeatures(features)
//zoom to the selected feature
self?.mapView.setViewpointGeometry(features[0].geometry!, padding: 200, completion: nil)
}
else {
SVProgressHUD.showErrorWithStatus("No state by that name", maskType: .Gradient)
}
//update selected features array
self?.selectedFeatures = features
}
})
}
//MARK: - Search bar delegate
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
if let text = searchBar.text {
self.queryForState(text)
}
searchBar.resignFirstResponder()
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
searchBar.resignFirstResponder()
}
}
|
apache-2.0
|
85e781d153b4a14f9d9bbe6a17a81e53
| 40.764706 | 151 | 0.661268 | 5.04142 | false | false | false | false |
saeta/penguin
|
Sources/PenguinTesting/StdlibProtocolTests.swift
|
1
|
19079
|
// Copyright 2020 The Penguin 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 XCTest
extension Equatable {
/// XCTests `Self`'s conformance to `Equatable`, given equivalent instances.
///
/// If `Self` has a distinguishable identity or any remote parts, `self`, `self1`, and `self2`
/// should not be trivial copies of each other. In other words, the instances should be as
/// different as possible internally, while still being equal. Otherwise, it's fine to pass `nil`
/// (the default) for `self1` and `self2`.
///
/// - Precondition: `self == (self1 ?? self) && self1 == (self2 ?? self)`.
public func checkEquatableSemantics(equal self1: Self? = nil, _ self2: Self? = nil) {
let self1 = self1 ?? self
let self2 = self2 ?? self
precondition(self == self1)
precondition(self1 == self2)
XCTAssertEqual(self, self, "reflexivity")
XCTAssertEqual(self1, self1, "reflexivity")
XCTAssertEqual(self2, self2, "reflexivity")
XCTAssertEqual(self1, self, "symmetry")
XCTAssertEqual(self2, self1, "symmetry")
XCTAssertEqual(self, self2, "transitivity")
}
}
extension Hashable {
/// XCTests `Self`'s conformance to `Hashable`, given equivalent instances.
///
/// If `Self` has a distinguishable identity or any remote parts, `self`, `self1`, and `self2`
/// should not be trivial copies of each other. In other words, the instances should be as
/// different as possible internally, while still being equal. Otherwise, it's fine to pass `nil`
/// (the default) for `self1` and `self2`.
///
/// - Precondition: `self == (self1 ?? self) && self1 == (self2 ?? self)`
public func checkHashableSemantics(equal self1: Self? = nil, _ self2: Self? = nil) {
let self1 = self1 ?? self
let self2 = self2 ?? self
checkEquatableSemantics(equal: self1, self2)
XCTAssertEqual(self.hashValue, self1.hashValue)
XCTAssertEqual(self.hashValue, self2.hashValue)
}
}
extension Comparable {
/// XCTests that `self` obeys all comparable laws with respect to an equivalent instance
///
/// If `Self` has a distinguishable identity or any remote parts, `self` and `self1` should
/// not be trivial copies of each other. In other words, the instances should be as different as
/// possible internally, while still being equal. Otherwise, it's fine to pass `nil` (the
/// default) for `self1`.
///
/// - Precondition: `self == (self1 ?? self)`
private func checkComparableUnordered(equal self1: Self? = nil) {
let self1 = self1 ?? self
precondition(self == self1)
// Comparable still has distinct requirements for <,>,<=,>= so we need to check them all :(
// Not Using XCTAssertLessThanOrEqual et al. because we don't want to be reliant on them calling
// the operators literally; there are other ways they could be implemented.
XCTAssertFalse(self < self1)
XCTAssertFalse(self > self1)
XCTAssertFalse(self1 < self)
XCTAssertFalse(self1 > self)
XCTAssert(self <= self1)
XCTAssert(self >= self1)
XCTAssert(self1 <= self)
XCTAssert(self1 >= self)
}
/// XCTests that `self` obeys all comparable laws with respect to `greater`.
///
/// - Precondition: `self < greater`.
private func checkComparableOrdering(greater: Self) {
precondition(self < greater)
// Comparable still has distinct requirements for <,>,<=,>= so we need to check them all :(
// Not Using XCTAssertLessThanOrEqual et al. because we don't want to be reliant on them calling
// the operators literally; there are other ways they could be implemented.
XCTAssert(self <= greater)
XCTAssertNotEqual(self, greater)
XCTAssertFalse(self >= greater)
XCTAssertFalse(self > greater)
XCTAssertFalse(greater < self)
XCTAssertFalse(greater <= self)
XCTAssert(greater >= self)
XCTAssert(greater > self)
}
/// XCTests `Self`'s conformance to `Comparable`.
///
/// If `Self` has a distinguishable identity or any remote parts, `self`, `self1`, and `self2`
/// should not be trivial copies of each other. In other words, the instances should be as
/// different as possible internally, while still being equal. Otherwise, it's fine to pass `nil`
/// (the default) for `self1` and `self2`.
///
/// If distinct values for `greater` or `greaterStill` are unavailable (e.g. when `Self` only has
/// one or two values), the caller may pass `nil` values. Callers are encouraged to pass non-`nil`
/// values whenever they are available, because they enable more checks.
///
/// - Precondition: `self == (self1 ?? self) && self1 == (self2 ?? self)`.
/// - Precondition: if `greaterStill != nil`, `greater != nil`.
/// - Precondition: if `greater != nil`, `self < greater!`.
/// - Precondition: if `greaterStill != nil`, `greater! < greaterStill!`.
public func checkComparableSemantics(
equal self1: Self? = nil, _ self2: Self? = nil, greater: Self?, greaterStill: Self?
) {
precondition(
greater != nil || greaterStill == nil, "`greaterStill` should be `nil` when `greater` is")
checkEquatableSemantics(equal: self1, self2)
self.checkComparableUnordered(equal: self)
self.checkComparableUnordered(equal: self1)
self.checkComparableUnordered(equal: self2)
(self1 ?? self).checkComparableUnordered(equal: self2)
greater?.checkComparableUnordered()
greaterStill?.checkComparableUnordered()
if let greater = greater {
self.checkComparableOrdering(greater: greater)
if let greaterStill = greaterStill {
greater.checkComparableOrdering(greater: greaterStill)
// Transitivity
self.checkComparableOrdering(greater: greaterStill)
}
}
}
/// Given three unequal instances, returns them in increasing order, relying only on <.
///
/// This function can be useful for checking comparable conformance in conditions where you know
/// you have unequal instances, but can't control the ordering.
///
/// let (min, mid, max) = X.sort3(X(a), X(b), X(c))
/// min.checkComparableSemantics(greater: mid, greaterStill: max)
///
public static func sort3(_ a: Self, _ b: Self, _ c: Self) -> (Self, Self, Self) {
precondition(a != b)
precondition(a != c)
precondition(b != c)
let min = a < b
? a < c ? a : c
: b < c ? b : c
let max = a < b
? b < c ? c : b
: a < c ? c : a
let mid = a < b
? b < c
? b
: a < c ? c : a
: a < c
? a
: b < c ? c : b
return (min, mid, max)
}
}
// ************************************************
// Checking the traversal properties of sequences.
/// A type that “generic type predicates” can conform to when their result is
///// true.
fileprivate protocol True {}
/// A “generic type predicate” that detects whether a type is a
/// `BidirectionalCollection`.
fileprivate struct IsBidirectionalCollection<C> {}
extension IsBidirectionalCollection: True where C : BidirectionalCollection { }
/// A “generic type predicate” that detects whether a type is a
/// `RandomAccessCollection`.
fileprivate struct IsRandomAccessCollection<C> {}
extension IsRandomAccessCollection: True where C : RandomAccessCollection { }
extension Collection {
/// True iff `Self` conforms to `BidirectionalCollection`.
///
/// Useful in asserting that a certain collection is *not* declared to conform
/// to `BidirectionalCollection`.
public var isBidirectional: Bool {
return IsBidirectionalCollection<Self>.self is True.Type
}
/// True iff `Self` conforms to `RandomAccessCollection`.
///
/// Useful in asserting that a certain collection is *not* declared to conform
/// to `RandomAccessCollection`.
public var isRandomAccess: Bool {
return IsRandomAccessCollection<Self>.self is True.Type
}
}
// *********************************************************************
// Checking sequence/collection semantics. Note that these checks cannot see
// any declarations that happen to shadow the protocol requirements. Those
// shadows have to be tested separately.
extension Sequence where Element: Equatable {
/// XCTests `self`'s semantic conformance to `Sequence`, expecting its
/// elements to match `expectedContents`.
///
/// - Complexity: O(N), where N is `expectedContents.count`.
/// - Note: the fact that a call to this method compiles verifies static
/// conformance.
public func checkSequenceSemantics<
ExampleContents: Collection>(expecting expectedContents: ExampleContents)
where ExampleContents.Element == Element
{
var i = self.makeIterator()
var remainder = expectedContents[...]
while let x = i.next() {
XCTAssertEqual(
remainder.popFirst(), x, "Sequence contents don't match expectations")
}
XCTAssert(
remainder.isEmpty,
"Expected tail elements \(Array(remainder)) not present in Sequence.")
XCTAssertEqual(
i.next(), nil,
"Exhausted iterator expected to return nil from next() in perpetuity.")
}
}
extension Collection where Element: Equatable {
/// XCTests `self`'s semantic conformance to `Collection`, expecting its
/// elements to match `expectedContents`.
///
/// - Parameter maxSupportedCount: the maximum number of elements that instances of `Self` can
/// have.
///
/// - Requires: `self.count >= 2 || self.count >= maxSupportedCount`.
/// - Complexity: O(N²), where N is `self.count`.
/// - Note: the fact that a call to this method compiles verifies static
/// conformance.
public func checkCollectionSemantics<ExampleContents: Collection>(
expecting expectedContents: ExampleContents, maxSupportedCount: Int = Int.max
) where ExampleContents.Element == Element {
precondition(
self.count >= 2 || self.count >= maxSupportedCount,
"must have at least \(Swift.min(2, maxSupportedCount)) elements")
let indicesWithEnd = Array(indices) + [endIndex]
startIndex.checkComparableSemantics(
greater: indicesWithEnd.dropFirst().first,
greaterStill: indicesWithEnd.dropFirst(2).first)
checkSequenceSemantics(expecting: expectedContents)
var i = startIndex
var firstPassElements: [Element] = []
var remainingCount: Int = expectedContents.count
var offset: Int = 0
var expectedIndices = indices[...]
while i != endIndex {
XCTAssertEqual(
i, expectedIndices.popFirst()!,
"elements of indices don't match index(after:) results.")
XCTAssertLessThan(i, endIndex)
let j = self.index(after: i)
XCTAssertLessThan(i, j)
firstPassElements.append(self[i])
XCTAssertEqual(index(i, offsetBy: remainingCount), endIndex)
if offset != 0 {
XCTAssertEqual(
index(startIndex, offsetBy: offset - 1, limitedBy: i),
index(startIndex, offsetBy: offset - 1))
}
XCTAssertEqual(
index(startIndex, offsetBy: offset, limitedBy: i), i)
if remainingCount != 0 {
XCTAssertEqual(
index(startIndex, offsetBy: offset + 1, limitedBy: i), nil)
}
XCTAssertEqual(distance(from: i, to: endIndex), remainingCount)
i = j
remainingCount -= 1
offset += 1
}
XCTAssert(firstPassElements.elementsEqual(expectedContents))
// Check that the second pass has the same elements.
XCTAssert(indices.lazy.map { self[$0] }.elementsEqual(expectedContents))
}
/// Returns `index(i, offsetBy: n)`, invoking the implementation that
/// satisfies the generic requirement, without interference from anything that
/// happens to shadow it.
func generic_index(_ i: Index, offsetBy n: Int) -> Index {
index(i, offsetBy: n)
}
/// Returns `index(i, offsetBy: n, limitedBy: limit)`, invoking the
/// implementation that satisfies the generic requirement, without
/// interference from anything that happens to shadow it.
func generic_index(
_ i: Index, offsetBy n: Int, limitedBy limit: Index
) -> Index? {
index(i, offsetBy: n, limitedBy: limit)
}
/// Returns `distance(from: i, to: j)`, invoking the
/// implementation that satisfies the generic requirement, without
/// interference from anything that happens to shadow it.
func generic_distance(from i: Index, to j: Index) -> Int {
distance(from: i, to: j)
}
}
extension BidirectionalCollection where Element: Equatable {
/// XCTests `self`'s semantic conformance to `BidirectionalCollection`,
/// expecting its elements to match `expectedContents`.
///
/// - Parameter maxSupportedCount: the maximum number of elements that instances of `Self` can
/// have.
///
/// - Requires: `self.count >= 2 || self.count >= maxSupportedCount`.
/// - Complexity: O(N²), where N is `self.count`.
/// - Note: the fact that a call to this method compiles verifies static
/// conformance.
public func checkBidirectionalCollectionSemantics<ExampleContents: Collection>(
expecting expectedContents: ExampleContents, maxSupportedCount: Int = Int.max
) where ExampleContents.Element == Element {
checkCollectionSemantics(
expecting: expectedContents, maxSupportedCount: maxSupportedCount)
var i = startIndex
while i != endIndex {
let j = index(after: i)
XCTAssertEqual(index(before: j), i)
let offset = distance(from: i, to: startIndex)
XCTAssertLessThanOrEqual(offset, 0)
XCTAssertEqual(index(i, offsetBy: offset), startIndex)
i = j
}
}
}
/// Shared storage for operation counts.
///
/// This is a class:
/// - so that increments aren't missed due to copies
/// - because non-mutating operations on `RandomAccessOperationCounter` have
/// to update it.
public final class RandomAccessOperationCounts {
/// The number of invocations of `index(after:)`
public var indexAfter: Int = 0
/// The number of invocations of `index(before:)`
public var indexBefore: Int = 0
/// Creates an instance with zero counter values.
public init() {}
/// Reset all counts to zero.
public func reset() { (indexAfter, indexBefore) = (0, 0) }
}
/// A wrapper over some `Base` collection that counts index increment/decrement
/// operations.
///
/// This wrapper is useful for verifying that generic collection adapters that
/// conditionally conform to `RandomAccessCollection` are actually providing the
/// correct complexity.
public struct RandomAccessOperationCounter<Base: RandomAccessCollection> {
public var base: Base
public typealias Index = Base.Index
public typealias Element = Base.Element
/// The number of index incrementat/decrement operations applied to `self` and
/// all its copies.
public var operationCounts = RandomAccessOperationCounts()
}
extension RandomAccessOperationCounter: RandomAccessCollection {
public var startIndex: Index { base.startIndex }
public var endIndex: Index { base.endIndex }
public subscript(i: Index) -> Base.Element { base[i] }
public func index(after i: Index) -> Index {
operationCounts.indexAfter += 1
return base.index(after: i)
}
public func index(before i: Index) -> Index {
operationCounts.indexBefore += 1
return base.index(before: i)
}
public func index(_ i: Index, offsetBy n: Int) -> Index {
base.index(i, offsetBy: n)
}
public func index(_ i: Index, offsetBy n: Int, limitedBy limit: Index) -> Index? {
base.index(i, offsetBy: n, limitedBy: limit)
}
public func distance(from i: Index, to j: Index) -> Int {
base.distance(from: i, to: j)
}
}
extension RandomAccessCollection where Element: Equatable {
/// XCTests `self`'s semantic conformance to `RandomAccessCollection`,
/// expecting its elements to match `expectedContents`.
///
/// - Parameter operationCounts: if supplied, should be an instance that
/// tracks operations in copies of `self`.
/// - Parameter maxSupportedCount: the maximum number of elements that instances of `Self` can
/// have.
///
/// - Requires: `self.count >= 2 || self.count >= maxSupportedCount`.
/// - Complexity: O(N²), where N is `self.count`.
/// - Note: the fact that a call to this method compiles verifies static
/// conformance.
public func checkRandomAccessCollectionSemantics<ExampleContents: Collection>(
expecting expectedContents: ExampleContents,
operationCounts: RandomAccessOperationCounts = .init(),
maxSupportedCount: Int = Int.max
)
where ExampleContents.Element == Element
{
checkBidirectionalCollectionSemantics(
expecting: expectedContents, maxSupportedCount: maxSupportedCount)
operationCounts.reset()
XCTAssertEqual(generic_distance(from: startIndex, to: endIndex), count)
XCTAssertEqual(operationCounts.indexAfter, 0)
XCTAssertEqual(operationCounts.indexBefore, 0)
XCTAssertEqual(generic_distance(from: endIndex, to: startIndex), -count)
XCTAssertEqual(operationCounts.indexAfter, 0)
XCTAssertEqual(operationCounts.indexBefore, 0)
XCTAssertEqual(index(startIndex, offsetBy: count), endIndex)
XCTAssertEqual(operationCounts.indexAfter, 0)
XCTAssertEqual(operationCounts.indexBefore, 0)
XCTAssertEqual(index(endIndex, offsetBy: -count), startIndex)
XCTAssertEqual(operationCounts.indexAfter, 0)
XCTAssertEqual(operationCounts.indexBefore, 0)
XCTAssertEqual(
index(startIndex, offsetBy: count, limitedBy: endIndex), endIndex)
XCTAssertEqual(operationCounts.indexAfter, 0)
XCTAssertEqual(operationCounts.indexBefore, 0)
XCTAssertEqual(
index(endIndex, offsetBy: -count, limitedBy: startIndex), startIndex)
XCTAssertEqual(operationCounts.indexAfter, 0)
XCTAssertEqual(operationCounts.indexBefore, 0)
}
}
extension MutableCollection where Element: Equatable {
/// XCTests `self`'s semantic conformance to `MutableCollection`.
///
/// - Requires: `count == distinctContents.count && !self.elementsEqual(distinctContents)`.
public mutating func checkMutableCollectionSemantics<C: Collection>(writing distinctContents: C)
where C.Element == Element
{
precondition(
count == distinctContents.count, "distinctContents must have the same length as self.")
precondition(
!self.elementsEqual(distinctContents),
"distinctContents must not have the same elements as self")
for (i, e) in zip(indices, distinctContents) { self[i] = e }
XCTAssert(self.elementsEqual(distinctContents))
}
}
|
apache-2.0
|
1102943a905970fbcf7261b956ee3951
| 37.513131 | 100 | 0.684536 | 4.321922 | false | false | false | false |
techgrains/TGFramework-iOS
|
TGFrameworkExample/TGFrameworkExample/Classes/Controller/FilterEmployeeListViewController.swift
|
1
|
4036
|
import UIKit
import TGFramework
class FilterEmployeeListViewController: BaseViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate {
@IBOutlet var employeeListTableView:UITableView!
@IBOutlet var filterTextField:UITextField!
var filterEmployeeListService: FilterEmployeeListService!
var employeeList = [Any]()
override func viewDidLoad() {
super.viewDidLoad()
/**
* Show NavigationBar
*/
self.navigationController?.navigationBar.isHidden = false
/**
* Set UITextField Border Color
*/
let myColor : UIColor = UIColor(colorLiteralRed: 24/255, green: 100/255, blue: 173/255, alpha: 1)
filterTextField.layer.borderColor = myColor.cgColor
filterTextField.layer.borderWidth = 1.0
filterTextField.layer.cornerRadius = 3.0
employeeListTableView.tableFooterView = UIView()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
/**
* Service Name
*/
self.navigationItem.title = "Employee List with Name"
}
@IBAction func filterClick(_ sender: UIButton) {
self.view.endEditing(true)
if((filterTextField.text?.characters.count)! > 0) {
employeeListWithFilter()
} else {
TGUtil.showAlertView("Sorry", message: "Please enter filter Name.")
self.employeeList.removeAll()
self.employeeListTableView.reloadData()
}
}
// MARK: - Employee List with filter Service
/**
* Call Employee List with filter Service
*/
func employeeListWithFilter() {
var response: FilterEmployeeListResponse!
self.setProgressIndicatorWithTitle("Loading...", andDetail: "")
progressIndicator.show(animated: true, whileExecuting: {() -> Void in
let request = FilterEmployeeListRequest()
request.name = self.filterTextField.text!
response = self.employeeList(withFilter: request)
}, completionBlock: {() -> Void in
self.employeeList.removeAll()
self.employeeList = response.employeeList
if(self.employeeList.count == 0) {
TGUtil.showAlertView("Sorry", message: "No found record!")
}
self.employeeListTableView.reloadData()
})
}
func employeeList(withFilter request: FilterEmployeeListRequest) -> FilterEmployeeListResponse {
if !(filterEmployeeListService != nil) {
filterEmployeeListService = FilterEmployeeListService.getInstance()
}
return filterEmployeeListService.employeeList(withFilter: request)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - UITextField Delegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true)
return false
}
// MARK: - Table Delegate
func numberOfSections(in aTableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return employeeList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell:UITableViewCell?
cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell?.selectionStyle = UITableViewCellSelectionStyle.none
let employee:Employee = employeeList[indexPath.row] as! Employee
cell?.textLabel?.text = employee.name
cell?.detailTextLabel?.text = employee.designation
cell?.textLabel?.textColor = UIColor(colorLiteralRed: 24/255, green: 100/255, blue: 173/255, alpha: 1)
cell?.detailTextLabel?.textColor = UIColor(colorLiteralRed: 125/255, green: 194/255, blue: 66/255, alpha: 1)
return cell!
}
}
|
apache-2.0
|
0845b82524907eccc9aa4c92a5287cea
| 35.36036 | 125 | 0.643211 | 5.248375 | false | false | false | false |
ninjaprox/TextContour
|
TextContourTests/TextContourTests.swift
|
1
|
1229
|
//
// TextContourTests.swift
// TextContourTests
//
// Created by Vinh Nguyen on 2/17/17.
// Copyright © 2017 Vinh Nguyen. All rights reserved.
//
import XCTest
@testable import TextContour
class TextContourTests: XCTestCase {
let fontSize: CGFloat = 40
let iosFilename = "contours-ios.json"
let webFilename = "contours-web.json"
var fontNames: [String]!
override func setUp() {
super.setUp()
fontNames = FontLoader().list()
}
override func tearDown() {
fontNames.removeAll()
fontNames = nil
super.tearDown()
}
func test_contours_ios() {
let contours = IOSDriver(fontNames: fontNames, fontSize: fontSize).contours()
if let data = try? JSONSerialization.data(withJSONObject: contours, options: .prettyPrinted) {
Writter().write(data, to: self.iosFilename)
}
XCTAssert(true)
}
func test_contours_web() {
let contours = WebDriver(fontNames: fontNames, fontSize: fontSize).contours()
if let data = try? JSONSerialization.data(withJSONObject: contours, options: .prettyPrinted) {
Writter().write(data, to: webFilename)
}
XCTAssert(true)
}
}
|
mit
|
82d0a41ae2a194cb5076efdd0a5dd02a
| 23.56 | 102 | 0.635179 | 4.263889 | false | true | false | false |
JGiola/swift-package-manager
|
Tests/UtilityTests/SimplePersistenceTests.swift
|
2
|
6369
|
/*
This source file is part of the Swift.org open source project
Copyright 2016 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import XCTest
import Basic
import TestSupport
import Utility
fileprivate class Foo: SimplePersistanceProtocol {
var int: Int
var path: AbsolutePath
let persistence: SimplePersistence
init(int: Int, path: AbsolutePath, fileSystem: FileSystem) {
self.int = int
self.path = path
self.persistence = SimplePersistence(
fileSystem: fileSystem,
schemaVersion: 1,
supportedSchemaVersions: [0],
statePath: AbsolutePath.root.appending(components: "subdir", "state.json")
)
}
func restore(from json: JSON) throws {
self.int = try json.get("int")
self.path = try AbsolutePath(json.get("path"))
}
func restore(from json: JSON, supportedSchemaVersion: Int) throws {
switch supportedSchemaVersion {
case 0:
self.int = try json.get("old_int")
self.path = try AbsolutePath(json.get("old_path"))
default:
fatalError()
}
}
func toJSON() -> JSON {
return JSON([
"int": int,
"path": path,
])
}
func save() throws {
try persistence.saveState(self)
}
func restore() throws -> Bool {
return try persistence.restoreState(self)
}
}
fileprivate enum Bar {
class V1: SimplePersistanceProtocol {
var int: Int
let persistence: SimplePersistence
init(int: Int, fileSystem: FileSystem) {
self.int = int
self.persistence = SimplePersistence(
fileSystem: fileSystem,
schemaVersion: 1,
statePath: AbsolutePath.root.appending(components: "subdir", "state.json")
)
}
func restore(from json: JSON) throws {
self.int = try json.get("int")
}
func toJSON() -> JSON {
return JSON([
"int": int,
])
}
}
class V2: SimplePersistanceProtocol {
var int: Int
var string: String
let persistence: SimplePersistence
init(int: Int, string: String, fileSystem: FileSystem) {
self.int = int
self.string = string
self.persistence = SimplePersistence(
fileSystem: fileSystem,
schemaVersion: 1,
statePath: AbsolutePath.root.appending(components: "subdir", "state.json")
)
}
func restore(from json: JSON) throws {
self.int = try json.get("int")
self.string = try json.get("string")
}
func toJSON() -> JSON {
return JSON([
"int": int,
"string": string
])
}
}
}
class SimplePersistenceTests: XCTestCase {
func testBasics() throws {
let fs = InMemoryFileSystem()
let stateFile = AbsolutePath.root.appending(components: "subdir", "state.json")
let foo = Foo(int: 1, path: AbsolutePath("/hello"), fileSystem: fs)
// Restoring right now should return false because state is not present.
XCTAssertFalse(try foo.restore())
// Save and check saved data.
try foo.save()
let json = try JSON(bytes: fs.readFileContents(stateFile))
XCTAssertEqual(1, try json.get("version"))
XCTAssertEqual(foo.toJSON(), try json.get("object"))
// Modify local state and restore.
foo.int = 5
XCTAssertTrue(try foo.restore())
XCTAssertEqual(foo.int, 1)
XCTAssertEqual(foo.path, AbsolutePath("/hello"))
// Modify state's schema version.
let newJSON = JSON(["version": 2])
try fs.writeFileContents(stateFile, bytes: newJSON.toBytes())
do {
_ = try foo.restore()
XCTFail()
} catch {
let error = String(describing: error)
XCTAssert(error.contains("unsupported schema version 2"), error)
}
}
func testBackwardsCompatibleStateFile() throws {
// Test that we don't overwrite the json in case we find keys we don't need.
let fs = InMemoryFileSystem()
let stateFile = AbsolutePath.root.appending(components: "subdir", "state.json")
// Create and save v2 object.
let v2 = Bar.V2(int: 100, string: "hello", fileSystem: fs)
try v2.persistence.saveState(v2)
// Restore v1 object from v2 file.
let v1 = Bar.V1(int: 1, fileSystem: fs)
XCTAssertEqual(v1.int, 1)
XCTAssertTrue(try v1.persistence.restoreState(v1))
XCTAssertEqual(v1.int, 100)
// Check state file still has the old "string" key.
let json = try JSON(bytes: fs.readFileContents(stateFile))
XCTAssertEqual("hello", try json.get("object").get("string"))
// Update a value in v1 object and save.
v1.int = 500
try v1.persistence.saveState(v1)
v2.string = ""
// Now restore v2 and expect string to be present as well as the updated int value.
XCTAssertTrue(try v2.persistence.restoreState(v2))
XCTAssertEqual(v2.int, 500)
XCTAssertEqual(v2.string, "hello")
}
func testCanLoadFromOldSchema() throws {
let fs = InMemoryFileSystem()
let stateFile = AbsolutePath.root.appending(components: "subdir", "state.json")
try fs.writeFileContents(stateFile) {
$0 <<< """
{
"version": 0,
"object": {
"old_path": "/oldpath",
"old_int": 4
}
}
"""
}
let foo = Foo(int: 1, path: AbsolutePath("/hello"), fileSystem: fs)
XCTAssertEqual(foo.path, AbsolutePath("/hello"))
XCTAssertEqual(foo.int, 1)
// Load from an older but supported schema state file.
XCTAssertTrue(try foo.restore())
XCTAssertEqual(foo.path, AbsolutePath("/oldpath"))
XCTAssertEqual(foo.int, 4)
}
}
|
apache-2.0
|
3b30f753d0f6bc133c2e4d94696c4709
| 29.768116 | 91 | 0.574973 | 4.559055 | false | false | false | false |
rcobelli/GameOfficials
|
Eureka-master/Source/Rows/PickerInlineRow.swift
|
1
|
3211
|
// PickerInlineRow.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
open class PickerInlineCell<T: Equatable> : Cell<T>, CellType {
required public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override func setup() {
super.setup()
accessoryType = .none
editingAccessoryType = .none
}
open override func update() {
super.update()
selectionStyle = row.isDisabled ? .none : .default
}
open override func didSelect() {
super.didSelect()
row.deselect()
}
}
//MARK: PickerInlineRow
open class _PickerInlineRow<T> : Row<PickerInlineCell<T>>, NoValueDisplayTextConformance where T: Equatable {
public typealias InlineRow = PickerRow<T>
open var options = [T]()
open var noValueDisplayText: String?
required public init(tag: String?) {
super.init(tag: tag)
}
}
/// A generic inline row where the user can pick an option from a picker view which shows and hides itself automatically
public final class PickerInlineRow<T> : _PickerInlineRow<T>, RowType, InlineRowType where T: Equatable {
required public init(tag: String?) {
super.init(tag: tag)
onExpandInlineRow { cell, row, _ in
let color = cell.detailTextLabel?.textColor
row.onCollapseInlineRow { cell, _, _ in
cell.detailTextLabel?.textColor = color
}
cell.detailTextLabel?.textColor = cell.tintColor
}
}
public override func customDidSelect() {
super.customDidSelect()
if !isDisabled {
toggleInlineRow()
}
}
public func setupInlineRow(_ inlineRow: InlineRow) {
inlineRow.options = self.options
inlineRow.displayValueFor = self.displayValueFor
}
}
|
mit
|
c182ba54b40504ca51dc40414f311d20
| 33.526882 | 120 | 0.678293 | 4.814093 | false | false | false | false |
paritoshmmmec/IBM-Ready-App-for-Healthcare
|
iOS/ReadyAppPT/DataSources/HealthKitManager.swift
|
2
|
32890
|
/*
Licensed Materials - Property of IBM
© Copyright IBM Corporation 2014, 2015. All Rights Reserved.
*/
import UIKit
import HealthKit
/**
Enum for Types of HealthData. Used internally.
- HeartRate:
- StepCount:
- BodyMass:
- ActiveEnergyBurned:
*/
private enum HealthDataType {
case HeartRate
case StepCount
case BodyMass
case ActiveEnergyBurned
}
/**
Enums used as keys for the HeartRateData dictionary
- Min: String key to access the minimum heart rate in a given time period
- Max: String key to access the maximum heart rate in a given time period
- Average: String key to access the maximum heart rate in a given time period
*/
enum HeartRateData: String {
case Min = "min"
case Max = "max"
case Average = "avg"
}
/**
Enums used as keys for the HeartRateData dictionary
- Start: String key to access the weight at the beginning of time period
- Current: String key to access the weight at the end of time period
*/
enum WeightInPoundsData: String {
case Start = "start"
case Current = "current"
}
/**
Used to process and return specific data points from Health Kit
*/
class HealthKitManager: NSObject {
var healthStore : HKHealthStore!
var shouldPopulateHealthKit : Bool = false
//Class variable that will return a singleton when requested
class var healthKitManager : HealthKitManager{
struct Singleton {
static let instance = HealthKitManager()
}
return Singleton.instance
}
/**
An override for the init method to insure the HKHealthStore is available
*/
override init() {
super.init()
healthStore = HKHealthStore()
}
/**
Populates HealthKit with data from the healthData.json file. This currently includes Heart Rate, Body Weight, Calories Burned, and Steps Taken data for 30 days previous to the current day.
:param: callback Callback function. This will be triggered when the last HealthKit value is saved and will progress the app to the Dashboard.
*/
func populateHealthKit(callback: (shouldProgress: Bool)->()) {
// Get JSON data from the file
let filePath = NSBundle.mainBundle().pathForResource("healthData", ofType: "json")
let data = NSData(contentsOfFile: filePath!)
var jsonResult = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableLeaves, error: nil) as! NSDictionary
var metrics = jsonResult["Metrics"] as! NSDictionary
// Populate heart rate data
var heartRateDict = metrics["HeartRate"] as! NSArray
var rateType: HKQuantityType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)
let heartRateBPM = HKUnit.countUnit().unitDividedByUnit(HKUnit.minuteUnit())
for heartRatePoint in heartRateDict {
var timeDiff = heartRatePoint["timeDiff"] as! String
var heartRateValue = heartRatePoint["value"] as! String
var timeDiffDouble = (timeDiff as NSString).doubleValue
var heartRateDouble = (heartRateValue as NSString).doubleValue
let rateQuantity = HKQuantity(unit: heartRateBPM, doubleValue: heartRateDouble)
var date: NSDate = NSDate()
date = date.dateByAddingTimeInterval(timeDiffDouble / -1000)
let rateSample = HKQuantitySample(type: rateType, quantity: rateQuantity, startDate: date, endDate: date)
healthStore.saveObject(rateSample, withCompletion: {(success:Bool, error: NSError!) -> Void in
//println("healthkit save heart rate object = \(success) error = \(error)")
})
}
// Populate body weight data
var bodyWeightDict = metrics["BodyWeight"] as! NSArray
rateType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass)
for bodyWeightPoint in bodyWeightDict {
var timeDiffString = bodyWeightPoint["timeDiff"] as! String
var bodyWeightString = bodyWeightPoint["value"] as! String
var timeDiff = (timeDiffString as NSString).doubleValue
var bodyWeight = (bodyWeightString as NSString).doubleValue
let rateQuantity = HKQuantity(unit: HKUnit.poundUnit(), doubleValue: bodyWeight)
var date: NSDate = NSDate()
date = date.dateByAddingTimeInterval(timeDiff / -1000)
let rateSample = HKQuantitySample(type: rateType, quantity: rateQuantity, startDate: date, endDate: date)
healthStore.saveObject(rateSample, withCompletion: {(success:Bool, error: NSError!) -> Void in
//println("healthkit save body weight object = \(success) error = \(error)")
})
}
// Populate calories data
var caloriesDict = metrics["Calories"] as! NSArray
rateType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierActiveEnergyBurned)
for caloriesPoint in caloriesDict {
var timeDiffString = caloriesPoint["timeDiff"] as! String
var caloriesString = caloriesPoint["value"] as! String
var timeDiff = (timeDiffString as NSString).doubleValue
var calories = (caloriesString as NSString).doubleValue
let rateQuantity = HKQuantity(unit: HKUnit.kilocalorieUnit() , doubleValue: calories)
var date: NSDate = NSDate()
date = date.dateByAddingTimeInterval(timeDiff / -1000)
let rateSample = HKQuantitySample(type: rateType, quantity: rateQuantity, startDate: date, endDate: date)
healthStore.saveObject(rateSample, withCompletion: {(success:Bool, error: NSError!) -> Void in
//println("healthkit save calories object = \(success) error = \(error)")
})
}
// Populate steps data
var stepsDict = metrics["Steps"] as! NSArray
rateType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount)
var totalStepsPoints = stepsDict.count
var pointsCount = 0
for stepsPoint in stepsDict {
var timeDiffString = stepsPoint["timeDiff"] as! String
var stepsString = stepsPoint["value"] as! String
var timeDiff = (timeDiffString as NSString).doubleValue
var steps = (stepsString as NSString).doubleValue
let rateQuantity = HKQuantity(unit: HKUnit.countUnit(), doubleValue: steps)
var date: NSDate = NSDate()
date = date.dateByAddingTimeInterval(timeDiff / -1000)
let rateSample = HKQuantitySample(type: rateType, quantity: rateQuantity, startDate: date, endDate: date)
healthStore.saveObject(rateSample, withCompletion: {(success:Bool, error: NSError!) -> Void in
pointsCount++
if (pointsCount == totalStepsPoints) {
callback(shouldProgress: true)
}
//println("healthkit save steps object = \(success) error = \(error)")
})
}
}
/**
Builds the set NSet of HKObjectTypes that are read from HealthKit
:returns: NSet of HKObjectTypes
*/
func getReadTypes() -> NSSet {
//HeartRate
let heartRateType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)
//StepCount
let stepCountType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount)
//bodyMass
let bodyMassType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass)
//EnergyBurned
let energyBurnedType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierActiveEnergyBurned)
//Sex
let sexType = HKCharacteristicType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierBiologicalSex)
return NSSet(objects:heartRateType, stepCountType, bodyMassType, energyBurnedType, sexType)
}
/**
Builds the set NSet of HKObjectTypes that are written to HealthKit
:returns: NSet of HKObjectTypes
*/
func getWriteTypes() -> NSSet {
//HeartRate
let heartRateType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)
//StepCount
let stepCountType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount)
//bodyMass
let bodyMassType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass)
//EnergyBurned
let energyBurnedType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierActiveEnergyBurned)
return NSSet(objects:heartRateType, stepCountType, bodyMassType, energyBurnedType)
}
/**
Used to call the HealthKit permissions alert
:param: callback callback function
*/
func getPermissionsForHealthKit(callback: (shouldProgress: Bool)->()){
let readTypes = self.getReadTypes()
let writeTypes = self.getWriteTypes()
if HKHealthStore.isHealthDataAvailable(){
healthStore.requestAuthorizationToShareTypes(writeTypes as Set<NSObject>, readTypes: readTypes as Set<NSObject>, completion: { (done, err) in
if (self.shouldPopulateHealthKit) {
self.populateHealthKit(callback)
} else {
callback(shouldProgress: done)
}
})
}
}
func getHeartInRange() {
var type: HKQuantityType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)
}
/**
This method is bassed a callback which will be called with a dictionary containing the min, max, and average heart rates as well as an error for accessing HealthKit
:param: startDate The beginning of the time period to query Health Kit
:param: callback callback function
*/
func getHeartRateData(startDate: NSDate, callback: ([String: Double]!, NSError!) -> ()){
let readTypes = self.getReadTypes()
let writeTypes = self.getWriteTypes()
if HKHealthStore.isHealthDataAvailable(){
healthStore.requestAuthorizationToShareTypes(writeTypes as Set<NSObject>, readTypes: readTypes as Set<NSObject>, completion: { (success, error) in
if(success){
let timeSortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: true)
let endDate = NSDate()
let predicate = HKQuery.predicateForSamplesWithStartDate(startDate, endDate: endDate, options: HKQueryOptions.None)
let query = HKSampleQuery(sampleType: self.getSampleTypeForEnum(HealthDataType.HeartRate), predicate: predicate, limit: Int.max, sortDescriptors: [timeSortDescriptor]) { (query, results, error) in
if(results == nil){
println("ERROR in getHeartRateData - data was nil")
return
}
var data : [String : Double] = [:]
var max = -9999.9
var min = 9999.9
var total = 0.0
let quantitySamples = results as! [HKQuantitySample]
for quantitySample in quantitySamples {
var value = quantitySample.quantity.doubleValueForUnit(HKUnit.countUnit().unitDividedByUnit(HKUnit.minuteUnit()))
if max < value {
max = value
}
if min > value {
min = value
}
total += value
}
var average = 0.0
if quantitySamples.count > 0 {
average = total / Double(quantitySamples.count)
}
data[HeartRateData.Min.rawValue] = min
data[HeartRateData.Max.rawValue] = max
data[HeartRateData.Average.rawValue] = average
if min == 9999.9 && max == -9999.9 && average == 0{
callback(nil, error)
}else{
callback(data, error)
}
}
self.healthStore.executeQuery(query)
}
})
}
}
/**
This method is bassed a callback which will be called with a Double value of the total steps as well as an error for accessing HealthKit
:param: startDate The beginning of the time period to query Health Kit
:param: callback callback function
*/
func getSteps(startDate: NSDate, callback: (Double, NSError!) -> ()){
let readTypes = self.getReadTypes()
let writeTypes = self.getWriteTypes()
if HKHealthStore.isHealthDataAvailable(){
healthStore.requestAuthorizationToShareTypes(writeTypes as Set<NSObject>, readTypes: readTypes as Set<NSObject>, completion: { (success, error) in
if(success){
let timeSortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: true)
let endDate = NSDate()
let predicate = HKQuery.predicateForSamplesWithStartDate(startDate, endDate: endDate, options: HKQueryOptions.None)
let query = HKSampleQuery(sampleType: self.getSampleTypeForEnum(HealthDataType.StepCount), predicate: predicate, limit: Int.max, sortDescriptors: [timeSortDescriptor]) { (query, results, error) in
var count = 0.0
if let tempResults = results {
let quantitySamples = tempResults as! [HKQuantitySample]
for quantitySample in quantitySamples {
count += quantitySample.quantity.doubleValueForUnit(HKUnit.countUnit())
}
callback(count, error)
}
}
self.healthStore.executeQuery(query)
}
})
}
}
/**
This method is bassed a callback which will be called with a dictionary containing the start and current weight as well as an error for accessing HealthKit
:param: startDate The beginning of the time period to query Health Kit
:param: callback callback function
*/
func getWeightInPoundsData(startDate: NSDate, callback: ([String: Double]!, NSError!) -> ()){
let readTypes = self.getReadTypes()
let writeTypes = self.getWriteTypes()
if HKHealthStore.isHealthDataAvailable(){
healthStore.requestAuthorizationToShareTypes(writeTypes as Set<NSObject>, readTypes: readTypes as Set<NSObject>, completion: { (success, error) in
if(success){
let timeSortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: true)
let endDate = NSDate()
let predicate = HKQuery.predicateForSamplesWithStartDate(startDate, endDate: endDate, options: HKQueryOptions.None)
let query = HKSampleQuery(sampleType: self.getSampleTypeForEnum(HealthDataType.BodyMass), predicate: predicate, limit: Int.max, sortDescriptors: [timeSortDescriptor]) { (query, results, error) in
var data : [String : Double] = [:]
if let quantitySamples = results as? [HKQuantitySample] {
if quantitySamples.count > 0 {
data[WeightInPoundsData.Start.rawValue] = quantitySamples.first?.quantity.doubleValueForUnit(HKUnit.poundUnit())
data[WeightInPoundsData.Current.rawValue] = quantitySamples.last?.quantity.doubleValueForUnit(HKUnit.poundUnit())
}
if data[WeightInPoundsData.Start.rawValue] == nil && data[WeightInPoundsData.Current.rawValue] == nil{
callback(nil, error)
}else{
callback(data, error)
}
} else {
callback(nil, error)
}
}
self.healthStore.executeQuery(query)
}
})
}
}
/**
This method is bassed a callback which will be called with a Double value of the total calories as well as an error for accessing HealthKit
:param: startDate The beginning of the time period to query Health Kit
:param: callback callback function
*/
func getCaloriesBurned(startDate: NSDate, callback: (Double, NSError!) -> ()){
let readTypes = self.getReadTypes()
let writeTypes = self.getWriteTypes()
if HKHealthStore.isHealthDataAvailable(){
healthStore.requestAuthorizationToShareTypes(writeTypes as Set<NSObject>, readTypes: readTypes as Set<NSObject>, completion: { (success, error) in
if(success){
let timeSortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: true)
let endDate = NSDate()
let predicate = HKQuery.predicateForSamplesWithStartDate(startDate, endDate: endDate, options: HKQueryOptions.None)
let query = HKSampleQuery(sampleType: self.getSampleTypeForEnum(HealthDataType.ActiveEnergyBurned), predicate: predicate, limit: Int.max, sortDescriptors: [timeSortDescriptor]) { (query, results, error) in
if (results != nil){
var count = 0.0
let quantitySamples = results as! [HKQuantitySample]
for quantitySample in quantitySamples {
count += quantitySample.quantity.doubleValueForUnit(HKUnit.jouleUnit())
}
callback(count, error)
}else{
callback(0, error)
}
}
self.healthStore.executeQuery(query)
}
})
}
}
/**
This method get the entered Sex of the user from healthkit to determine which vector graphic to display on the pain location page.
:returns: A Boolean which is true if user is Male or Not Set, false if Female
*/
func isMale() -> Bool {
var sex: HKBiologicalSexObject = healthStore.biologicalSexWithError(nil)!
if sex.biologicalSex == HKBiologicalSex.Female {
return false
} else {
return true
}
}
/**
Internal function to get a specific HKSampleType
:param: type Class enum
:returns: The HKSampleType
*/
private func getSampleTypeForEnum(type: HealthDataType) -> HKSampleType {
switch(type){
case HealthDataType.HeartRate:
return HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)
case HealthDataType.StepCount:
return HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount)
case HealthDataType.BodyMass:
return HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass)
case HealthDataType.ActiveEnergyBurned:
return HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierActiveEnergyBurned)
default:
return HKSampleType()
}
}
// MARK: HealthKit collection queries
/**
Method for a collection of HealthKit data that uses a Sum result
:param: start starting date range
:param: end ending date range
:param: interval date component representing how to separate data
:param: type type of HealthKit data to gather
:param: callback callback to report results to
*/
func getSumDataInRange(start: NSDate, end: NSDate, interval: NSDateComponents, type: HKQuantityType, callback: (String) -> ()) {
var jsonObject: [AnyObject] = [AnyObject]()
var xValue: Int = 1
var predicate = HKQuery.predicateForSamplesWithStartDate(start, endDate: end, options: HKQueryOptions.StrictEndDate)
var query = HKStatisticsCollectionQuery(quantityType: type, quantitySamplePredicate: predicate, options: HKStatisticsOptions.CumulativeSum, anchorDate: start, intervalComponents: interval)
query.initialResultsHandler = { (statsQuery: HKStatisticsCollectionQuery!, collection: HKStatisticsCollection!, error: NSError!) in
if collection != nil {
collection.enumerateStatisticsFromDate(start, toDate: end, withBlock: { (result, stop) in
if let sum: HKQuantity = result.sumQuantity() {
var sumUnit = ""
if type == self.getSampleTypeForEnum(HealthDataType.StepCount) as! HKQuantityType {
var temp = sum.doubleValueForUnit(HKUnit.countUnit())
temp = round(temp)
jsonObject.append(["x":xValue, "y":temp])
} else {
var temp = sum.doubleValueForUnit(HKUnit.jouleUnit())
temp = round(temp)
sumUnit = Utils.getLocalizedEnergy(temp)
jsonObject.append(["x":xValue, "y":sumUnit])
}
} else {
jsonObject.append(["x":xValue, "y":0])
}
xValue++
})
callback(Utils.JSONStringify(jsonObject, prettyPrinted: false))
}
}
HealthKitManager.healthKitManager.healthStore.executeQuery(query)
}
/**
Method for a collection of HealthKit data that uses a Average result
:param: start starting date range
:param: end ending date range
:param: interval date component representing how to separate data
:param: type type of HealthKit data to gather
:param: callback callback to report results to
*/
func getAverageDataInRange(start: NSDate, end: NSDate, interval: NSDateComponents, type: HKQuantityType, callback: (String) -> ()) {
var jsonObject: [AnyObject] = [AnyObject]()
var xValue: Int = 1
var predicate = HKQuery.predicateForSamplesWithStartDate(start, endDate: end, options: HKQueryOptions.StrictEndDate)
var query = HKStatisticsCollectionQuery(quantityType: type, quantitySamplePredicate: predicate, options: HKStatisticsOptions.DiscreteAverage, anchorDate: start, intervalComponents: interval)
query.initialResultsHandler = { (statsQuery: HKStatisticsCollectionQuery!, collection: HKStatisticsCollection!, error: NSError!) in
if collection != nil {
collection.enumerateStatisticsFromDate(start, toDate: end, withBlock: { (result, stop) in
if let avr: HKQuantity = result.averageQuantity() {
var avrUnit = ""
if type == self.getSampleTypeForEnum(HealthDataType.BodyMass) as! HKQuantityType {
var temp = avr.doubleValueForUnit(HKUnit.poundUnit())
temp = round(temp)
avrUnit = Utils.getLocalizedWeight(temp)
jsonObject.append(["x":xValue, "y":avrUnit])
} else {
var temp = avr.doubleValueForUnit(HKUnit.countUnit().unitDividedByUnit(HKUnit.minuteUnit()))
temp = round(temp)
jsonObject.append(["x":xValue, "y":temp])
}
} else {
jsonObject.append(["x":xValue, "y":0])
}
xValue++
})
callback(Utils.JSONStringify(jsonObject, prettyPrinted: false))
}
}
HealthKitManager.healthKitManager.healthStore.executeQuery(query)
}
/**
Method for deleting all the HealthKit data created from the app
:param: callback callback to do something on completion
*/
func deleteHealthKitData(callback: ()->()){
self.deleteHeartRates({
self.deleteSteps({
self.deleteWeightData({
self.deleteCaloriesBurned({
callback()
})
})
})
})
}
/**
Method for deleting the Heart Rate data created from the app
:param: callback callback to do something on completion
*/
func deleteHeartRates(callback: ()->()){
let readTypes = self.getReadTypes()
let writeTypes = self.getWriteTypes()
if HKHealthStore.isHealthDataAvailable(){
healthStore.requestAuthorizationToShareTypes(writeTypes as Set<NSObject>, readTypes: readTypes as Set<NSObject>, completion: { (success, error) in
if(success){
let predicate = HKQuery.predicateForObjectsFromSource(HKSource.defaultSource())
let query = HKSampleQuery(sampleType: self.getSampleTypeForEnum(HealthDataType.HeartRate), predicate: predicate, limit: Int.max, sortDescriptors: nil) { (query, results, error) in
let quantitySamples = results as! [HKQuantitySample]
if quantitySamples.count > 0{
for (index, quantitySample) in enumerate(quantitySamples) {
self.healthStore.deleteObject(quantitySample, withCompletion: { (success, error) in
if index == quantitySamples.count-1{
callback()
}
})
}
}else{
callback()
}
}
self.healthStore.executeQuery(query)
}
})
}
}
/**
Method for deleting the Steps data created from the app
:param: callback callback to do something on completion
*/
func deleteSteps(callback: ()->()){
let readTypes = self.getReadTypes()
let writeTypes = self.getWriteTypes()
if HKHealthStore.isHealthDataAvailable(){
healthStore.requestAuthorizationToShareTypes(writeTypes as Set<NSObject>, readTypes: readTypes as Set<NSObject>, completion: { (success, error) in
if(success){
let predicate = HKQuery.predicateForObjectsFromSource(HKSource.defaultSource())
let query = HKSampleQuery(sampleType: self.getSampleTypeForEnum(HealthDataType.StepCount), predicate: predicate, limit: Int.max, sortDescriptors: nil) { (query, results, error) in
let quantitySamples = results as! [HKQuantitySample]
if quantitySamples.count > 0{
for (index, quantitySample) in enumerate(quantitySamples) {
self.healthStore.deleteObject(quantitySample, withCompletion: { (success, error) in
if index == quantitySamples.count-1{
callback()
}
})
}
}else{
callback()
}
}
self.healthStore.executeQuery(query)
}
})
}
}
/**
Method for deleting the Weight data created from the app
:param: callback callback to do something on completion
*/
func deleteWeightData(callback: ()->()){
let readTypes = self.getReadTypes()
let writeTypes = self.getWriteTypes()
if HKHealthStore.isHealthDataAvailable(){
healthStore.requestAuthorizationToShareTypes(writeTypes as Set<NSObject>, readTypes: readTypes as Set<NSObject>, completion: { (success, error) in
if(success){
let predicate = HKQuery.predicateForObjectsFromSource(HKSource.defaultSource())
let query = HKSampleQuery(sampleType: self.getSampleTypeForEnum(HealthDataType.BodyMass), predicate: predicate, limit: Int.max, sortDescriptors: nil) { (query, results, error) in
let quantitySamples = results as! [HKQuantitySample]
if quantitySamples.count > 0{
for (index, quantitySample) in enumerate(quantitySamples) {
self.healthStore.deleteObject(quantitySample, withCompletion: { (success, error) in
if index == quantitySamples.count-1{
callback()
}
})
}
}else{
callback()
}
}
self.healthStore.executeQuery(query)
}
})
}
}
/**
Method for deleting the Calories Burned data created from the app
:param: callback callback to do something on completion
*/
func deleteCaloriesBurned(callback: ()->()){
let readTypes = self.getReadTypes()
let writeTypes = self.getWriteTypes()
if HKHealthStore.isHealthDataAvailable(){
healthStore.requestAuthorizationToShareTypes(writeTypes as Set<NSObject>, readTypes: readTypes as Set<NSObject>, completion: { (success, error) in
if(success){
let predicate = HKQuery.predicateForObjectsFromSource(HKSource.defaultSource())
let query = HKSampleQuery(sampleType: self.getSampleTypeForEnum(HealthDataType.ActiveEnergyBurned), predicate: predicate, limit: Int.max, sortDescriptors: nil) { (query, results, error) in
let quantitySamples = results as! [HKQuantitySample]
if quantitySamples.count > 0{
for (index, quantitySample) in enumerate(quantitySamples) {
self.healthStore.deleteObject(quantitySample, withCompletion: { (success, error) in
if index == quantitySamples.count-1{
callback()
}
})
}
}else{
callback()
}
}
self.healthStore.executeQuery(query)
}
})
}
}
}
|
epl-1.0
|
5e381c3892f1622b349719d57581210f
| 44.742698 | 225 | 0.563289 | 5.891974 | false | false | false | false |
mshhmzh/firefox-ios
|
Sync/SyncStateMachine.swift
|
5
|
36495
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import Account
import XCGLogger
import Deferred
private let log = Logger.syncLogger
private let StorageVersionCurrent = 5
// Names of collections for which a synchronizer is implemented locally.
private let LocalEngines: [String] = [
"bookmarks",
"clients",
"history",
"passwords",
"tabs",
]
// Names of collections which will appear in a default meta/global produced locally.
// Map collection name to engine version. See http://docs.services.mozilla.com/sync/objectformats.html.
private let DefaultEngines: [String: Int] = [
"bookmarks": BookmarksStorageVersion,
"clients": ClientsStorageVersion,
"history": HistoryStorageVersion,
"passwords": PasswordsStorageVersion,
"tabs": TabsStorageVersion,
// We opt-in to syncing collections we don't know about, since no client offers to sync non-enabled,
// non-declined engines yet. See Bug 969669.
"forms": 1,
"addons": 1,
"prefs": 2,
]
// Names of collections which will appear as declined in a default
// meta/global produced locally.
private let DefaultDeclined: [String] = [String]()
// public for testing.
public func createMetaGlobalWithEngineConfiguration(engineConfiguration: EngineConfiguration) -> MetaGlobal {
var engines: [String: EngineMeta] = [:]
for engine in engineConfiguration.enabled {
// We take this device's version, or, if we don't know the correct version, 0. Another client should recognize
// the engine, see an old version, wipe and start again.
// TODO: this client does not yet do this wipe-and-update itself!
let version = DefaultEngines[engine] ?? 0
engines[engine] = EngineMeta(version: version, syncID: Bytes.generateGUID())
}
return MetaGlobal(syncID: Bytes.generateGUID(), storageVersion: StorageVersionCurrent, engines: engines, declined: engineConfiguration.declined)
}
public func createMetaGlobal() -> MetaGlobal {
let engineConfiguration = EngineConfiguration(enabled: Array(DefaultEngines.keys), declined: DefaultDeclined)
return createMetaGlobalWithEngineConfiguration(engineConfiguration)
}
public typealias TokenSource = () -> Deferred<Maybe<TokenServerToken>>
public typealias ReadyDeferred = Deferred<Maybe<Ready>>
// See docs in docs/sync.md.
// You might be wondering why this doesn't have a Sync15StorageClient like FxALoginStateMachine
// does. Well, such a client is pinned to a particular server, and this state machine must
// acknowledge that a Sync client occasionally must migrate between two servers, preserving
// some state from the last.
// The resultant 'Ready' will be able to provide a suitably initialized storage client.
public class SyncStateMachine {
// The keys are used as a set, to prevent cycles in the state machine.
var stateLabelsSeen = [SyncStateLabel: Bool]()
var stateLabelSequence = [SyncStateLabel]()
let scratchpadPrefs: Prefs
public init(prefs: Prefs) {
self.scratchpadPrefs = prefs.branch("scratchpad")
}
public class func clearStateFromPrefs(prefs: Prefs) {
log.debug("Clearing all Sync prefs.")
Scratchpad.clearFromPrefs(prefs.branch("scratchpad")) // XXX this is convoluted.
prefs.clearAll()
}
private func advanceFromState(state: SyncState) -> ReadyDeferred {
log.info("advanceFromState: \(state.label)")
// Record visibility before taking any action.
let labelAlreadySeen = self.stateLabelsSeen.updateValue(true, forKey: state.label) != nil
stateLabelSequence.append(state.label)
if let ready = state as? Ready {
// Sweet, we made it!
return deferMaybe(ready)
}
// Cycles are not necessarily a problem, but seeing the same (recoverable) error condition is a problem.
if state is RecoverableSyncState && labelAlreadySeen {
return deferMaybe(StateMachineCycleError())
}
return state.advance() >>== self.advanceFromState
}
public func toReady(authState: SyncAuthState) -> ReadyDeferred {
let token = authState.token(NSDate.now(), canBeExpired: false)
return chainDeferred(token, f: { (token, kB) in
log.debug("Got token from auth state.")
if Logger.logPII {
log.debug("Server is \(token.api_endpoint).")
}
let prior = Scratchpad.restoreFromPrefs(self.scratchpadPrefs, syncKeyBundle: KeyBundle.fromKB(kB))
if prior == nil {
log.info("No persisted Sync state. Starting over.")
}
let scratchpad = prior ?? Scratchpad(b: KeyBundle.fromKB(kB), persistingTo: self.scratchpadPrefs)
log.info("Advancing to InitialWithLiveToken.")
let state = InitialWithLiveToken(scratchpad: scratchpad, token: token)
// Start with fresh visibility data.
self.stateLabelsSeen = [:]
self.stateLabelSequence = []
return self.advanceFromState(state)
})
}
}
public enum SyncStateLabel: String {
case Stub = "STUB" // For 'abstract' base classes.
case InitialWithExpiredToken = "initialWithExpiredToken"
case InitialWithExpiredTokenAndInfo = "initialWithExpiredTokenAndInfo"
case InitialWithLiveToken = "initialWithLiveToken"
case InitialWithLiveTokenAndInfo = "initialWithLiveTokenAndInfo"
case ResolveMetaGlobalVersion = "resolveMetaGlobalVersion"
case ResolveMetaGlobalContent = "resolveMetaGlobalContent"
case NewMetaGlobal = "newMetaGlobal"
case HasMetaGlobal = "hasMetaGlobal"
case NeedsFreshCryptoKeys = "needsFreshCryptoKeys"
case HasFreshCryptoKeys = "hasFreshCryptoKeys"
case Ready = "ready"
case FreshStartRequired = "freshStartRequired" // Go around again... once only, perhaps.
case ServerConfigurationRequired = "serverConfigurationRequired"
case ChangedServer = "changedServer"
case MissingMetaGlobal = "missingMetaGlobal"
case MissingCryptoKeys = "missingCryptoKeys"
case MalformedCryptoKeys = "malformedCryptoKeys"
case SyncIDChanged = "syncIDChanged"
case RemoteUpgradeRequired = "remoteUpgradeRequired"
case ClientUpgradeRequired = "clientUpgradeRequired"
static let allValues: [SyncStateLabel] = [
InitialWithExpiredToken,
InitialWithExpiredTokenAndInfo,
InitialWithLiveToken,
InitialWithLiveTokenAndInfo,
ResolveMetaGlobalVersion,
ResolveMetaGlobalContent,
NewMetaGlobal,
HasMetaGlobal,
NeedsFreshCryptoKeys,
HasFreshCryptoKeys,
Ready,
FreshStartRequired,
ServerConfigurationRequired,
ChangedServer,
MissingMetaGlobal,
MissingCryptoKeys,
MalformedCryptoKeys,
SyncIDChanged,
RemoteUpgradeRequired,
ClientUpgradeRequired,
]
}
/**
* States in this state machine all implement SyncState.
*
* States are either successful main-flow states, or (recoverable) error states.
* Errors that aren't recoverable are simply errors.
* Main-flow states flow one to one.
*
* (Terminal failure states might be introduced at some point.)
*
* Multiple error states (but typically only one) can arise from each main state transition.
* For example, parsing meta/global can result in a number of different non-routine situations.
*
* For these reasons, and the lack of useful ADTs in Swift, we model the main flow as
* the success branch of a Result, and the recovery flows as a part of the failure branch.
*
* We could just as easily use a ternary Either-style operator, but thanks to Swift's
* optional-cast-let it's no saving to do so.
*
* Because of the lack of type system support, all RecoverableSyncStates must have the same
* signature. That signature implies a possibly multi-state transition; individual states
* will have richer type signatures.
*/
public protocol SyncState {
var label: SyncStateLabel { get }
func advance() -> Deferred<Maybe<SyncState>>
}
/*
* Base classes to avoid repeating initializers all over the place.
*/
public class BaseSyncState: SyncState {
public var label: SyncStateLabel { return SyncStateLabel.Stub }
public let client: Sync15StorageClient!
let token: TokenServerToken // Maybe expired.
var scratchpad: Scratchpad
// TODO: 304 for i/c.
public func getInfoCollections() -> Deferred<Maybe<InfoCollections>> {
return chain(self.client.getInfoCollections(), f: {
return $0.value
})
}
public init(client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken) {
self.scratchpad = scratchpad
self.token = token
self.client = client
log.info("Inited \(self.label.rawValue)")
}
public func synchronizer<T: Synchronizer>(synchronizerClass: T.Type, delegate: SyncDelegate, prefs: Prefs) -> T {
return T(scratchpad: self.scratchpad, delegate: delegate, basePrefs: prefs)
}
// This isn't a convenience initializer 'cos subclasses can't call convenience initializers.
public init(scratchpad: Scratchpad, token: TokenServerToken) {
let workQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
let resultQueue = dispatch_get_main_queue()
let backoff = scratchpad.backoffStorage
let client = Sync15StorageClient(token: token, workQueue: workQueue, resultQueue: resultQueue, backoff: backoff)
self.scratchpad = scratchpad
self.token = token
self.client = client
log.info("Inited \(self.label.rawValue)")
}
public func advance() -> Deferred<Maybe<SyncState>> {
return deferMaybe(StubStateError())
}
}
public class BaseSyncStateWithInfo: BaseSyncState {
public let info: InfoCollections
init(client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken, info: InfoCollections) {
self.info = info
super.init(client: client, scratchpad: scratchpad, token: token)
}
init(scratchpad: Scratchpad, token: TokenServerToken, info: InfoCollections) {
self.info = info
super.init(scratchpad: scratchpad, token: token)
}
}
/*
* Error types.
*/
public protocol SyncError: MaybeErrorType {}
public class UnknownError: SyncError {
public var description: String {
return "Unknown error."
}
}
public class StateMachineCycleError: SyncError {
public var description: String {
return "The Sync state machine encountered a cycle. This is a coding error."
}
}
public class CouldNotFetchMetaGlobalError: SyncError {
public var description: String {
return "Could not fetch meta/global."
}
}
public class CouldNotFetchKeysError: SyncError {
public var description: String {
return "Could not fetch crypto/keys."
}
}
public class StubStateError: SyncError {
public var description: String {
return "Unexpectedly reached a stub state. This is a coding error."
}
}
public class ClientUpgradeRequiredError: SyncError {
let targetStorageVersion: Int
public init(target: Int) {
self.targetStorageVersion = target
}
public var description: String {
return "Client upgrade required to work with storage version \(self.targetStorageVersion)."
}
}
public class InvalidKeysError: SyncError {
let keys: Keys
public init(_ keys: Keys) {
self.keys = keys
}
public var description: String {
return "Downloaded crypto/keys, but couldn't parse them."
}
}
/**
* Error states. These are errors that can be recovered from by taking actions. We use RecoverableSyncState as a
* sentinel: if we see the same recoverable state twice, we bail out and complain that we've seen a cycle. (Seeing
* some states -- principally initial states -- twice is fine.)
*/
public protocol RecoverableSyncState: SyncState {
}
/**
* Recovery: discard our local timestamps and sync states; discard caches.
* Be prepared to handle a conflict between our selected engines and the new
* server's meta/global; if an engine is selected locally but not declined
* remotely, then we'll need to upload a new meta/global and sync that engine.
*/
public class ChangedServerError: RecoverableSyncState {
public var label: SyncStateLabel { return SyncStateLabel.ChangedServer }
let newToken: TokenServerToken
let newScratchpad: Scratchpad
public init(scratchpad: Scratchpad, token: TokenServerToken) {
self.newToken = token
self.newScratchpad = Scratchpad(b: scratchpad.syncKeyBundle, persistingTo: scratchpad.prefs)
}
public func advance() -> Deferred<Maybe<SyncState>> {
// TODO: mutate local storage to allow for a fresh start.
let state = InitialWithLiveToken(scratchpad: newScratchpad.checkpoint(), token: newToken)
return deferMaybe(state)
}
}
/**
* Recovery: same as for changed server, but no need to upload a new meta/global.
*/
public class SyncIDChangedError: RecoverableSyncState {
public var label: SyncStateLabel { return SyncStateLabel.SyncIDChanged }
private let previousState: BaseSyncStateWithInfo
private let newMetaGlobal: Fetched<MetaGlobal>
public init(previousState: BaseSyncStateWithInfo, newMetaGlobal: Fetched<MetaGlobal>) {
self.previousState = previousState
self.newMetaGlobal = newMetaGlobal
}
public func advance() -> Deferred<Maybe<SyncState>> {
// TODO: mutate local storage to allow for a fresh start.
let s = self.previousState.scratchpad.evolve().setGlobal(self.newMetaGlobal).setKeys(nil).build().checkpoint()
let state = HasMetaGlobal(client: self.previousState.client, scratchpad: s, token: self.previousState.token, info: self.previousState.info)
return deferMaybe(state)
}
}
/**
* Recovery: configure the server.
*/
public class ServerConfigurationRequiredError: RecoverableSyncState {
public var label: SyncStateLabel { return SyncStateLabel.ServerConfigurationRequired }
private let previousState: BaseSyncStateWithInfo
public init(previousState: BaseSyncStateWithInfo) {
self.previousState = previousState
}
public func advance() -> Deferred<Maybe<SyncState>> {
let client = self.previousState.client
let s = self.previousState.scratchpad.evolve()
.setGlobal(nil)
.addLocalCommandsFromKeys(nil)
.setKeys(nil)
.build().checkpoint()
// Upload a new meta/global ...
let metaGlobal: MetaGlobal
if let oldEngineConfiguration = s.engineConfiguration {
metaGlobal = createMetaGlobalWithEngineConfiguration(oldEngineConfiguration)
} else {
metaGlobal = createMetaGlobal()
}
return client.uploadMetaGlobal(metaGlobal, ifUnmodifiedSince: nil)
// ... and a new crypto/keys.
>>> { return client.uploadCryptoKeys(Keys.random(), withSyncKeyBundle: s.syncKeyBundle, ifUnmodifiedSince: nil) }
>>> { return deferMaybe(InitialWithLiveToken(client: client, scratchpad: s, token: self.previousState.token)) }
}
}
/**
* Recovery: wipe the server (perhaps unnecessarily) and proceed to configure the server.
*/
public class FreshStartRequiredError: RecoverableSyncState {
public var label: SyncStateLabel { return SyncStateLabel.FreshStartRequired }
private let previousState: BaseSyncStateWithInfo
public init(previousState: BaseSyncStateWithInfo) {
self.previousState = previousState
}
public func advance() -> Deferred<Maybe<SyncState>> {
let client = self.previousState.client
return client.wipeStorage()
>>> { return deferMaybe(ServerConfigurationRequiredError(previousState: self.previousState)) }
}
}
public class MissingMetaGlobalError: RecoverableSyncState {
public var label: SyncStateLabel { return SyncStateLabel.MissingMetaGlobal }
private let previousState: BaseSyncStateWithInfo
public init(previousState: BaseSyncStateWithInfo) {
self.previousState = previousState
}
public func advance() -> Deferred<Maybe<SyncState>> {
return deferMaybe(FreshStartRequiredError(previousState: self.previousState))
}
}
public class MissingCryptoKeysError: RecoverableSyncState {
public var label: SyncStateLabel { return SyncStateLabel.MissingCryptoKeys }
private let previousState: BaseSyncStateWithInfo
public init(previousState: BaseSyncStateWithInfo) {
self.previousState = previousState
}
public func advance() -> Deferred<Maybe<SyncState>> {
return deferMaybe(FreshStartRequiredError(previousState: self.previousState))
}
}
public class RemoteUpgradeRequired: RecoverableSyncState {
public var label: SyncStateLabel { return SyncStateLabel.RemoteUpgradeRequired }
private let previousState: BaseSyncStateWithInfo
public init(previousState: BaseSyncStateWithInfo) {
self.previousState = previousState
}
public func advance() -> Deferred<Maybe<SyncState>> {
return deferMaybe(FreshStartRequiredError(previousState: self.previousState))
}
}
public class ClientUpgradeRequired: RecoverableSyncState {
public var label: SyncStateLabel { return SyncStateLabel.ClientUpgradeRequired }
private let previousState: BaseSyncStateWithInfo
let targetStorageVersion: Int
public init(previousState: BaseSyncStateWithInfo, target: Int) {
self.previousState = previousState
self.targetStorageVersion = target
}
public func advance() -> Deferred<Maybe<SyncState>> {
return deferMaybe(ClientUpgradeRequiredError(target: self.targetStorageVersion))
}
}
/*
* Non-error states.
*/
public class InitialWithLiveToken: BaseSyncState {
public override var label: SyncStateLabel { return SyncStateLabel.InitialWithLiveToken }
// This looks totally redundant, but try taking it out, I dare you.
public override init(scratchpad: Scratchpad, token: TokenServerToken) {
super.init(scratchpad: scratchpad, token: token)
}
// This looks totally redundant, but try taking it out, I dare you.
public override init(client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken) {
super.init(client: client, scratchpad: scratchpad, token: token)
}
func advanceWithInfo(info: InfoCollections) -> SyncState {
return InitialWithLiveTokenAndInfo(scratchpad: self.scratchpad, token: self.token, info: info)
}
override public func advance() -> Deferred<Maybe<SyncState>> {
return chain(getInfoCollections(), f: self.advanceWithInfo)
}
}
/**
* Each time we fetch a new meta/global, we need to reconcile it with our
* current state.
*
* It might be identical to our current meta/global, in which case we can short-circuit.
*
* We might have no previous meta/global at all, in which case this state
* simply configures local storage to be ready to sync according to the
* supplied meta/global. (Not necessarily datatype elections: those will be per-device.)
*
* Or it might be different. In this case the previous m/g and our local user preferences
* are compared to the new, resulting in some actions and a final state.
*
* This states are similar in purpose to GlobalSession.processMetaGlobal in Android Sync.
*/
public class ResolveMetaGlobalVersion: BaseSyncStateWithInfo {
let fetched: Fetched<MetaGlobal>
init(fetched: Fetched<MetaGlobal>, client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken, info: InfoCollections) {
self.fetched = fetched
super.init(client: client, scratchpad: scratchpad, token: token, info: info)
}
public override var label: SyncStateLabel { return SyncStateLabel.ResolveMetaGlobalVersion }
class func fromState(state: BaseSyncStateWithInfo, fetched: Fetched<MetaGlobal>) -> ResolveMetaGlobalVersion {
return ResolveMetaGlobalVersion(fetched: fetched, client: state.client, scratchpad: state.scratchpad, token: state.token, info: state.info)
}
override public func advance() -> Deferred<Maybe<SyncState>> {
// First: check storage version.
let v = fetched.value.storageVersion
if v > StorageVersionCurrent {
// New storage version? Uh-oh. No recovery possible here.
log.info("Client upgrade required for storage version \(v)")
return deferMaybe(ClientUpgradeRequired(previousState: self, target: v))
}
if v < StorageVersionCurrent {
// Old storage version? Uh-oh. Wipe and upload both meta/global and crypto/keys.
log.info("Server storage version \(v) is outdated.")
return deferMaybe(RemoteUpgradeRequired(previousState: self))
}
return deferMaybe(ResolveMetaGlobalContent.fromState(self, fetched: self.fetched))
}
}
public class ResolveMetaGlobalContent: BaseSyncStateWithInfo {
let fetched: Fetched<MetaGlobal>
init(fetched: Fetched<MetaGlobal>, client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken, info: InfoCollections) {
self.fetched = fetched
super.init(client: client, scratchpad: scratchpad, token: token, info: info)
}
public override var label: SyncStateLabel { return SyncStateLabel.ResolveMetaGlobalContent }
class func fromState(state: BaseSyncStateWithInfo, fetched: Fetched<MetaGlobal>) -> ResolveMetaGlobalContent {
return ResolveMetaGlobalContent(fetched: fetched, client: state.client, scratchpad: state.scratchpad, token: state.token, info: state.info)
}
override public func advance() -> Deferred<Maybe<SyncState>> {
// Check global syncID and contents.
if let previous = self.scratchpad.global?.value {
// Do checks that only apply when we're coming from a previous meta/global.
if previous.syncID != fetched.value.syncID {
log.info("Remote global sync ID has changed. Dropping keys and resetting all local collections.")
let s = self.scratchpad.freshStartWithGlobal(fetched).checkpoint()
return deferMaybe(HasMetaGlobal.fromState(self, scratchpad: s))
}
let b = self.scratchpad.evolve()
.setGlobal(fetched) // We always adopt the upstream meta/global record.
let previousEngines = Set(previous.engines.keys)
let remoteEngines = Set(fetched.value.engines.keys)
for engine in previousEngines.subtract(remoteEngines) {
log.info("Remote meta/global disabled previously enabled engine \(engine).")
b.localCommands.insert(.DisableEngine(engine: engine))
}
for engine in remoteEngines.subtract(previousEngines) {
log.info("Remote meta/global enabled previously disabled engine \(engine).")
b.localCommands.insert(.EnableEngine(engine: engine))
}
for engine in remoteEngines.intersect(previousEngines) {
let remoteEngine = fetched.value.engines[engine]!
let previousEngine = previous.engines[engine]!
if previousEngine.syncID != remoteEngine.syncID {
log.info("Remote sync ID for \(engine) has changed. Resetting local.")
b.localCommands.insert(.ResetEngine(engine: engine))
}
}
let s = b.build().checkpoint()
return deferMaybe(HasMetaGlobal.fromState(self, scratchpad: s))
}
// No previous meta/global. Adopt the new meta/global.
let s = self.scratchpad.freshStartWithGlobal(fetched).checkpoint()
return deferMaybe(HasMetaGlobal.fromState(self, scratchpad: s))
}
}
private func processFailure(failure: MaybeErrorType?) -> MaybeErrorType {
if let failure = failure as? ServerInBackoffError {
log.warning("Server in backoff. Bailing out. \(failure.description)")
return failure
}
// TODO: backoff etc. for all of these.
if let failure = failure as? ServerError<NSHTTPURLResponse> {
// Be passive.
log.error("Server error. Bailing out. \(failure.description)")
return failure
}
if let failure = failure as? BadRequestError<NSHTTPURLResponse> {
// Uh oh.
log.error("Bad request. Bailing out. \(failure.description)")
return failure
}
log.error("Unexpected failure. \(failure?.description)")
return failure ?? UnknownError()
}
public class InitialWithLiveTokenAndInfo: BaseSyncStateWithInfo {
public override var label: SyncStateLabel { return SyncStateLabel.InitialWithLiveTokenAndInfo }
// This method basically hops over HasMetaGlobal, because it's not a state
// that we expect consumers to know about.
override public func advance() -> Deferred<Maybe<SyncState>> {
// Either m/g and c/k are in our local cache, and they're up-to-date with i/c,
// or we need to fetch them.
// Cached and not changed in i/c? Use that.
// This check would be inaccurate if any other fields were stored in meta/; this
// has been the case in the past, with the Sync 1.1 migration indicator.
if let global = self.scratchpad.global {
if let metaModified = self.info.modified("meta") {
// We check the last time we fetched the record, and that can be
// later than the collection timestamp. All we care about here is if the
// server might have a newer record.
if global.timestamp >= metaModified {
log.debug("Cached meta/global fetched at \(global.timestamp), newer than server modified \(metaModified). Using cached meta/global.")
// Strictly speaking we can avoid fetching if this condition is not true,
// but if meta/ is modified for a different reason -- store timestamps
// for the last collection fetch. This will do for now.
return deferMaybe(HasMetaGlobal.fromState(self))
}
log.info("Cached meta/global fetched at \(global.timestamp) older than server modified \(metaModified). Fetching fresh meta/global.")
} else {
// No known modified time for meta/. That means the server has no meta/global.
// Drop our cached value and fall through; we'll try to fetch, fail, and
// go through the usual failure flow.
log.warning("Local meta/global fetched at \(global.timestamp) found, but no meta collection on server. Dropping cached meta/global.")
self.scratchpad = self.scratchpad.evolve().setGlobal(nil).setKeys(nil).build().checkpoint()
}
} else {
log.debug("No cached meta/global found. Fetching fresh meta/global.")
}
// Fetch.
return self.client.getMetaGlobal().bind { result in
if let resp = result.successValue {
// We use the server's timestamp, rather than the record's modified field.
// Either can be made to work, but the latter has suffered from bugs: see Bug 1210625.
let fetched = Fetched(value: resp.value, timestamp: resp.metadata.timestampMilliseconds)
return deferMaybe(ResolveMetaGlobalVersion.fromState(self, fetched: fetched))
}
if let _ = result.failureValue as? NotFound<NSHTTPURLResponse> {
// OK, this is easy.
// This state is responsible for creating the new m/g, uploading it, and
// restarting with a clean scratchpad.
return deferMaybe(MissingMetaGlobalError(previousState: self))
}
// Otherwise, we have a failure state. Die on the sword!
return deferMaybe(processFailure(result.failureValue))
}
}
}
public class HasMetaGlobal: BaseSyncStateWithInfo {
public override var label: SyncStateLabel { return SyncStateLabel.HasMetaGlobal }
class func fromState(state: BaseSyncStateWithInfo) -> HasMetaGlobal {
return HasMetaGlobal(client: state.client, scratchpad: state.scratchpad, token: state.token, info: state.info)
}
class func fromState(state: BaseSyncStateWithInfo, scratchpad: Scratchpad) -> HasMetaGlobal {
return HasMetaGlobal(client: state.client, scratchpad: scratchpad, token: state.token, info: state.info)
}
override public func advance() -> Deferred<Maybe<SyncState>> {
// Check if crypto/keys is fresh in the cache already.
if let keys = self.scratchpad.keys where keys.value.valid {
if let cryptoModified = self.info.modified("crypto") {
// Both of these are server timestamps. If the record we stored was fetched after the last time the record was modified, as represented by the "crypto" entry in info/collections, and we're fetching from the
// same server, then the record must be identical, and we can use it directly. If are ever additional records in the crypto collection, this will fetch keys too frequently. In that case, we should use X-I-U-S and expect some 304 responses.
if keys.timestamp >= cryptoModified {
log.debug("Cached keys fetched at \(keys.timestamp), newer than server modified \(cryptoModified). Using cached keys.")
return deferMaybe(HasFreshCryptoKeys.fromState(self, scratchpad: self.scratchpad, collectionKeys: keys.value))
}
// The server timestamp is newer, so there might be new keys.
// Re-fetch keys and check to see if the actual contents differ.
// If the keys are the same, we can ignore this change. If they differ,
// we need to re-sync any collection whose keys just changed.
log.info("Cached keys fetched at \(keys.timestamp) older than server modified \(cryptoModified). Fetching fresh keys.")
return deferMaybe(NeedsFreshCryptoKeys.fromState(self, scratchpad: self.scratchpad, staleCollectionKeys: keys.value))
} else {
// No known modified time for crypto/. That likely means the server has no keys.
// Drop our cached value and fall through; we'll try to fetch, fail, and
// go through the usual failure flow.
log.warning("Local keys fetched at \(keys.timestamp) found, but no crypto collection on server. Dropping cached keys.")
self.scratchpad = self.scratchpad.evolve().setKeys(nil).build().checkpoint()
}
} else {
log.debug("No cached keys found. Fetching fresh keys.")
}
return deferMaybe(NeedsFreshCryptoKeys.fromState(self, scratchpad: self.scratchpad, staleCollectionKeys: nil))
}
}
public class NeedsFreshCryptoKeys: BaseSyncStateWithInfo {
public override var label: SyncStateLabel { return SyncStateLabel.NeedsFreshCryptoKeys }
let staleCollectionKeys: Keys?
class func fromState(state: BaseSyncStateWithInfo, scratchpad: Scratchpad, staleCollectionKeys: Keys?) -> NeedsFreshCryptoKeys {
return NeedsFreshCryptoKeys(client: state.client, scratchpad: scratchpad, token: state.token, info: state.info, keys: staleCollectionKeys)
}
public init(client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken, info: InfoCollections, keys: Keys?) {
self.staleCollectionKeys = keys
super.init(client: client, scratchpad: scratchpad, token: token, info: info)
}
override public func advance() -> Deferred<Maybe<SyncState>> {
// Fetch crypto/keys.
return self.client.getCryptoKeys(self.scratchpad.syncKeyBundle, ifUnmodifiedSince: nil).bind { result in
if let resp = result.successValue {
let collectionKeys = Keys(payload: resp.value.payload)
if (!collectionKeys.valid) {
log.error("Unexpectedly invalid crypto/keys during a successful fetch.")
return Deferred(value: Maybe(failure: InvalidKeysError(collectionKeys)))
}
let fetched = Fetched(value: collectionKeys, timestamp: resp.metadata.timestampMilliseconds)
let s = self.scratchpad.evolve()
.addLocalCommandsFromKeys(fetched)
.setKeys(fetched)
.build().checkpoint()
return deferMaybe(HasFreshCryptoKeys.fromState(self, scratchpad: s, collectionKeys: collectionKeys))
}
if let _ = result.failureValue as? NotFound<NSHTTPURLResponse> {
// No crypto/keys? We can handle this. Wipe and upload both meta/global and crypto/keys.
return deferMaybe(MissingCryptoKeysError(previousState: self))
}
// Otherwise, we have a failure state.
return deferMaybe(processFailure(result.failureValue))
}
}
}
public class HasFreshCryptoKeys: BaseSyncStateWithInfo {
public override var label: SyncStateLabel { return SyncStateLabel.HasFreshCryptoKeys }
let collectionKeys: Keys
class func fromState(state: BaseSyncStateWithInfo, scratchpad: Scratchpad, collectionKeys: Keys) -> HasFreshCryptoKeys {
return HasFreshCryptoKeys(client: state.client, scratchpad: scratchpad, token: state.token, info: state.info, keys: collectionKeys)
}
public init(client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken, info: InfoCollections, keys: Keys) {
self.collectionKeys = keys
super.init(client: client, scratchpad: scratchpad, token: token, info: info)
}
override public func advance() -> Deferred<Maybe<SyncState>> {
return deferMaybe(Ready(client: self.client, scratchpad: self.scratchpad, token: self.token, info: self.info, keys: self.collectionKeys))
}
}
public protocol EngineStateChanges {
func collectionsThatNeedLocalReset() -> [String]
func enginesEnabled() -> [String]
func enginesDisabled() -> [String]
func clearLocalCommands()
}
public class Ready: BaseSyncStateWithInfo {
public override var label: SyncStateLabel { return SyncStateLabel.Ready }
let collectionKeys: Keys
public init(client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken, info: InfoCollections, keys: Keys) {
self.collectionKeys = keys
super.init(client: client, scratchpad: scratchpad, token: token, info: info)
}
}
extension Ready: EngineStateChanges {
public func collectionsThatNeedLocalReset() -> [String] {
var needReset: Set<String> = Set()
for command in self.scratchpad.localCommands {
switch command {
case let .ResetAllEngines(except: except):
needReset.unionInPlace(Set(LocalEngines).subtract(except))
case let .ResetEngine(engine):
needReset.insert(engine)
case .EnableEngine, .DisableEngine:
break
}
}
return Array(needReset).sort()
}
public func enginesEnabled() -> [String] {
var engines: Set<String> = Set()
for command in self.scratchpad.localCommands {
switch command {
case let .EnableEngine(engine):
engines.insert(engine)
default:
break
}
}
return Array(engines).sort()
}
public func enginesDisabled() -> [String] {
var engines: Set<String> = Set()
for command in self.scratchpad.localCommands {
switch command {
case let .DisableEngine(engine):
engines.insert(engine)
default:
break
}
}
return Array(engines).sort()
}
public func clearLocalCommands() {
self.scratchpad = self.scratchpad.evolve().clearLocalCommands().build().checkpoint()
}
}
|
mpl-2.0
|
a7b092293a9a0d3b27351c5c84acf99f
| 40.852064 | 257 | 0.684039 | 5.009609 | false | false | false | false |
aahmedae/blitz-news-ios
|
Blitz News/Controller/SelectSourcesViewController.swift
|
1
|
3010
|
//
// SelectSourcesViewController.swift
// Blitz News
//
// Created by Asad Ahmed on 5/16/17.
// View controller responsible for handling input for selecting the user's preferred news sources
//
import UIKit
class SelectSourcesViewController: NewsSourceViewController
{
// MARK:- Outlets and variables
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var spinner: UIActivityIndicatorView!
// MARK:- Setup
override func viewDidLoad()
{
super.viewDidLoad()
setupUI()
loadNewsSources()
}
// Fetches the data for the sources.
func loadNewsSources()
{
UIApplication.shared.isNetworkActivityIndicatorVisible = true
allowUserSelections = true
weak var weakSelf = self
NewsAPIManager.sharedInstance.newsSources { [unowned self] (data, error) in
if let sources = data
{
weakSelf?.sources = sources
weakSelf?.categoryIDs = NewsAPIManager.sharedInstance.categoryIDs
DispatchQueue.main.async {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
weakSelf?.spinner.stopAnimating()
weakSelf?.setupNewsSourceTableView(tableView: self.tableView)
}
}
else
{
// recevied error when downloading
DispatchQueue.main.async {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
weakSelf?.spinner.stopAnimating()
let ac = NewsSourceVCHelper.alertDialogForError(error)
weakSelf?.present(ac, animated: true, completion: nil)
}
}
}
}
// UI setup
fileprivate func setupUI()
{
view.backgroundColor = UISettings.VC_BACKGROUND_COLOR
tableView.backgroundColor = UISettings.VC_BACKGROUND_COLOR
tableView.separatorColor = UISettings.SOURCE_TABLE_VIEW_SEPARATOR_COLOR
tableView.separatorInset = UISettings.SOURCE_TABLE_VIEW_SEPARATOR_INSETS
}
// MARK:- Table View
// User taps on cell to select / deselect a news source
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
// toggle the selection state of the source
let source = sourceForIndexPath(indexPath)
source.userSelected = !source.userSelected
// reload table view row to reflect the new changes
tableView.deselectRow(at: indexPath, animated: false)
tableView.reloadRows(at: [indexPath], with: .automatic)
}
// MARK:- Events
@IBAction func doneBarButtonTapped(_ sender: UIBarButtonItem)
{
// save selected news sources in core data
CoreDataManager.sharedInstance.save()
presentingViewController?.dismiss(animated: true, completion: nil)
}
}
|
mit
|
509e86fe6729eb2af5022e75816c3322
| 32.076923 | 98 | 0.619269 | 5.563771 | false | false | false | false |
gregomni/swift
|
SwiftCompilerSources/Sources/SIL/Operand.swift
|
2
|
3398
|
//===--- Operand.swift - Instruction operands -----------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SILBridging
/// An operand of an instruction.
public struct Operand : CustomStringConvertible, CustomReflectable {
fileprivate let bridged: BridgedOperand
init(_ bridged: BridgedOperand) {
self.bridged = bridged
}
public var value: Value {
Operand_getValue(bridged).value
}
public static func ==(lhs: Operand, rhs: Operand) -> Bool {
return lhs.bridged.op == rhs.bridged.op
}
public var instruction: Instruction {
return Operand_getUser(bridged).instruction
}
public var index: Int { instruction.operands.getIndex(of: self) }
/// True if the operand is used to describe a type dependency, but it's not
/// used as value.
public var isTypeDependent: Bool { Operand_isTypeDependent(bridged) != 0 }
public var description: String { "operand #\(index) of \(instruction)" }
public var customMirror: Mirror { Mirror(self, children: []) }
}
public struct OperandArray : RandomAccessCollection, CustomReflectable {
private let opArray: BridgedArrayRef
init(opArray: BridgedArrayRef) {
self.opArray = opArray
}
public var startIndex: Int { return 0 }
public var endIndex: Int { return Int(opArray.numElements) }
public subscript(_ index: Int) -> Operand {
precondition(index >= 0 && index < endIndex)
return Operand(BridgedOperand(op: opArray.data! + index &* BridgedOperandSize))
}
public func getIndex(of operand: Operand) -> Int {
let idx = (operand.bridged.op - UnsafeRawPointer(opArray.data!)) /
BridgedOperandSize
precondition(self[idx].bridged.op == operand.bridged.op)
return idx
}
public var customMirror: Mirror {
let c: [Mirror.Child] = map { (label: nil, value: $0.value) }
return Mirror(self, children: c)
}
public subscript(bounds: Range<Int>) -> OperandArray {
precondition(bounds.lowerBound >= 0)
precondition(bounds.upperBound <= endIndex)
return OperandArray(opArray: BridgedArrayRef(
data: opArray.data! + bounds.lowerBound &* BridgedOperandSize,
numElements: bounds.upperBound - bounds.lowerBound))
}
}
public struct UseList : CollectionLikeSequence {
public struct Iterator : IteratorProtocol {
var currentOpPtr: UnsafeRawPointer?
public mutating func next() -> Operand? {
if let opPtr = currentOpPtr {
let bridged = BridgedOperand(op: opPtr)
currentOpPtr = Operand_nextUse(bridged).op
return Operand(bridged)
}
return nil
}
}
private let firstOpPtr: UnsafeRawPointer?
init(_ firstOpPtr: OptionalBridgedOperand) {
self.firstOpPtr = firstOpPtr.op
}
public var isSingleUse: Bool {
if let opPtr = firstOpPtr {
return Operand_nextUse(BridgedOperand(op: opPtr)).op == nil
}
return false
}
public func makeIterator() -> Iterator {
return Iterator(currentOpPtr: firstOpPtr)
}
}
|
apache-2.0
|
400e7a5dd2a7277447644b37b2b9f1ea
| 29.339286 | 83 | 0.668923 | 4.530667 | false | false | false | false |
geraldWilliam/Tenkay
|
Pod/Classes/ImageView.swift
|
1
|
811
|
//
// ImageView.swift
// Tenkay
//
// Created by Gerald Burke on 2/20/16.
// Copyright © 2016 Gerald Burke. All rights reserved.
//
import Foundation
private let imageCache = NSCache()
public extension UIImageView {
public func setImageURL(url: NSURL) {
if let cachedImage = imageCache.objectForKey(url) as? UIImage {
Dispatch.onMain() { [weak self] in
self?.image = cachedImage
}
}
Dispatch.inBackground() {
guard let
data = NSData(contentsOfURL: url),
fetchedImage = UIImage(data: data)
else { return }
imageCache.setObject(fetchedImage, forKey: url)
Dispatch.onMain() { [weak self] in
guard let strong = self else { return }
strong.image = fetchedImage
}
}
}
}
|
mit
|
378a22aac2c0234f6071336d7c4967e1
| 21.527778 | 67 | 0.6 | 4.175258 | false | false | false | false |
nbkhope/swift
|
HackingWithSwift/Project1/Project1/MasterViewController.swift
|
1
|
2357
|
//
// MasterViewController.swift
// Project1
//
// Created by nbkhope on 10/5/15.
// Copyright © 2015 nbkdev. All rights reserved.
//
import UIKit
class MasterViewController: UITableViewController {
var detailViewController: DetailViewController? = nil
/* To hold the items in the list */
var objects = [String]()
override func viewDidLoad() {
super.viewDidLoad()
let fm = NSFileManager.defaultManager()
let path = NSBundle.mainBundle().resourcePath!
let items = try! fm.contentsOfDirectoryAtPath(path)
for item in items {
if item.hasPrefix("nssl") {
objects.append(item)
}
}
}
override func viewWillAppear(animated: Bool) {
self.clearsSelectionOnViewWillAppear = self.splitViewController!.collapsed
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow {
let navigationController = segue.destinationViewController as! UINavigationController
let controller = navigationController.topViewController as! DetailViewController
controller.detailItem = objects[indexPath.row]
// Note: detailItem is an optional String var
controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return objects.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
let object = objects[indexPath.row]
cell.textLabel!.text = object
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
}
|
gpl-2.0
|
4fe11193562bd8c70c77ed06ea44875d
| 26.395349 | 115 | 0.73854 | 4.665347 | false | false | false | false |
Pluto-tv/RxSwift
|
RxSwift/Subjects/ReplaySubject.swift
|
1
|
6406
|
//
// ReplaySubject.swift
// RxSwift
//
// Created by Krunoslav Zaher on 4/14/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
/**
Represents an object that is both an observable sequence as well as an observer.
Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies.
*/
public class ReplaySubject<Element> : Observable<Element>, SubjectType, ObserverType, Disposable {
public typealias SubjectObserverType = ReplaySubject<Element>
typealias DisposeKey = Bag<AnyObserver<Element>>.KeyType
func unsubscribe(key: DisposeKey) {
abstractMethod()
}
/**
Notifies all subscribed observers about next event.
- parameter event: Event to send to the observers.
*/
public func on(event: Event<E>) {
abstractMethod()
}
/**
Returns observer interface for subject.
*/
public func asObserver() -> SubjectObserverType {
return self
}
/**
Unsubscribe all observers and release resources.
*/
public func dispose() {
}
/**
Creates new instance of `ReplaySubject` that replays at most `bufferSize` last elements of sequence.
- parameter bufferSize: Maximal number of elements to replay to observer after subscription.
- returns: New instance of replay subject.
*/
public static func create(bufferSize bufferSize: Int) -> ReplaySubject<Element> {
if bufferSize == 1 {
return ReplayOne()
}
else {
return ReplayMany(bufferSize: bufferSize)
}
}
}
class ReplayBufferBase<Element> : ReplaySubject<Element> {
let lock = NSRecursiveLock()
// state
var disposed = false
var stoppedEvent = nil as Event<Element>?
var observers = Bag<AnyObserver<Element>>()
override init() {
}
func trim() {
abstractMethod()
}
func addValueToBuffer(value: Element) {
abstractMethod()
}
func replayBuffer(observer: AnyObserver<Element>) {
abstractMethod()
}
override func on(event: Event<Element>) {
lock.performLocked {
if self.disposed {
return
}
if self.stoppedEvent != nil {
return
}
switch event {
case .Next(let value):
addValueToBuffer(value)
trim()
self.observers.forEach { $0.on(event) }
case .Error, .Completed:
stoppedEvent = event
trim()
self.observers.forEach { $0.on(event) }
observers.removeAll()
}
}
}
override func subscribe<O : ObserverType where O.E == Element>(observer: O) -> Disposable {
return lock.calculateLocked {
if self.disposed {
observer.on(.Error(RxError.DisposedError))
return NopDisposable.instance
}
let AnyObserver = observer.asObserver()
replayBuffer(AnyObserver)
if let stoppedEvent = self.stoppedEvent {
observer.on(stoppedEvent)
return NopDisposable.instance
}
else {
let key = self.observers.insert(AnyObserver)
return ReplaySubscription(subject: self, disposeKey: key)
}
}
}
override func unsubscribe(key: DisposeKey) {
lock.performLocked {
if self.disposed {
return
}
_ = self.observers.removeKey(key)
}
}
func lockedDispose() {
disposed = true
stoppedEvent = nil
observers.removeAll()
}
override func dispose() {
super.dispose()
lock.performLocked {
self.lockedDispose()
}
}
}
class ReplayOne<Element> : ReplayBufferBase<Element> {
var value: Element?
override init() {
super.init()
}
override func trim() {
}
override func addValueToBuffer(value: Element) {
self.value = value
}
override func replayBuffer(observer: AnyObserver<Element>) {
if let value = self.value {
observer.on(.Next(value))
}
}
override func lockedDispose() {
super.lockedDispose()
value = nil
}
}
class ReplayManyBase<Element> : ReplayBufferBase<Element> {
var queue: Queue<Element>
init(queueSize: Int) {
queue = Queue(capacity: queueSize + 1)
}
override func addValueToBuffer(value: Element) {
queue.enqueue(value)
}
override func replayBuffer(observer: AnyObserver<E>) {
for item in queue {
observer.on(.Next(item))
}
}
override func lockedDispose() {
super.lockedDispose()
self.queue = Queue(capacity: 0)
}
}
class ReplayMany<Element> : ReplayManyBase<Element> {
let bufferSize: Int
init(bufferSize: Int) {
self.bufferSize = bufferSize
super.init(queueSize: bufferSize)
}
override func trim() {
while queue.count > bufferSize {
queue.dequeue()
}
}
}
class ReplayAll<Element> : ReplayManyBase<Element> {
init() {
super.init(queueSize: 0)
}
override func trim() {
}
}
class ReplaySubscription<Element> : Disposable {
typealias Subject = ReplaySubject<Element>
typealias DisposeKey = ReplayBufferBase<Element>.DisposeKey
var lock = SpinLock()
// state
var subject: Subject?
var disposeKey: DisposeKey?
init(subject: Subject, disposeKey: DisposeKey) {
self.subject = subject
self.disposeKey = disposeKey
}
func dispose() {
let oldState = lock.calculateLocked { () -> (Subject?, DisposeKey?) in
let state = (self.subject, self.disposeKey)
self.subject = nil
self.disposeKey = nil
return state
}
if let subject = oldState.0, let disposeKey = oldState.1 {
subject.unsubscribe(disposeKey)
}
}
}
|
mit
|
f60e82cc9a3bb4b0806963ff191ca687
| 23.357414 | 109 | 0.56088 | 5.137129 | false | false | false | false |
KempinGe/LiveBroadcast
|
LIveBroadcast/LIveBroadcast/classes/Home/Model/GKBCarouselModel.swift
|
1
|
777
|
//
// GKBCarouselModel.swift
// LIveBroadcast
//
// Created by KempinGe on 2016/12/11.
// Copyright © 2016年 盖凯宾. All rights reserved.
//
import UIKit
class GKBCarouselModel: NSObject {
// var id : String = ""
var title : String = ""
var pic_url : String = ""
var tv_pic_url : String = ""
var room : [String : NSObject]? {
didSet{
guard let anchorRoom = room else {
return
}
carouselRoom = GKBAnchorModel(dict: anchorRoom)
}
}
var carouselRoom : GKBAnchorModel?
init(dict : [String : Any]) {
super.init()
setValuesForKeys(dict)
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {
}
}
|
mit
|
2953c392bf03731b5365b90e2a86496f
| 19.756757 | 72 | 0.544271 | 3.979275 | false | false | false | false |
aliceatlas/daybreak
|
Classes/SBTabViewItem.swift
|
1
|
48575
|
/*
SBTabViewItem.swift
Copyright (c) 2014, Alice Atlas
Copyright (c) 2010, Atsushi Jike
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import BLKGUI
class SBTabViewItem: NSTabViewItem, NSSplitViewDelegate, SBWebViewDelegate, SBSourceTextViewDelegate, WebFrameLoadDelegate, WebResourceLoadDelegate, WebUIDelegate, WebPolicyDelegate {
unowned var tabbarItem: SBTabbarItem
override var tabView: SBTabView! {
return super.tabView as? SBTabView
}
var URL: NSURL? {
didSet {
URL !! { self.webView.mainFrame.loadRequest(NSURLRequest(URL: $0, cachePolicy: .ReloadIgnoringLocalCacheData, timeoutInterval: kSBTimeoutInterval)) }
}
}
lazy var splitView: SBTabSplitView = {
let splitView = SBTabSplitView(frame: .zero)
splitView.delegate = self
splitView.autoresizingMask = [.ViewWidthSizable, .ViewHeightSizable]
return splitView
}()
var sourceView: SBDrawer?
var madeWebView = false
lazy var webView: SBWebView = {
let center = NSNotificationCenter.defaultCenter()
let view = SBWebView(frame: self.tabView!.bounds, frameName: nil, groupName: nil)
// Set properties
view.drawsBackground = true
view.autoresizingMask = [.ViewWidthSizable, .ViewHeightSizable]
view.delegate = self
view.hostWindow = self.tabView!.window
view.frameLoadDelegate = self
view.resourceLoadDelegate = self
view.UIDelegate = self
view.policyDelegate = self
view.downloadDelegate = SBDownloads.sharedDownloads
view.preferences = SBGetWebPreferences
view.textEncodingName = view.preferences.defaultTextEncodingName
self.setUserAgent(view)
// Add observer
center.addObserver(self, selector: #selector(webViewProgressStarted(_:)), name: WebViewProgressStartedNotification, object: view)
center.addObserver(self, selector: #selector(webViewProgressEstimateChanged(_:)), name: WebViewProgressEstimateChangedNotification, object: view)
center.addObserver(self, selector: #selector(webViewProgressFinished(_:)), name: WebViewProgressFinishedNotification, object: view)
self.splitView.invisibleDivider = true
self.splitView.addSubview(view)
self.madeWebView = true
return view
}()
var sourceTextView: SBSourceTextView?
var webSplitView: SBFixedSplitView?
var sourceSplitView: SBFixedSplitView?
var sourceSaveButton: BLKGUI.Button?
var sourceCloseButton: BLKGUI.Button?
var resourceIdentifiers: [SBWebResourceIdentifier] = []
//var showSource = false
private let sourceBottomMargin: CGFloat = 48.0
var URLString: String? {
get { return URL?.absoluteString }
set(URLString) {
URL = URLString !! {NSURL(string: $0.URLEncodedString)}
}
}
var selected: Bool {
get { return tabView.selectedTabViewItem! === self }
set(selected) { tabView.selectTabViewItem(self) }
}
var canBackward: Bool { return webView.canGoBack }
var canForward: Bool { return webView.canGoForward }
var mainFrameURLString: String? { return webView.mainFrameURL }
var pageTitle: String? { return webView.mainFrame.dataSource?.pageTitle }
var requestURLString: String? { return webView.mainFrame?.dataSource?.request.URL?.absoluteString }
var documentSource: String? { return webView.mainFrame?.dataSource?.representation?.documentSource() }
init(identifier: Int, tabbarItem: SBTabbarItem) {
self.tabbarItem = tabbarItem
super.init(identifier: identifier)
view = NSView(frame: .zero)
view!.addSubview(splitView)
}
deinit {
destructWebView()
}
required init?(coder: NSCoder) {
fatalError("NSCoding not supported")
}
// MARK: Getter
func webFramesInFrame(frame: WebFrame) -> [WebFrame] {
var frames: [WebFrame] = []
for childFrame in frame.childFrames as! [WebFrame] {
frames.append(childFrame)
if !childFrame.childFrames.isEmpty {
frames += webFramesInFrame(childFrame)
}
}
return frames
}
// MARK: Setter
func toggleShowSource() {
showSource = !showSource
}
func hideShowSource() {
showSource = false
}
var showSource: Bool = false {
didSet {
if showSource != oldValue {
if showSource {
var r = view!.bounds
var tr = view!.bounds
var br = view!.bounds
var openRect = NSZeroRect
var saveRect = NSZeroRect
var closeRect = NSZeroRect
var wr = view!.bounds
wr.size.height *= 0.6
r.size.height *= 0.4
br.size.height = sourceBottomMargin
tr.size.height = r.size.height - br.size.height
tr.origin.y = br.size.height
saveRect.size.width = 105.0
saveRect.size.height = 24.0
saveRect.origin.x = r.size.width - saveRect.size.width - 10.0
saveRect.origin.y = br.origin.y + (br.size.height - saveRect.size.height) / 2
openRect.size.width = 210.0
openRect.size.height = 24.0
openRect.origin.y = saveRect.origin.y
openRect.origin.x = saveRect.origin.x - openRect.size.width - 10.0
closeRect.size.width = 105.0
closeRect.size.height = 24.0
closeRect.origin.y = saveRect.origin.y
closeRect.origin.x = 10.0
sourceView = SBDrawer(frame: r)
let scrollView = BLKGUI.ScrollView(frame: tr)
let openButton = BLKGUI.Button(frame: openRect)
sourceSaveButton = BLKGUI.Button(frame: saveRect)
sourceCloseButton = BLKGUI.Button(frame: closeRect)
#if true
let horizontalScroller = scrollView.horizontalScroller as? BLKGUI.Scroller
let verticalScroller = scrollView.verticalScroller as? BLKGUI.Scroller
verticalScroller !! { r.size.width = r.size.width - $0.frame.size.width }
#endif
sourceTextView = SBSourceTextView(frame: tr)
scrollView.autoresizingMask = [.ViewWidthSizable, .ViewHeightSizable]
scrollView.autohidesScrollers = true
scrollView.hasHorizontalScroller = false
scrollView.hasVerticalScroller = true
scrollView.backgroundColor = SBBackgroundColor
scrollView.drawsBackground = true
#if true
horizontalScroller?.drawsBackground = true
horizontalScroller?.backgroundColor = NSColor(calibratedWhite: 0.35, alpha: 1.0)
verticalScroller?.drawsBackground = true
verticalScroller?.backgroundColor = NSColor(calibratedWhite: 0.35, alpha: 1.0)
#endif
sourceTextView!.delegate = self
sourceTextView!.minSize = NSMakeSize(0.0, r.size.height)
sourceTextView!.maxSize = NSMakeSize(CGFloat(FLT_MAX), CGFloat(FLT_MAX))
sourceTextView!.verticallyResizable = true
sourceTextView!.horizontallyResizable = false
sourceTextView!.usesFindPanel = true
sourceTextView!.editable = false
sourceTextView!.autoresizingMask = .ViewWidthSizable
sourceTextView!.textContainer!.containerSize = NSMakeSize(r.size.width, CGFloat(FLT_MAX))
sourceTextView!.textContainer!.widthTracksTextView = true
sourceTextView!.string = documentSource ?? ""
sourceTextView!.selectedRange = NSMakeRange(0, 0)
scrollView.documentView = sourceTextView
openButton.autoresizingMask = .ViewMinXMargin
openButton.title = NSLocalizedString("Open in other application…", comment: "")
openButton.target = self
openButton.action = #selector(openDocumentSource(_:))
sourceSaveButton!.autoresizingMask = .ViewMinXMargin
sourceSaveButton!.title = NSLocalizedString("Save", comment: "")
sourceSaveButton!.target = self
sourceSaveButton!.action = #selector(saveDocumentSource(_:))
sourceSaveButton!.keyEquivalent = "\r"
sourceCloseButton!.autoresizingMask = .ViewMinXMargin
sourceCloseButton!.title = NSLocalizedString("Close", comment: "")
sourceCloseButton!.target = self
sourceCloseButton!.action = #selector(hideShowSource)
sourceCloseButton!.keyEquivalent = "\u{1B}"
sourceView!.addSubviews(scrollView, openButton, sourceSaveButton!, sourceCloseButton!)
if webSplitView != nil {
webSplitView!.frame = wr
splitView.addSubview(webSplitView!)
} else {
webView.frame = wr
splitView.addSubview(webView)
}
splitView.addSubview(sourceView!)
splitView.invisibleDivider = false
webView.window!.makeFirstResponder(sourceTextView)
} else {
sourceTextView!.removeFromSuperview()
sourceSplitView?.removeFromSuperview()
sourceView!.removeFromSuperview()
sourceTextView = nil
sourceSplitView = nil
sourceView = nil
splitView.invisibleDivider = true
webView.window!.makeFirstResponder(webView)
}
splitView.adjustSubviews()
}
}
}
func setShowFindbarInWebView(showFindbar: Bool) -> Bool {
var r = false
if showFindbar {
if webSplitView == nil {
let findbar = SBFindbar(frame: NSMakeRect(0, 0, webView.frame.size.width, 24.0))
findbar.target = webView
findbar.doneSelector = #selector(SBWebView.executeCloseFindbar)
(sourceSplitView ?? sourceView)?.removeFromSuperview()
webSplitView = SBFixedSplitView(embedViews: [findbar, webView], frameRect: webView.frame)
(sourceSplitView ?? sourceView) !! splitView.addSubview
findbar.selectText(nil)
r = true
}
} else {
if webSplitView != nil {
(sourceSplitView ?? sourceView)?.removeFromSuperview()
SBDisembedViewInSplitView(webView, webSplitView!)
(sourceSplitView ?? sourceView) !! splitView.addSubview
webSplitView = nil
webView.window!.makeFirstResponder(webView)
r = true
}
}
return r
}
func setShowFindbarInSource(showFindbar: Bool) {
if showFindbar {
if sourceSplitView == nil {
let findbar = SBFindbar(frame: NSMakeRect(0, 0, sourceView!.frame.size.width, 24.0))
findbar.target = sourceTextView
findbar.doneSelector = #selector(SBSourceTextView.executeCloseFindbar)
sourceSaveButton!.keyEquivalent = ""
sourceCloseButton!.keyEquivalent = ""
sourceSplitView = SBFixedSplitView(embedViews: [findbar, sourceView!], frameRect: sourceView!.frame)
findbar.selectText(nil)
}
} else {
sourceSaveButton!.keyEquivalent = "\r"
sourceCloseButton!.keyEquivalent = "\u{1B}"
SBDisembedViewInSplitView(sourceView!, sourceSplitView!)
sourceSplitView = nil
sourceTextView!.window!.makeFirstResponder(sourceTextView)
}
}
func hideFinderbarInWebView() {
setShowFindbarInWebView(false)
}
func hideFinderbarInSource() {
setShowFindbarInSource(false)
}
// MARK: Destruction
func destructWebView() {
if madeWebView {
let center = NSNotificationCenter.defaultCenter()
center.removeObserver(self, name: WebViewProgressStartedNotification, object: webView)
center.removeObserver(self, name: WebViewProgressEstimateChangedNotification, object: webView)
center.removeObserver(self, name: WebViewProgressFinishedNotification, object: webView)
if webView.loading {
webView.stopLoading(nil)
}
webView.hostWindow = nil
webView.frameLoadDelegate = nil
webView.resourceLoadDelegate = nil
webView.UIDelegate = nil
webView.policyDelegate = nil
webView.downloadDelegate = nil
webView.removeFromSuperview()
}
}
// MARK: Construction
func setUserAgent() {
setUserAgent(nil)
}
private func setUserAgent(inView: SBWebView?) {
let webView = inView ?? self.webView
var userAgentName = NSUserDefaults.standardUserDefaults().stringForKey(kSBUserAgentName)
// Set custom user agent
if userAgentName == SBUserAgentNames[0] {
let bundle = NSBundle.mainBundle()
let infoDictionary = bundle.infoDictionary
let localizedInfoDictionary = bundle.localizedInfoDictionary
let applicationName = (localizedInfoDictionary?["CFBundleName"] ?? infoDictionary?["CFBundleName"]) as? String
let version = (infoDictionary?["CFBundleVersion"] as? String)?.stringByDeletingSpaces
var safariVersion = NSBundle(path: "/Applications/Safari.app")?.infoDictionary?["CFBundleVersion"] as? String
safariVersion = safariVersion !! {suffix($0, count($0) - 1)} ?? "0"
if applicationName != nil {
webView.applicationNameForUserAgent = applicationName!
version !! { webView.applicationNameForUserAgent = "\(webView.applicationNameForUserAgent)/\($0) Safari/\(safariVersion!)" }
webView.customUserAgent = nil
}
} else if userAgentName == SBUserAgentNames[1] {
let applicationName = SBUserAgentNames[1]
let bundle = NSBundle(path: "/Applications/\(applicationName).app")
let infoDictionary = bundle?.infoDictionary
let version = (infoDictionary?["CFBundleShortVersionString"] ?? infoDictionary?["CFBundleVersion"]) as? String
var safariVersion = NSBundle(path: "/Applications/Safari.app")?.infoDictionary?["CFBundleVersion"] as? String
safariVersion = safariVersion !! {suffix($0, count($0) - 1)} ?? "0"
if (version !! safariVersion) != nil {
webView.applicationNameForUserAgent = "Version/\(version!) \(applicationName)/\(safariVersion!)"
webView.customUserAgent = nil
}
} else {
webView.customUserAgent = userAgentName
}
}
// MARK: SplitView Delegate
func splitView(aSplitView: NSSplitView, canCollapseSubview subview: NSView) -> Bool {
return aSplitView !== splitView || subview !== webView
}
func splitView(aSplitView: NSSplitView, shouldHideDividerAtIndex dividerIndex: Int) -> Bool {
return false
}
func splitView(aSplitView: NSSplitView, shouldCollapseSubview subview: NSView, forDoubleClickOnDividerAtIndex dividerIndex: Int) -> Bool {
return true
}
func splitView(aSplitView: NSSplitView, constrainSplitPosition proposedPosition: CGFloat, ofSubviewAt offset: Int) -> CGFloat {
return proposedPosition
}
func splitView(aSplitView: NSSplitView, constrainMaxCoordinate proposedMax: CGFloat, ofSubviewAt offset: Int) -> CGFloat {
if aSplitView === splitView {
return splitView.bounds.size.height - 10 - sourceBottomMargin
}
return proposedMax
}
func splitView(aSplitView: NSSplitView, constrainMinCoordinate proposedMin: CGFloat, ofSubviewAt offset: Int) -> CGFloat {
if aSplitView === splitView {
return 10
}
return proposedMin
}
// MARK: TextView Delegate
func textViewShouldOpenFindbar(textView: SBSourceTextView) {
if sourceSplitView != nil {
setShowFindbarInSource(false)
}
setShowFindbarInSource(true)
}
func textViewShouldCloseFindbar(textView: SBSourceTextView) {
if sourceSplitView != nil {
setShowFindbarInSource(false)
}
}
// MARK: WebView Delegate
func webViewShouldOpenFindbar(webView: SBWebView) {
if webSplitView != nil {
setShowFindbarInWebView(false)
}
setShowFindbarInWebView(true)
}
func webViewShouldCloseFindbar(webView: SBWebView) -> Bool {
if webSplitView != nil {
return setShowFindbarInWebView(false)
}
return false
}
// MARK: WebView Notification
func webViewProgressStarted(notification: NSNotification) {
if notification.object === webView {
tabbarItem.progress = 0.0
}
}
func webViewProgressEstimateChanged(notification: NSNotification) {
if notification.object === webView {
tabbarItem.progress = CGFloat(webView.estimatedProgress)
}
}
func webViewProgressFinished(notification: NSNotification) {
if notification.object === webView {
tabbarItem.progress = 1.0
}
}
// MARK: WebFrameLoadDelegate
func webView(sender: WebView, didStartProvisionalLoadForFrame frame: WebFrame) {
if sender.mainFrame === frame {
removeAllResourceIdentifiers()
}
}
func webView(sender: WebView, didFinishLoadForFrame frame: WebFrame) {
if sender.mainFrame === frame {
if selected {
tabView.executeSelectedItemDidFinishLoading(self)
}
if showSource {
sourceTextView!.string = documentSource
}
}
}
func webView(sender: WebView, didCommitLoadForFrame frame: WebFrame) {
if sender.mainFrame === frame && selected {
tabView.executeSelectedItemDidStartLoading(self)
}
}
func webView(sender: WebView, willCloseFrame frame: WebFrame) {
if sender.mainFrame === frame {
}
}
func webView(sender: WebView, didChangeLocationWithinPageForFrame frame: WebFrame) {
if sender.mainFrame === frame {
}
}
func webView(sender: WebView, didReceiveTitle title: String, forFrame frame: WebFrame) {
if sender.mainFrame === frame {
tabbarItem.title = title
if selected {
tabView.executeSelectedItemDidReceiveTitle(self)
}
}
}
func webView(sender: WebView, didReceiveIcon image: NSImage, forFrame frame: WebFrame) {
if sender.mainFrame === frame {
tabbarItem.image = image
if selected {
tabView.executeSelectedItemDidReceiveIcon(self)
}
}
}
func webView(sender: WebView, didFailProvisionalLoadWithError error: NSError?, forFrame frame: WebFrame) {
// if ([[sender mainFrame] isEqual:frame]) {
if error != nil {
DebugLog("%@, %@", __FUNCTION__, error!.localizedDescription)
if let userInfo = error!.userInfo {
let URLString = userInfo[NSURLErrorFailingURLStringErrorKey] as! String
var title: String?
switch error!.code {
case NSURLErrorCancelled:
title = NSLocalizedString("Cancelled", comment: "")
case NSURLErrorBadURL:
title = NSLocalizedString("Bad URL", comment: "")
case NSURLErrorTimedOut:
title = NSLocalizedString("Timed Out", comment: "")
case NSURLErrorUnsupportedURL:
title = NSLocalizedString("Unsupported URL", comment: "")
case NSURLErrorCannotFindHost:
title = NSLocalizedString("Cannot Find Host", comment: "")
case NSURLErrorCannotConnectToHost:
title = NSLocalizedString("Cannot Connect to Host", comment: "")
case NSURLErrorNetworkConnectionLost:
title = NSLocalizedString("Network Connection Lost", comment: "")
case NSURLErrorDNSLookupFailed:
title = NSLocalizedString("DNS Lookup Failed", comment: "")
case NSURLErrorHTTPTooManyRedirects:
title = NSLocalizedString("Too Many Redirects", comment: "")
case NSURLErrorResourceUnavailable:
title = NSLocalizedString("Resource Unavailable", comment: "")
case NSURLErrorNotConnectedToInternet:
title = NSLocalizedString("Not Connected to Internet", comment: "")
case NSURLErrorRedirectToNonExistentLocation:
title = NSLocalizedString("Redirect to Non Existent Location", comment: "")
case NSURLErrorBadServerResponse:
title = NSLocalizedString("Bad Server Response", comment: "")
case NSURLErrorUserCancelledAuthentication:
title = NSLocalizedString("User Cancelled Authentication", comment: "")
case NSURLErrorUserAuthenticationRequired:
title = NSLocalizedString("User Authentication Required", comment: "")
case NSURLErrorZeroByteResource:
title = NSLocalizedString("Zero Byte Resource", comment: "")
case NSURLErrorCannotDecodeRawData:
title = NSLocalizedString("Cannot Decode Raw Data", comment: "")
case NSURLErrorCannotDecodeContentData:
title = NSLocalizedString("Cannot Decode Content Data", comment: "")
case NSURLErrorCannotParseResponse:
title = NSLocalizedString("Cannot Parse Response", comment: "")
case NSURLErrorFileDoesNotExist:
title = NSLocalizedString("File Does Not Exist", comment: "")
case NSURLErrorFileIsDirectory:
// Try to opening with other application
if let URL = NSURL(string: URLString)
where !NSWorkspace.sharedWorkspace().openURL(URL) {
title = NSLocalizedString("File is Directory", comment: "")
}
case NSURLErrorNoPermissionsToReadFile:
title = NSLocalizedString("No Permissions to ReadFile", comment: "")
case NSURLErrorDataLengthExceedsMaximum:
title = NSLocalizedString("Data Length Exceeds Maximum", comment: "")
case NSURLErrorSecureConnectionFailed:
title = NSLocalizedString("Secure Connection Failed", comment: "")
case NSURLErrorServerCertificateHasBadDate:
title = NSLocalizedString("Server Certificate Has BadDate", comment: "")
case NSURLErrorServerCertificateUntrusted:
let URL = NSURL(string: URLString)!
let aTitle = NSLocalizedString("Server Certificate Untrusted", comment: "")
var alert = NSAlert()
alert.messageText = aTitle
alert.addButtonWithTitle(NSLocalizedString("Continue", comment: ""))
alert.addButtonWithTitle(NSLocalizedString("Cancel", comment: ""))
alert.informativeText = NSLocalizedString("The certificate for this website is invalid. You might be connecting to a website that is pretending to be \"%@\", which could put your confidential information at risk. Would you like to connect to the website anyway?", comment: "").format(URL.host!)
alert.beginSheetModalForWindow(sender.window!) {
if $0 == NSAlertFirstButtonReturn {
NSURLRequest.setAllowsAnyHTTPSCertificate(true, forHost: URL.host)
frame.loadRequest(NSURLRequest(URL: URL, cachePolicy: .ReloadIgnoringLocalCacheData, timeoutInterval: kSBTimeoutInterval))
self.webView(self.webView, didStartProvisionalLoadForFrame: frame)
} else {
self.showErrorPageWithTitle(aTitle, URLString: URL.absoluteString, frame: frame)
}
}
case NSURLErrorServerCertificateHasUnknownRoot:
title = NSLocalizedString("Server Certificate Has UnknownRoot", comment: "")
case NSURLErrorServerCertificateNotYetValid:
title = NSLocalizedString("Server Certificate Not Yet Valid", comment: "")
case NSURLErrorClientCertificateRejected:
title = NSLocalizedString("Client Certificate Rejected", comment: "")
case NSURLErrorCannotLoadFromNetwork:
title = NSLocalizedString("Cannot Load from Network", comment: "")
default:
break
}
title !! { self.showErrorPageWithTitle($0, URLString: URLString, frame: frame) }
}
}
}
func webView(sender: WebView, didFailLoadWithError error: NSError, forFrame frame: WebFrame) {
if sender.mainFrame === frame {
DebugLog("%@, %@", __FUNCTION__, error.localizedDescription)
if selected {
tabView.executeSelectedItemDidFailLoading(self)
}
}
}
func webView(sender: WebView, didReceiveServerRedirectForProvisionalLoadForFrame frame: WebFrame) {
if sender.mainFrame === frame {
if selected {
tabView.executeSelectedItemDidReceiveServerRedirect(self)
}
}
}
// MARK: WebResourceLoadDelegate
func webView(sender: WebView, identifierForInitialRequest request: NSURLRequest, fromDataSource dataSource: WebDataSource) -> AnyObject {
let identifier = SBWebResourceIdentifier(URLRequest: request)
if addResourceIdentifier(identifier) && selected {
tabView.executeSelectedItemDidAddResourceID(identifier)
}
return identifier
}
func webView(sender: WebView, resource identifier: AnyObject?, willSendRequest request: NSURLRequest, redirectResponse: NSURLResponse, fromDataSource dataSource: WebDataSource) -> NSURLRequest {
return request
}
func webView(sender: WebView, resource identifier: AnyObject?, didReceiveResponse response: NSURLResponse, fromDataSource dataSource: WebDataSource) {
let length = response.expectedContentLength
if length > 0, let resourceID = identifier as? SBWebResourceIdentifier {
resourceID.length = length
if selected {
tabView.executeSelectedItemDidReceiveExpectedContentLengthOfResourceID(resourceID)
}
}
}
func webView(sender: WebView, resource identifier: AnyObject?, didFailLoadingWithError error: NSError, fromDataSource dataSource: WebDataSource) {
if let resourceID = identifier as? SBWebResourceIdentifier {
resourceID.flag = false
}
}
func webView(sender: WebView, resource identifier: AnyObject?, didReceiveContentLength length: Int, fromDataSource dataSource: WebDataSource) {
if length > 0, let resourceID = identifier as? SBWebResourceIdentifier {
resourceID.received += length
if selected {
tabView.executeSelectedItemDidReceiveContentLengthOfResourceID(resourceID)
}
}
}
func webView(sender: WebView, resource identifier: AnyObject?, didFinishLoadingFromDataSource dataSource: WebDataSource) {
if let resourceID = identifier as? SBWebResourceIdentifier {
if let response = NSURLCache.sharedURLCache().cachedResponseForRequest(resourceID.request) {
// Loaded from cache
let length = response.data.length
if length > 0 {
resourceID.length = CLongLong(length)
resourceID.received = CLongLong(length)
}
}
if selected {
tabView.executeSelectedItemDidReceiveFinishLoadingOfResourceID(resourceID)
}
}
}
// MARK: WebUIDelegate
func webViewShow(sender: WebView) {
if let document = sender.window!.delegate as? SBDocument {
document.showWindows()
}
}
func webView(sender: WebView, setToolbarsVisible visible: Bool) {
let window = sender.window as! SBDocumentWindow
let toolbar = window.sbToolbar!
toolbar.autosavesConfiguration = false
toolbar.visible = visible
if visible {
if !window.tabbarVisibility {
window.showTabbar()
}
} else {
if !window.tabbarVisibility {
window.hideTabbar()
}
}
}
func webView(sender: WebView, createWebViewModalDialogWithRequest request: NSURLRequest) -> WebView {
return webView
}
func webView(sender: WebView, createWebViewWithRequest request: NSURLRequest) -> WebView! {
let document = try? SBGetDocumentController.openUntitledDocumentAndDisplay(false, sidebarVisibility: false, initialURL: request.URL)
return document?.selectedWebView
}
func webView(sender: WebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WebFrame) -> Bool {
return tabView.executeShouldConfirmMessage(message)
}
func webView(sender: WebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WebFrame) {
tabView.executeShouldShowMessage(message)
}
func webView(sender: WebView, runOpenPanelForFileButtonWithResultListener resultListener: WebOpenPanelResultListener) {
let panel = SBOpenPanel()
let window = tabView!.window!
panel.beginSheetModalForWindow(window) {
if $0 == NSFileHandlingPanelOKButton {
resultListener.chooseFilename(panel.URLs[0].path)
}
panel.orderOut(nil)
}
}
func webView(sender: WebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String, initiatedByFrame frame: WebFrame) -> String? {
return tabView.executeShouldTextInput(prompt)
}
func webView(sender: WebView, contextMenuItemsForElement element: [NSObject: AnyObject], defaultMenuItems: [AnyObject]) -> [AnyObject] {
var menuItems: [NSMenuItem] = []
var selectedString = (sender.mainFrame.frameView.documentView as! WebDocumentText).selectedString()
if !selectedString.isEmpty {
for frame in webFramesInFrame(sender.mainFrame) {
selectedString = (frame.frameView.documentView as! WebDocumentText).selectedString()
if !selectedString.isEmpty {
break
}
}
}
let linkURL = element[WebElementLinkURLKey] as? NSURL
let frame = element[WebElementFrameKey] as! WebFrame
let frameURL = frame.dataSource?.request.URL
let applicationBundleIdentifier = NSUserDefaults.standardUserDefaults().stringForKey(kSBOpenApplicationBundleIdentifier)
var appName: String?
if let applicationPath = applicationBundleIdentifier !! {NSWorkspace.sharedWorkspace().absolutePathForAppBundleWithIdentifier($0)},
bundle = NSBundle(path: applicationPath) {
appName = (bundle.localizedInfoDictionary?["CFBundleDisplayName"] ?? bundle.infoDictionary?["CFBundleName"]) as? String
}
menuItems.extend(defaultMenuItems as! [NSMenuItem])
if linkURL == nil && selectedString.isEmpty {
if frameURL != nil {
// Add Open in items
let newItem1 = NSMenuItem(title: NSLocalizedString("Open in Application...", comment: ""), action: #selector(openURLInSelectedApplicationFromMenu(_:)), keyEquivalent: "")
newItem1.target = self
newItem1.representedObject = frameURL
var newItem2: NSMenuItem?
if appName != nil {
newItem2 = NSMenuItem(title: NSLocalizedString("Open in %@", comment: "").format(appName!), action: #selector(openURLInApplicationFromMenu(_:)), keyEquivalent: "")
newItem2!.target = self
newItem2!.representedObject = frameURL
}
menuItems.insert(.separatorItem(), atIndex: 0)
if newItem2 != nil {
menuItems.insert(newItem2!, atIndex: 0)
}
menuItems.insert(newItem1, atIndex: 0)
}
}
if linkURL != nil {
for (index, item) in reverse(Array(enumerate(menuItems))) {
let tag = item.tag
if tag == 1 {
// Add Open link in items
let newItem0 = NSMenuItem(title: NSLocalizedString("Open Link in New Tab", comment: ""), action: #selector(openURLInNewTabFromMenu(_:)), keyEquivalent: "")
newItem0.target = self
newItem0.representedObject = frameURL
let newItem1 = NSMenuItem(title: NSLocalizedString("Open Link in Application...", comment: ""), action: #selector(openURLInSelectedApplicationFromMenu(_:)), keyEquivalent: "")
newItem1.target = self
newItem1.representedObject = frameURL
var newItem2: NSMenuItem?
if appName != nil {
let newItem2 = NSMenuItem(title: NSLocalizedString("Open Link in %@", comment: "").format(appName!), action: #selector(openURLInApplicationFromMenu(_:)), keyEquivalent: "")
newItem2.target = self
newItem2.representedObject = frameURL
}
if newItem2 != nil {
menuItems.insert(newItem2!, atIndex: index)
}
menuItems.insert(newItem1, atIndex: index)
menuItems.insert(newItem0, atIndex: index)
break
}
}
}
if !selectedString.isEmpty {
var replaced = false
// Create items
let newItem0 = NSMenuItem(title: NSLocalizedString("Search in Google", comment: ""), action: #selector(searchStringFromMenu(_:)), keyEquivalent: "")
newItem0.target = self
newItem0.representedObject = selectedString
let newItem1 = NSMenuItem(title: NSLocalizedString("Open Google Search Results in New Tab", comment: ""), action: #selector(searchStringInNewTabFromMenu(_:)), keyEquivalent: "")
newItem1.target = self
newItem1.representedObject = selectedString
// Find an item
for (index, item) in reverse(Array(enumerate(menuItems))) {
if item.tag == 21 {
menuItems[index] = newItem0
menuItems.insert(newItem1, atIndex: index + 1)
replaced = true
}
}
if !replaced {
menuItems.insert(.separatorItem(), atIndex: 0)
menuItems.insert(newItem0, atIndex: 0)
menuItems.insert(newItem1, atIndex: 1)
}
}
if frame !== sender.mainFrame {
let newItem0 = NSMenuItem(title: NSLocalizedString("Open Frame in Current Frame", comment: ""), action: #selector(openFrameInCurrentFrameFromMenu(_:)), keyEquivalent: "")
let newItem1 = NSMenuItem(title: NSLocalizedString("Open Frame in New Tab", comment: ""), action: #selector(openURLInNewTabFromMenu(_:)), keyEquivalent: "")
newItem0.target = self
newItem1.target = self
newItem0.representedObject = frameURL
newItem1.representedObject = frameURL
menuItems.append(newItem0)
menuItems.append(newItem1)
}
return menuItems
}
// MARK: WebPolicyDelegate
func webView(webView: WebView, decidePolicyForMIMEType type: String, request: NSURLRequest, frame: WebFrame, decisionListener listener: WebPolicyDecisionListener) {
if WebView.canShowMIMETypeAsHTML(type) {
listener.use()
} else {
listener.download()
}
}
func webView(webView: WebView, decidePolicyForNavigationAction actionInformation: [NSObject: AnyObject], request: NSURLRequest, frame: WebFrame, decisionListener listener: WebPolicyDecisionListener) {
let URL = request.URL!
let modifierFlags = NSEventModifierFlags(rawValue: actionInformation[WebActionModifierFlagsKey] as! UInt)
let navigationType = WebNavigationType(rawValue: actionInformation[WebActionNavigationTypeKey] as! Int)!
switch navigationType {
case .LinkClicked:
if URL.hasWebScheme { // 'http', 'https', 'file'
if modifierFlags.contains(.CommandKeyMask) { // Command
var selection = true
let makeActiveFlag = NSUserDefaults.standardUserDefaults().boolForKey(kSBWhenNewTabOpensMakeActiveFlag)
// Make it active flag and Shift key mask
if makeActiveFlag == modifierFlags.contains(.ShiftKeyMask) {
selection = false
}
tabView.executeShouldAddNewItemForURL(URL, selection: selection)
listener.ignore()
} else if modifierFlags.contains(.AlternateKeyMask) { // Option
listener.download()
} else {
listener.use()
}
} else {
// Open URL in other application.
if NSWorkspace.sharedWorkspace().openURL(URL) {
listener.ignore()
} else {
listener.use()
}
}
case .FormSubmitted, .BackForward, .Reload, .FormResubmitted, .Other:
listener.use()
}
}
func webView(webView: WebView, decidePolicyForNewWindowAction actionInformation: [NSObject: AnyObject], request: NSURLRequest, newFrameName: String, decisionListener listener: WebPolicyDecisionListener) {
// open link in new tab
tabView.executeShouldAddNewItemForURL(request.URL!, selection: true)
}
func webView(webView: WebView, unableToImplementPolicyWithError error: NSError, frame: WebFrame) {
if let string = error.userInfo["NSErrorFailingURLStringKey"] as? String,
URL = NSURL(string: string) {
if URL.hasWebScheme { // 'http', 'https', 'file'
// Error
} else {
// open URL with other applications
if !NSWorkspace.sharedWorkspace().openURL(URL) {
// Error
}
}
}
}
// MARK: Actions
func addResourceIdentifier(identifier: SBWebResourceIdentifier) -> Bool {
if let anIdentifier = resourceIdentifiers.first({$0.request == identifier.request}) {
DebugLog("%@ contains request %@", __FUNCTION__, anIdentifier.request)
return false
}
resourceIdentifiers.append(identifier)
return true
}
func removeAllResourceIdentifiers() {
resourceIdentifiers.removeAll()
}
func backward(sender: AnyObject?) {
if webView.canGoBack {
webView.goBack(nil)
}
}
func forward(sender: AnyObject?) {
if webView.canGoForward {
webView.goForward(nil)
}
}
func openDocumentSource(sender: AnyObject?) {
let openPanel = SBOpenPanel()
openPanel.canChooseDirectories = false
openPanel.allowedFileTypes = ["app"]
if openPanel.runModal() == NSFileHandlingPanelOKButton {
let encodingName = webView.textEncodingName
var name = (pageTitle?.ifNotEmpty ?? NSLocalizedString("Untitled", comment: "")).stringByAppendingPathExtension("html")!
let filePath = NSTemporaryDirectory().stringByAppendingPathComponent(name)
let encoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding(encodingName.ifNotEmpty ?? kSBDefaultEncodingName))
do {
try documentSource!.writeToFile(filePath, atomically: true, encoding: encoding)
} catch let error as NSError {
SBRunAlertWithMessage(error.localizedDescription)
return
}
let appPath = openPanel.URL!.path!
if !NSWorkspace.sharedWorkspace().openFile(filePath, withApplication: appPath) {
SBRunAlertWithMessage(NSLocalizedString("Could not open in %@.", comment: "").format(appPath))
}
}
}
func saveDocumentSource(sender: AnyObject?) {
let encodingName = webView.textEncodingName
let name = ((pageTitle?.ifNotEmpty ?? NSLocalizedString("Untitled", comment: "")) as NSString).stringByAppendingPathExtension("html")!
let encoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding(encodingName.ifNotEmpty ?? kSBDefaultEncodingName))
let savePanel = NSSavePanel()
savePanel.canCreateDirectories = true
savePanel.nameFieldStringValue = name
if savePanel.runModal() == NSFileHandlingPanelOKButton {
do {
try documentSource!.writeToFile(savePanel.URL!.path!, atomically: true, encoding: encoding)
} catch let error as NSError {
SBRunAlertWithMessage(error.localizedDescription)
}
}
}
func removeFromTabView() {
destructWebView()
tabView!.removeTabViewItem(self)
}
func showErrorPageWithTitle(title: String, URLString: String, frame: WebFrame) {
let bundle = NSBundle.mainBundle()
let title = "<img src=\"Application.icns\" style=\"width:76px;height:76px;margin-right:10px;vertical-align:middle;\" alt=\"\">" + title
let searchURLString = "https://www.google.com/search?hl=ja&q=" + URLString
let searchMessage = NSLocalizedString("You can search the web for this URL.", comment: "")
var message = NSLocalizedString("Daybreak can’t open the page “%@”", comment: "").format(URLString)
message = "\(message)<br /><br />\(searchMessage)<br /><a href=\"\(searchURLString)\">\(URLString)</a>"
let path = bundle.pathForResource("Error", ofType: "html")!
if NSFileManager.defaultManager().fileExistsAtPath(path),
let HTMLString = try? String(contentsOfFile: path, encoding: NSUTF8StringEncoding) {
let formattedHTML = HTMLString.format(title, message)
// Load
frame.loadHTMLString(formattedHTML, baseURL: NSURL(fileURLWithPath: path))
}
}
// MARK: Menu Actions
func searchStringFromMenu(menuItem: NSMenuItem) {
if let searchString: String = menuItem.representedObject as? String {
tabView.executeShouldSearchString(searchString, newTab: false)
}
}
func searchStringInNewTabFromMenu(menuItem: NSMenuItem) {
if let searchString: String = menuItem.representedObject as? String {
tabView.executeShouldSearchString(searchString, newTab: true)
}
}
func openURLInApplicationFromMenu(menuItem: NSMenuItem) {
if let URL = menuItem.representedObject as? NSURL,
savedBundleIdentifier = NSUserDefaults.standardUserDefaults().stringForKey(kSBOpenApplicationBundleIdentifier) {
openURL(URL, inBundleIdentifier: savedBundleIdentifier)
}
}
func openURLInSelectedApplicationFromMenu(menuItem: NSMenuItem) {
if let URL = menuItem.representedObject as? NSURL {
var bundleIdentifier: String?
let panel = NSOpenPanel()
panel.canChooseFiles = true
panel.canChooseDirectories = false
panel.allowedFileTypes = ["app"]
panel.allowsMultipleSelection = false
panel.directoryURL = NSURL.fileURLWithPath("/Applications")
if panel.runModal() == NSFileHandlingPanelOKButton,
let bundle = NSBundle(URL: panel.URL!),
bundleIdentifier = bundle.bundleIdentifier
where openURL(URL, inBundleIdentifier: bundleIdentifier) {
NSUserDefaults.standardUserDefaults().setObject(bundleIdentifier, forKey: kSBOpenApplicationBundleIdentifier)
}
}
}
func openURL(URL: NSURL?, inBundleIdentifier bundleIdentifier: String?) -> Bool {
if (URL !! bundleIdentifier) != nil {
return NSWorkspace.sharedWorkspace().openURLs([URL!], withAppBundleIdentifier: bundleIdentifier!, options: .Default, additionalEventParamDescriptor:nil, launchIdentifiers: nil)
}
return false
}
func openFrameInCurrentFrameFromMenu(menuItem: NSMenuItem) {
if let URL = menuItem.representedObject as? NSURL {
self.URL = URL
}
}
func openURLInNewTabFromMenu(menuItem: NSMenuItem) {
if let URL = menuItem.representedObject as? NSURL {
tabView.executeShouldAddNewItemForURL(URL, selection: true)
}
}
}
class SBTabSplitView: NSSplitView {
var invisibleDivider = false
override var dividerThickness: CGFloat {
return invisibleDivider ? 0.0 : 5.0
}
override var dividerColor: NSColor {
return SBWindowBackColor
}
}
|
bsd-2-clause
|
230e3b5bd68af0b7aa35111c25e5b7d5
| 45.743985 | 318 | 0.6092 | 5.628346 | false | false | false | false |
csontosgabor/Twitter_Post
|
Twitter_Post/VideoTrimmerViewController.swift
|
1
|
11580
|
//
// GMVideoTrimmer.swift
// Photo
//
// Created by Gabor Csontos on 8/30/16.
// Copyright © 2016 GabeMajorszki. All rights reserved.
//
import UIKit
import AVFoundation
import Photos
import AssetsLibrary
import MobileCoreServices
@objc public protocol VideoTrimmerDelegate {
@objc optional func handleVideoConfirmButton(_ assetIdentifier: String?)
}
extension VideoTrimmerViewController: ICGVideoTrimmerDelegate {
func trimmerView(_ trimmerView: ICGVideoTrimmerView, didChangeLeftPosition startTime: CGFloat, rightPosition endTime: CGFloat) {
if startTime != self.startTime {
//then it moved the left position, we should rearrange the bar
self.seekVideoToPos(startTime)
}
self.startTime = startTime
self.stopTime = endTime
}
}
class VideoTrimmerViewController: UIViewController {
var isPlaying = false
var player: AVPlayer!
var playerItem: AVPlayerItem!
var playerLayer: AVPlayerLayer!
var videoPlaybackPosition: CGFloat!
var playbackTimeCheckerTimer: Timer!
var trimmerView: ICGVideoTrimmerView!
var videoPlayer = UIView()
var videoLayer = UIView()
var exportSession: AVAssetExportSession!
var asset: AVAsset!
var startTime: CGFloat!
var stopTime: CGFloat!
var dismissAnimated: Bool = true
var assetLocalId: String?
var tempURL: URL?
var error: NSError?
weak var delegate: VideoTrimmerDelegate?
var playButton = UIImageView()
var confirmButton: UIButton!
var cancelButton: UIButton!
public init(assetLocalId: String?, tempURL: URL?, dismissAnimated: Bool) {
self.assetLocalId = assetLocalId
self.tempURL = tempURL
self.dismissAnimated = dismissAnimated
super.init(nibName: nil, bundle: nil)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func loadAVAsset(_ identifier: String?){
guard let localidentifier = identifier else {
return
}
var fetcher = VideoFetcher()
.onSuccess { url in
//loading asset
DispatchQueue.main.async {
self.loadVideo(url)
}
}
.onFailure { error in
self.error = error
showAlertViewWithTitleAndText("Ups", message: error.localizedDescription, vc: self)
}
fetcher = fetcher.fetch(localidentifier)
}
func loadVideo(_ url: URL?) {
self.videoLayer.layer.sublayers?.forEach { $0.removeFromSuperlayer() }
guard let url = url else {
return
}
self.asset = AVAsset(url: url)
self.createTrimmerView(self.asset)
let item = AVPlayerItem(asset: self.asset)
self.player = AVPlayer(playerItem: item)
self.playerLayer = AVPlayerLayer(player: self.player)
self.playerLayer.frame = self.videoLayer.frame
self.playerLayer.contentsGravity = AVLayerVideoGravityResizeAspectFill
self.player!.actionAtItemEnd = .none
self.videoLayer.layer.addSublayer(self.playerLayer!)
self.videoPlaybackPosition = 0
let tap = UITapGestureRecognizer(target: self, action: #selector(self.tapOnVideoLayer))
self.view.addGestureRecognizer(tap)
self.tapOnVideoLayer(tap)
DispatchQueue.main.async {
// set properties for trimmer view
self.trimmerView.themeColor = .white
self.trimmerView.asset = self.asset
self.trimmerView.showsRulerView = true
self.trimmerView.trackerColor = .white
self.trimmerView.delegate = self
// important: reset subviews
self.trimmerView.resetSubviews()
}
}
func tapOnVideoLayer(_ tap: UITapGestureRecognizer) {
if self.isPlaying == false {
self.player.play()
showHidePlayButton(show: false)
self.startPlaybackTimeChecker()
} else {
self.player.pause()
showHidePlayButton(show: true)
self.stopPlaybackTimeChecker()
}
self.isPlaying = !self.isPlaying
self.trimmerView.hideTracker(!self.isPlaying)
}
func startPlaybackTimeChecker() {
self.stopPlaybackTimeChecker()
self.playbackTimeCheckerTimer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(onPlaybackTimeCheckerTimer), userInfo: nil, repeats: true)
}
func stopPlaybackTimeChecker() {
if (self.playbackTimeCheckerTimer != nil) {
self.playbackTimeCheckerTimer.invalidate()
self.playbackTimeCheckerTimer = nil
}
}
// MARK: - PlaybackTimeCheckerTimer
func onPlaybackTimeCheckerTimer() {
self.videoPlaybackPosition = CGFloat(CMTimeGetSeconds(self.player.currentTime()))
self.trimmerView.seek(toTime: CGFloat(CMTimeGetSeconds(self.player.currentTime())))
if self.videoPlaybackPosition >= self.stopTime {
self.videoPlaybackPosition = self.startTime
self.seekVideoToPos(self.startTime)
self.trimmerView.seek(toTime: self.startTime)
}
}
func seekVideoToPos(_ pos: CGFloat) {
self.videoPlaybackPosition = pos
let time = CMTimeMakeWithSeconds(Double(self.videoPlaybackPosition), self.player.currentTime().timescale)
self.player.seek(to: time, toleranceBefore: kCMTimeZero, toleranceAfter: kCMTimeZero)
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .black
setupView()
//load by assetId
if let asset = assetLocalId {
loadAVAsset(asset)
}
//load by tempurl -> cameraView or slowMotionVideo
if let tempurl = tempURL {
loadVideo(tempurl)
}
}
public override var prefersStatusBarHidden: Bool {
return true
}
public override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation {
return UIStatusBarAnimation.slide
}
func setupView() {
//videoPlayer x,y,w,h
if !videoPlayer.isDescendant(of: self.view) { self.view.addSubview(videoPlayer) }
videoLayer.frame = self.view.frame
videoPlayer.backgroundColor = UIColor.black
//videoLayer x,y,w,h
if !videoLayer.isDescendant(of: self.videoPlayer) { self.videoPlayer.addSubview(videoLayer) }
videoLayer.frame = self.view.frame
videoPlayer.backgroundColor = UIColor.clear
//playButton x,y,w,h
if !playButton.isDescendant(of: self.view) { self.view.addSubview(playButton) }
playButton.translatesAutoresizingMaskIntoConstraints = false
playButton.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true
playButton.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
playButton.widthAnchor.constraint(equalToConstant: 40).isActive = true
playButton.heightAnchor.constraint(equalToConstant: 40).isActive = true
playButton.contentMode = .scaleAspectFill
playButton.image = UIImage(named: "ic_swipe_play")
playButton.isHidden = true
setupButtons()
}
func setupButtons() {
//cancelButton
cancelButton = UIButton()
cancelButton.setTitle("Cancel", for: .normal)
cancelButton.setTitleColor(UIColor.white, for: .normal)
cancelButton.titleLabel?.font = UIFont.systemFont(ofSize: 18)
cancelButton.contentHorizontalAlignment = .left
//confirmButton
confirmButton = UIButton()
confirmButton.setTitle("Done", for: .normal)
confirmButton.setTitleColor(UIColor.white, for: .normal)
confirmButton.titleLabel?.font = UIFont.systemFont(ofSize: 18)
confirmButton.contentHorizontalAlignment = .right
confirmButton.action = { [weak self] in self?.confirmVideo() }
cancelButton.action = { [weak self] in self?.cancel() }
//confirmButton x,y,w,h
confirmButton.translatesAutoresizingMaskIntoConstraints = false
if !confirmButton.isDescendant(of: self.view) { self.view.addSubview(confirmButton) }
confirmButton.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: -10).isActive = true
confirmButton.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 12).isActive = true
confirmButton.widthAnchor.constraint(equalToConstant: 60).isActive = true
confirmButton.heightAnchor.constraint(equalToConstant: 30).isActive = true
//dismissButton x,y,w,h
cancelButton.translatesAutoresizingMaskIntoConstraints = false
if !cancelButton.isDescendant(of: self.view) { self.view.addSubview(cancelButton) }
cancelButton.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 10).isActive = true
cancelButton.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 12).isActive = true
cancelButton.widthAnchor.constraint(equalToConstant: 60).isActive = true
cancelButton.heightAnchor.constraint(equalToConstant: 30).isActive = true
}
func confirmVideo(){
//if no changes ->
// if CGFloat(self.asset.duration) == self.startTime && startTime == 0 {}
var save = SaveVideo()
.onSuccess { assetId in
DispatchQueue.main.async {
self.delegate?.handleVideoConfirmButton?(assetId)
self.cancel()
}
}
.onFailure { error in
self.error = error
showAlertViewWithTitleAndText("Ups", message: error.localizedDescription, vc: self)
}
save = save.save(self.asset, startTime: startTime, stopTime: stopTime)
}
func cancel() {
self.dismiss(animated: self.dismissAnimated, completion: {
if self.error == nil { self.player.pause() ; self.trimmerView.resetSubviews() }
})
}
func createTrimmerView(_ asset: AVAsset!){
trimmerView = ICGVideoTrimmerView(frame: CGRect(x: 0, y: self.view.frame.height - 100, width: self.view.frame.width, height: 100), asset: asset)
if !trimmerView.isDescendant(of: self.view) { self.view.addSubview(trimmerView) }
}
func showHidePlayButton(show: Bool){
if show == false {
UIView.animate(withDuration: 0.2, animations: {
self.playButton.isHidden = true
})
} else {
UIView.animate(withDuration: 0.2, animations: {
self.playButton.isHidden = false
})
}
}
}
|
mit
|
0d4cc7e4a79337e50d958e0c5d642903
| 29.551451 | 172 | 0.604802 | 5.299314 | false | false | false | false |
melling/SwiftCookBook
|
SwiftCookBook.playground/Pages/Date_Time.xcplaygroundpage/Contents.swift
|
1
|
8310
|
/*:
Swift Cookbook Date/Time Functions
Copy and Paste into a Swift Playground
Version: 20151020.01
- [h4labs Swift Cookbook](http://www.h4labs.com/dev/ios/swift_cookbook.html)
Some ideas came from [Perl](http://pleac.sourceforge.net/pleac_perl/arrays.html) and [Python](http://pleac.sourceforge.net/pleac_python/datesandtimes.html) Pleacs.
*/
import Foundation
//: Current Date/Time
var aDate: Date
let now = Date() // Current Date/Time
//: Date from String
let microsoftDateStr = "1986-03-13" // year-month-day
// Set date format
var dateFmt = DateFormatter()
dateFmt.timeZone = NSTimeZone.default
dateFmt.dateFormat = "yyyy-MM-dd"
microsoftDateStr
// Get Date for the given string
dateFmt.date(from: microsoftDateStr)
var microsoftIpoDate = dateFmt.date(from: microsoftDateStr)
print(microsoftIpoDate!)
microsoftIpoDate
//: Date Using Date Components
var components = DateComponents()
components.year = 1980
components.month = 12
components.day = 12
// Get Date given the above date components
var appleIpoDate = Calendar(identifier: .gregorian).date(from: components)
print(appleIpoDate!)
let ipoDates = [appleIpoDate, microsoftIpoDate]
ipoDates.first
func iPhoneBirthday() -> Date {
var components = DateComponents()
components.year = 2007
components.month = 1
components.day = 9
components.hour = 9
components.minute = 41
components.second = 0
let aDate = Calendar(identifier: .gregorian).date(from: components)
return aDate!
}
let bDay = iPhoneBirthday()
//: Standard Date Formats
/*:
# Standard Formats
Short | Short | 1/9/07, 9:41 AM
Short | Medium | 1/9/07, 9:41:00 AM
Short | Long | 1/9/07, 9:41:00 AM EST
Short | Full | 1/9/07, 9:41:00 AM Eastern Standard Time
Medium | Short | Jan 9, 2007, 9:41 AM
Medium | Medium | Jan 9, 2007, 9:41:00 AM
Medium | Long | Jan 9, 2007, 9:41:00 AM EST
Medium | Full | Jan 9, 2007, 9:41:00 AM Eastern Standard Time
Long | Short | January 9, 2007 at 9:41 AM
Long | Medium | January 9, 2007 at 9:41:00 AM
Long | Long | January 9, 2007 at 9:41:00 AM EST
Long | Full | January 9, 2007 at 9:41:00 AM Eastern Standard Time
Full | Short | Tuesday, January 9, 2007 at 9:41 AM
Full | Medium | Tuesday, January 9, 2007 at 9:41:00 AM
Full | Long | Tuesday, January 9, 2007 at 9:41:00 AM EST
Full | Full | Tuesday, January 9, 2007 at 9:41:00 AM Eastern Standard Time
*/
func formatDates(aDate:Date) {
let dateStyles:[DateFormatter.Style] = [.short, .medium, .long, .full]
let styleNames = ["", "Short", "Medium", "Long", "Full"]
let formatter = DateFormatter()
for style in dateStyles {
for style2 in dateStyles {
formatter.dateStyle = style
formatter.timeStyle = style2
let dateString = formatter.string(from: aDate)
let styleNames0 = "\(styleNames[Int(style.rawValue)]) | \(styleNames[Int(style2.rawValue)])"
print("\(styleNames0) | \(dateString)")
}
}
}
formatDates(aDate: bDay)
// Get Date for the given string
dateFmt.date(from: microsoftDateStr)
//: Current Year
func year() -> Int {
let date = Date()
let calendar = Calendar.current
let components = calendar.dateComponents([.year], from: date)
let year = components.year
return year!
}
//: Year/Month/Day returned as a tuple
func yearMonthDay(date:Date) -> (Int, Int, Int) {
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day], from: date)
let year = components.year
let month = components.month
let day = components.day
return (year!, month!, day!)
}
let (y,m,d) = yearMonthDay(date: Date())
//: Add leading zeros for month/day
print("The date is %d-%d-%d", y,m,d)
//: Day of Year
func dayOfYear() -> Int {
let date = Date() // now
let calendar = Calendar.current
let day = calendar.ordinality(of: .day, in: .year, for: date)
return day!
}
year()
dayOfYear()
//: Tomorrow
func tomorrow() -> Date {
var dateComponents = DateComponents()
dateComponents.setValue(1, for: .day);
let now = Date()
let tomorrow = Calendar.current.date(byAdding: dateComponents, to: now)
return tomorrow!
}
tomorrow()
//: Yesterday
func yesterday() -> Date {
var dateComponents = DateComponents()
dateComponents.setValue(-1, for: .day) // -1 days
let now = Date()
let yesterday = Calendar.current.date(byAdding: dateComponents, to: now)
return yesterday!
}
yesterday()
//: Day of Week
func dayOfWeek() -> Int {
let weekday:Int
let now = Date()
let gregorian = Calendar(identifier: .gregorian)
let x = gregorian.dateComponents([.weekdayOrdinal], from: now)
gregorian.firstWeekday
weekday = x.weekdayOrdinal!
return weekday
}
dayOfWeek()
//: Last day of month
func lastDayOfMonth(_ aDate:Date) -> Date {
let calendar = Calendar(identifier: .gregorian)
var components = calendar.dateComponents([.year , .month , .day],
from:aDate)
// components.month += 1 // Next month
components.day = 0 // Set the day to zero to get last day of prior month
let aDate = calendar.date(from: components)
return aDate!
}
lastDayOfMonth(now)
func lastDaysOfMonthForYear(year:Int) -> [Date] {
var result:[Date] = []
var components = DateComponents()
components.year = year
components.day = 1
for month in 1...12 {
components.month = month
let aDate = Calendar(identifier: .gregorian).date(from: components)
let d = lastDayOfMonth(aDate!)
result += [d]
}
return result
}
lastDaysOfMonthForYear(year: 2016)
//: Add n days - Can be positive or negative
func addDays(_ numDays:Int) -> Date {
var dateComponents = DateComponents()
dateComponents.setValue(numDays, for: .day) // -1 days
let now = Date()
let newDay = Calendar.current.date(byAdding: dateComponents, to: now)
// let newDay = Calendar.current.date(dateComponents, to: now, options: NSCalendar.Options(rawValue: 0))
return newDay!
}
addDays(1)
addDays(-1)
//: Last Saturday
//: Date Difference: Number of days between two dates
func dateDiff(startDate:Date, endDate:Date) -> Int {
let calendar = Calendar.current
// Ignore hours/minutes/seconds
let date1 = calendar.startOfDay(for: startDate)
let date2 = calendar.startOfDay(for: endDate)
// let unit = [Calendar.Component.day]
let components = calendar.dateComponents([.day], from: date1, to: date2)
return abs(components.day!)
}
dateDiff(startDate: lastDayOfMonth(now), endDate: now)
//: Leap Year
func isLeapYear(_ year: Int) -> Bool {
let isLeapYear = ((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0))
return isLeapYear
}
func isLeapYear(date: Date = Date()) -> Bool {
let calendar = Calendar.current
let components = calendar.dateComponents([.year], from: date)
let year = components.year
return isLeapYear(year!)
}
isLeapYear(1900) // false
isLeapYear(2000) // true
isLeapYear(2015) // false
isLeapYear(2016) // true
//let now0 = Date()
//isLeapYear(now0)
isLeapYear() // Default parameter is Date()
//: Date from Int YYYYMMDD
func dateFromInt(_ date:Int) -> Date {
let year = date / 10000
let month = date % 10000 / 100
let day = date % 100
var components = DateComponents()
components.year = year
components.month = month
components.day = day
let aDate = Calendar(identifier: .gregorian).date(from: components)
return aDate!
}
let d0 = dateFromInt(20160111)
//: Date to Int YYYYMMDD
func intFromDate(_ date:Date) -> Int {
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day], from: date)
let year = components.year
let month = components.month
let day = components.day
let intDate = year! * 10000 + month! * 100 + day!
return intDate
}
let d1 = intFromDate(Date())
//: Parsing Date Strings
//: Formatted Date Strings
|
cc0-1.0
|
033ac1bf0bf1003ff55ba080f9dab169
| 21.82967 | 164 | 0.645006 | 3.70486 | false | false | false | false |
flodolo/firefox-ios
|
Client/Frontend/Intro/IntroViewController.swift
|
1
|
11184
|
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0
import Foundation
import UIKit
import Shared
class IntroViewController: UIViewController, OnboardingViewControllerProtocol {
private var viewModel: IntroViewModel
private let profile: Profile
private var onboardingCards = [OnboardingCardViewController]()
var notificationCenter: NotificationProtocol = NotificationCenter.default
var didFinishFlow: (() -> Void)?
struct UX {
static let closeButtonSize: CGFloat = 30
static let closeHorizontalMargin: CGFloat = 24
static let closeVerticalMargin: CGFloat = 20
static let pageControlHeight: CGFloat = 40
static let pageControlBottomPadding: CGFloat = 8
}
// MARK: - Var related to onboarding
private lazy var closeButton: UIButton = .build { button in
button.setImage(UIImage(named: ImageIdentifiers.bottomSheetClose), for: .normal)
button.addTarget(self, action: #selector(self.closeOnboarding), for: .touchUpInside)
button.accessibilityIdentifier = AccessibilityIdentifiers.Onboarding.closeButton
}
private lazy var pageController: UIPageViewController = {
let pageVC = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal)
pageVC.dataSource = self
pageVC.delegate = self
return pageVC
}()
private lazy var pageControl: UIPageControl = .build { pageControl in
pageControl.currentPage = 0
pageControl.numberOfPages = self.viewModel.enabledCards.count
pageControl.currentPageIndicatorTintColor = UIColor.Photon.Blue50
pageControl.pageIndicatorTintColor = UIColor.Photon.LightGrey40
pageControl.isUserInteractionEnabled = false
pageControl.accessibilityIdentifier = AccessibilityIdentifiers.Onboarding.pageControl
}
// MARK: Initializer
init(viewModel: IntroViewModel, profile: Profile) {
self.viewModel = viewModel
self.profile = profile
super.init(nibName: nil, bundle: nil)
setupLayout()
setupNotifications(forObserver: self,
observing: [.DisplayThemeChanged])
applyTheme()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
notificationCenter.removeObserver(self)
}
override func viewDidLoad() {
super.viewDidLoad()
setupPageController()
}
// MARK: View setup
private func setupPageController() {
// Create onboarding card views
var cardViewController: OnboardingCardViewController
for cardType in viewModel.enabledCards {
if let viewModel = viewModel.getCardViewModel(cardType: cardType) {
if cardType == .wallpapers {
cardViewController = WallpaperCardViewController(viewModel: viewModel,
delegate: self)
} else {
cardViewController = OnboardingCardViewController(viewModel: viewModel,
delegate: self)
}
onboardingCards.append(cardViewController)
}
}
if let firstViewController = onboardingCards.first {
pageController.setViewControllers([firstViewController],
direction: .forward,
animated: true,
completion: nil)
}
}
private func setupLayout() {
addChild(pageController)
view.addSubview(pageController.view)
pageController.didMove(toParent: self)
view.addSubviews(pageControl, closeButton)
NSLayoutConstraint.activate([
pageControl.leadingAnchor.constraint(equalTo: view.leadingAnchor),
pageControl.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor,
constant: -UX.pageControlBottomPadding),
pageControl.trailingAnchor.constraint(equalTo: view.trailingAnchor),
closeButton.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor,
constant: UX.closeVerticalMargin),
closeButton.trailingAnchor.constraint(equalTo: view.trailingAnchor,
constant: -UX.closeHorizontalMargin),
closeButton.widthAnchor.constraint(equalToConstant: UX.closeButtonSize),
closeButton.heightAnchor.constraint(equalToConstant: UX.closeButtonSize),
])
}
@objc private func closeOnboarding() {
didFinishFlow?()
viewModel.sendCloseButtonTelemetry(index: pageControl.currentPage)
}
func getNextOnboardingCard(index: Int, goForward: Bool) -> OnboardingCardViewController? {
guard let index = viewModel.getNextIndex(currentIndex: index, goForward: goForward) else { return nil }
return onboardingCards[index]
}
// Used to programmatically set the pageViewController to show next card
func moveToNextPage(cardType: IntroViewModel.InformationCards) {
if let nextViewController = getNextOnboardingCard(index: cardType.rawValue, goForward: true) {
pageControl.currentPage = cardType.rawValue + 1
pageController.setViewControllers([nextViewController], direction: .forward, animated: false)
}
}
// Due to restrictions with PageViewController we need to get the index of the current view controller
// to calculate the next view controller
func getCardIndex(viewController: OnboardingCardViewController) -> Int? {
let cardType = viewController.viewModel.cardType
guard let index = viewModel.enabledCards.firstIndex(of: cardType) else { return nil }
return index
}
}
// MARK: UIPageViewControllerDataSource & UIPageViewControllerDelegate
extension IntroViewController: UIPageViewControllerDataSource, UIPageViewControllerDelegate {
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard let onboardingVC = viewController as? OnboardingCardViewController,
let index = getCardIndex(viewController: onboardingVC) else {
return nil
}
pageControl.currentPage = index
return getNextOnboardingCard(index: index, goForward: false)
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
guard let onboardingVC = viewController as? OnboardingCardViewController,
let index = getCardIndex(viewController: onboardingVC) else {
return nil
}
pageControl.currentPage = index
return getNextOnboardingCard(index: index, goForward: true)
}
}
extension IntroViewController: OnboardingCardDelegate {
func showNextPage(_ cardType: IntroViewModel.InformationCards) {
guard cardType != viewModel.enabledCards.last else {
self.didFinishFlow?()
return
}
moveToNextPage(cardType: cardType)
}
func primaryAction(_ cardType: IntroViewModel.InformationCards) {
switch cardType {
case .welcome, .wallpapers:
moveToNextPage(cardType: cardType)
case .signSync:
presentSignToSync()
default:
break
}
}
// Extra step to make sure pageControl.currentPage is the right index card
// because UIPageViewControllerDataSource call fails
func pageChanged(_ cardType: IntroViewModel.InformationCards) {
if let cardIndex = viewModel.enabledCards.firstIndex(of: cardType),
cardIndex != pageControl.currentPage {
pageControl.currentPage = cardIndex
}
}
private func presentSignToSync(_ fxaOptions: FxALaunchParams? = nil,
flowType: FxAPageType = .emailLoginFlow,
referringPage: ReferringPage = .onboarding) {
let singInSyncVC = FirefoxAccountSignInViewController.getSignInOrFxASettingsVC(fxaOptions,
flowType: flowType,
referringPage: referringPage,
profile: profile)
let controller: DismissableNavigationViewController
let buttonItem = UIBarButtonItem(title: .SettingsSearchDoneButton,
style: .plain,
target: self,
action: #selector(dismissSignInViewController))
let theme = BuiltinThemeName(rawValue: LegacyThemeManager.instance.current.name) ?? .normal
buttonItem.tintColor = theme == .dark ? UIColor.theme.homePanel.activityStreamHeaderButton : UIColor.Photon.Blue50
singInSyncVC.navigationItem.rightBarButtonItem = buttonItem
controller = DismissableNavigationViewController(rootViewController: singInSyncVC)
controller.onViewDismissed = {
self.closeOnboarding()
}
self.present(controller, animated: true)
}
@objc func dismissSignInViewController() {
dismiss(animated: true, completion: nil)
closeOnboarding()
}
}
// MARK: UIViewController setup
extension IntroViewController {
override var prefersStatusBarHidden: Bool {
return true
}
override var shouldAutorotate: Bool {
return false
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
// This actually does the right thing on iPad where the modally
// presented version happily rotates with the iPad orientation.
return .portrait
}
}
// MARK: - NotificationThemeable and Notifiable
extension IntroViewController: NotificationThemeable, Notifiable {
func handleNotifications(_ notification: Notification) {
switch notification.name {
case .DisplayThemeChanged:
applyTheme()
default:
break
}
}
func applyTheme() {
let theme = BuiltinThemeName(rawValue: LegacyThemeManager.instance.current.name) ?? .normal
let indicatorColor = theme == .dark ? UIColor.theme.homePanel.activityStreamHeaderButton : UIColor.Photon.Blue50
pageControl.currentPageIndicatorTintColor = indicatorColor
view.backgroundColor = LegacyThemeManager.instance.current.onboarding.backgroundColor
onboardingCards.forEach { cardViewController in
cardViewController.applyTheme()
}
}
}
|
mpl-2.0
|
38ad947b01dc98f44778897429240d0f
| 39.967033 | 149 | 0.648337 | 6.151815 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.