repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
711k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
vimeo/VIMVideoPlayer
|
refs/heads/v6.0.2
|
Examples/VimeoPlayer-iOS-Example/VimeoPlayer-iOS-Example/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// VIMVideoPlayer-iOS-Example
//
// Created by King, Gavin on 3/9/16.
// Copyright © 2016 Gavin King. 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 UIKit
class ViewController: UIViewController, VIMVideoPlayerViewDelegate
{
@IBOutlet weak var videoPlayerView: VIMVideoPlayerView!
@IBOutlet weak var slider: UISlider!
private var isScrubbing = false
override func viewDidLoad()
{
super.viewDidLoad()
self.setupVideoPlayerView()
self.setupSlider()
}
// MARK: Setup
private func setupVideoPlayerView()
{
self.videoPlayerView.player.looping = true
self.videoPlayerView.player.disableAirplay()
self.videoPlayerView.setVideoFillMode(AVLayerVideoGravityResizeAspectFill)
self.videoPlayerView.delegate = self
if let path = NSBundle.mainBundle().pathForResource("waterfall", ofType: "mp4")
{
self.videoPlayerView.player.setURL(NSURL(fileURLWithPath: path))
}
else
{
assertionFailure("Video file not found!")
}
}
private func setupSlider()
{
self.slider.addTarget(self, action: "scrubbingDidStart", forControlEvents: UIControlEvents.TouchDown)
self.slider.addTarget(self, action: "scrubbingDidChange", forControlEvents: UIControlEvents.ValueChanged)
self.slider.addTarget(self, action: "scrubbingDidEnd", forControlEvents: UIControlEvents.TouchUpInside)
self.slider.addTarget(self, action: "scrubbingDidEnd", forControlEvents: UIControlEvents.TouchUpOutside)
}
// MARK: Actions
@IBAction func didTapPlayPauseButton(sender: UIButton)
{
if self.videoPlayerView.player.playing
{
sender.selected = true
self.videoPlayerView.player.pause()
}
else
{
sender.selected = false
self.videoPlayerView.player.play()
}
}
// MARK: Scrubbing Actions
func scrubbingDidStart()
{
self.isScrubbing = true
self.videoPlayerView.player.startScrubbing()
}
func scrubbingDidChange()
{
guard let duration = self.videoPlayerView.player.player.currentItem?.duration
where self.isScrubbing == true else
{
return
}
let time = Float(CMTimeGetSeconds(duration)) * self.slider.value
self.videoPlayerView.player.scrub(time)
}
func scrubbingDidEnd()
{
self.videoPlayerView.player.stopScrubbing()
self.isScrubbing = false
}
// MARK: VIMVideoPlayerViewDelegate
func videoPlayerViewIsReadyToPlayVideo(videoPlayerView: VIMVideoPlayerView?)
{
self.videoPlayerView.player.play()
}
func videoPlayerView(videoPlayerView: VIMVideoPlayerView!, timeDidChange cmTime: CMTime)
{
guard let duration = self.videoPlayerView.player.player.currentItem?.duration
where self.isScrubbing == false else
{
return
}
let durationInSeconds = Float(CMTimeGetSeconds(duration))
let timeInSeconds = Float(CMTimeGetSeconds(cmTime))
self.slider.value = timeInSeconds / durationInSeconds
}
}
|
509663bf583ff90f192833b204d365bf
| 31.136691 | 113 | 0.659875 | false | false | false | false |
overtake/TelegramSwift
|
refs/heads/master
|
Telegram-Mac/ChatSendAsMenuItem.swift
|
gpl-2.0
|
1
|
//
// ChatSendAdMenuItem.swift
// Telegram
//
// Created by Mike Renoir on 18.01.2022.
// Copyright © 2022 Telegram. All rights reserved.
//
import Foundation
import TGUIKit
import Postbox
import SwiftSignalKit
import TelegramCore
class ContextSendAsMenuItem : ContextMenuItem {
private let peer: SendAsPeer
private let context: AccountContext
private let isSelected: Bool
init(peer: SendAsPeer, context: AccountContext, isSelected: Bool, handler: (() -> Void)? = nil) {
self.peer = peer
self.context = context
self.isSelected = isSelected
super.init(peer.peer.displayTitle.prefixWithDots(20), handler: handler)
}
required init(coder decoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func rowItem(presentation: AppMenu.Presentation, interaction: AppMenuBasicItem.Interaction) -> TableRowItem {
return ContextSendAsMenuRowItem(.zero, item: self, interaction: interaction, presentation: presentation, peer: peer, context: context, isSelected: isSelected)
}
}
private final class ContextSendAsMenuRowItem : AppMenuRowItem {
private let disposable = MetaDisposable()
fileprivate let context: AccountContext
fileprivate let statusLayout: TextViewLayout
fileprivate let peer: SendAsPeer
fileprivate let selected: Bool
init(_ initialSize: NSSize, item: ContextMenuItem, interaction: AppMenuBasicItem.Interaction, presentation: AppMenu.Presentation, peer: SendAsPeer, context: AccountContext, isSelected: Bool) {
self.peer = peer
self.context = context
self.selected = isSelected
let status: String
if peer.peer.isUser {
status = strings().chatSendAsPersonalAccount
} else {
if peer.peer.isGroup || peer.peer.isSupergroup {
status = strings().chatSendAsGroupCountable(Int(peer.subscribers ?? 0))
} else {
status = strings().chatSendAsChannelCountable(Int(peer.subscribers ?? 0))
}
}
self.statusLayout = .init(.initialize(string: status, color: presentation.disabledTextColor, font: .normal(.text)))
super.init(initialSize, item: item, interaction: interaction, presentation: presentation)
let signal:Signal<(CGImage?, Bool), NoError>
let peer = self.peer.peer
signal = peerAvatarImage(account: context.account, photo: .peer(peer, peer.smallProfileImage, peer.displayLetters, nil), displayDimensions: NSMakeSize(25 * System.backingScale, 25 * System.backingScale), font: .avatar(20), genCap: true, synchronousLoad: false) |> deliverOnMainQueue
disposable.set(signal.start(next: { [weak item] image, _ in
if let image = image {
item?.image = NSImage(cgImage: image, size: NSMakeSize(25, 25))
}
}))
}
override var imageSize: CGFloat {
return 25
}
deinit {
disposable.dispose()
}
override var textSize: CGFloat {
return max(text.layoutSize.width, statusLayout.layoutSize.width) + leftInset * 2 + innerInset * 2
}
override var effectiveSize: NSSize {
var size = super.effectiveSize
if peer.isPremiumRequired && !context.isPremium {
size.width += 15
}
return size
}
override var height: CGFloat {
return 35
}
override func makeSize(_ width: CGFloat = CGFloat.greatestFiniteMagnitude, oldWidth: CGFloat = 0) -> Bool {
_ = super.makeSize(width, oldWidth: oldWidth)
self.statusLayout.measure(width: width - leftInset * 2 - innerInset * 2)
return true
}
override func viewClass() -> AnyClass {
return ContextAccountMenuRowView.self
}
}
private final class ContextAccountMenuRowView : AppMenuRowView {
private let statusView: TextView = TextView()
private var borderView: View?
private var lockView: ImageView?
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
addSubview(statusView)
statusView.userInteractionEnabled = false
statusView.isSelectable = false
}
override func layout() {
super.layout()
guard let item = item as? ContextSendAsMenuRowItem else {
return
}
statusView.setFrameOrigin(NSMakePoint(textX, textY + 14))
if let borderView = borderView {
borderView.frame = imageFrame.insetBy(dx: -2, dy: -2)
}
if let lockView = lockView {
lockView.setFrameOrigin(textX + item.text.layoutSize.width, textY)
}
}
override func set(item: TableRowItem, animated: Bool = false) {
super.set(item: item, animated: animated)
guard let item = item as? ContextSendAsMenuRowItem else {
return
}
statusView.update(item.statusLayout)
if item.peer.isPremiumRequired && !item.context.isPremium {
let current: ImageView
if let view = self.lockView {
current = view
} else {
current = ImageView()
addSubview(current)
self.lockView = current
}
current.image = NSImage(named: "Icon_EmojiLock")?.precomposed(item.presentation.disabledTextColor)
current.sizeToFit()
} else if let view = self.lockView {
performSubviewRemoval(view, animated: animated)
self.lockView = nil
}
if item.selected {
let current: View
if let view = borderView {
current = view
} else {
current = View()
self.borderView = current
addSubview(current)
}
current.setFrameSize(NSMakeSize(item.imageSize + 4, item.imageSize + 4))
current.layer?.cornerRadius = current.frame.height / 2
current.layer?.borderWidth = 1
current.layer?.borderColor = item.presentation.colors.accent.cgColor
} else if let view = borderView {
performSubviewRemoval(view, animated: animated)
}
}
override var textY: CGFloat {
return 2
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
497f7075df51f4f10653d0c3aa062fde
| 33.315789 | 290 | 0.617485 | false | false | false | false |
yrchen/edx-app-ios
|
refs/heads/master
|
Source/JSONFormBuilderTextEditor.swift
|
apache-2.0
|
1
|
//
// JSONFormBuilderTextEditor.swift
// edX
//
// Created by Michael Katz on 10/1/15.
// Copyright © 2015 edX. All rights reserved.
//
import Foundation
class JSONFormBuilderTextEditorViewController: UIViewController {
let textView = OEXPlaceholderTextView()
var text: String { return textView.text }
var doneEditing: ((value: String)->())?
init(text: String?, placeholder: String?) {
super.init(nibName: nil, bundle: nil)
self.view = UIView()
self.view.backgroundColor = UIColor.whiteColor()
textView.textContainer.lineFragmentPadding = 0
textView.textContainerInset = OEXStyles.sharedStyles().standardTextViewInsets
textView.typingAttributes = OEXStyles.sharedStyles().textAreaBodyStyle.attributes
textView.placeholderTextColor = OEXStyles.sharedStyles().neutralLight()
textView.textColor = OEXStyles.sharedStyles().neutralBlackT()
textView.text = text ?? ""
if let placeholder = placeholder {
textView.placeholder = placeholder
}
textView.delegate = self
setupViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupViews() {
view.addSubview(textView)
textView.snp_makeConstraints { (make) -> Void in
make.top.equalTo(view.snp_topMargin)
make.leading.equalTo(view.snp_leadingMargin)
make.trailing.equalTo(view.snp_trailingMargin)
make.bottom.equalTo(view.snp_bottomMargin)
}
}
override func willMoveToParentViewController(parent: UIViewController?) {
if parent == nil { //removing from the hierarchy
doneEditing?(value: textView.text)
}
}
}
extension JSONFormBuilderTextEditorViewController : UITextViewDelegate {
func textViewShouldEndEditing(textView: UITextView) -> Bool {
textView.resignFirstResponder()
return true
}
}
|
cbd2a088f561255a1b683b3093a91a0e
| 29.043478 | 89 | 0.648649 | false | false | false | false |
hanzhuzi/XRVideoPlayer-master
|
refs/heads/master
|
XRPlayer/Source/XRPlayerMarcos.swift
|
mit
|
1
|
//
// XRPlayerMarcos.swift
// XRPlayer
//
// Created by 徐冉 on 2019/7/30.
// Copyright © 2019 QK. All rights reserved.
//
import UIKit
import Foundation
// MARK: - Print
#if DEBUG
func XRPlayerLog(_ items: Any...) {
print(items)
}
#else
func XRPlayerLog(_ items: Any...) {
}
#endif
//MARK: - 屏幕尺寸
// iPhone5, 5S,5C,SE
public func xrPlayer_iSiPhone5_5S_5C_SE() -> Bool {
return (UIScreen.instancesRespond(to: #selector(getter: UIScreen.currentMode)) ? __CGSizeEqualToSize(UIScreen.main.currentMode!.size, CGSize(width: 640, height: 1136)) : false) || (UIScreen.instancesRespond(to: #selector(getter: UIScreen.currentMode)) ? __CGSizeEqualToSize(UIScreen.main.currentMode!.size, CGSize(width: 1136, height: 640)) : false)
}
// iPhone6,6S,7,8
public func xrPlayer_iSiPhone6_6S_7_8() -> Bool {
return (UIScreen.instancesRespond(to: #selector(getter: UIScreen.currentMode)) ? __CGSizeEqualToSize(UIScreen.main.currentMode!.size, CGSize(width: 750, height: 1334)) : false) || (UIScreen.instancesRespond(to: #selector(getter: UIScreen.currentMode)) ? __CGSizeEqualToSize(UIScreen.main.currentMode!.size, CGSize(width: 1334, height: 750)) : false)
}
// iPhone6, 7, 8,Plus
public func xrPlayer_iSiPhone6_7_8Plus() -> Bool {
return (UIScreen.instancesRespond(to: #selector(getter: UIScreen.currentMode)) ? __CGSizeEqualToSize(UIScreen.main.currentMode!.size, CGSize(width: 1242, height: 2208)) : false) || (UIScreen.instancesRespond(to: #selector(getter: UIScreen.currentMode)) ? __CGSizeEqualToSize(UIScreen.main.currentMode!.size, CGSize(width: 2208, height: 1242)) : false)
}
// iPhoneX, XS
public func xrPlayer_iSiPhoneX_XS() -> Bool {
return (UIScreen.instancesRespond(to: #selector(getter: UIScreen.currentMode)) ? __CGSizeEqualToSize(UIScreen.main.currentMode!.size, CGSize(width: 1125, height: 2436)) : false) || (UIScreen.instancesRespond(to: #selector(getter: UIScreen.currentMode)) ? __CGSizeEqualToSize(UIScreen.main.currentMode!.size, CGSize(width: 2436, height: 1125)) : false)
}
// iPhoneXR
public func xrPlayer_iSiPhoneXR() -> Bool {
return (UIScreen.instancesRespond(to: #selector(getter: UIScreen.currentMode)) ? __CGSizeEqualToSize(UIScreen.main.currentMode!.size, CGSize(width: 828, height: 1792)) : false) || (UIScreen.instancesRespond(to: #selector(getter: UIScreen.currentMode)) ? __CGSizeEqualToSize(UIScreen.main.currentMode!.size, CGSize(width: 1792, height: 828)) : false)
}
// iPhoneXS_Max
public func xrPlayer_iSiPhoneXS_Max() -> Bool {
return (UIScreen.instancesRespond(to: #selector(getter: UIScreen.currentMode)) ? __CGSizeEqualToSize(UIScreen.main.currentMode!.size, CGSize(width: 1242, height: 2688)) : false) || (UIScreen.instancesRespond(to: #selector(getter: UIScreen.currentMode)) ? __CGSizeEqualToSize(UIScreen.main.currentMode!.size, CGSize(width: 2688, height: 1242)) : false)
}
// 是否有齐刘海和虚拟指示器
public func xrPlayer_iSiPhoneXSerries() -> Bool {
var isiPhoneXSerries: Bool = false
if UIDevice.current.userInterfaceIdiom != .phone {
isiPhoneXSerries = false
}
if #available(iOS 11.0, *) {
if let mainWindow = UIApplication.shared.delegate?.window {
if mainWindow!.safeAreaInsets.bottom > 0 {
isiPhoneXSerries = true
}
}
}
isiPhoneXSerries = xrPlayer_iSiPhoneX_XS() || xrPlayer_iSiPhoneXR() || xrPlayer_iSiPhoneXS_Max()
return isiPhoneXSerries
}
// 加载XRPlayer Bundle中的图片
func xrplayer_imageForBundleResource(imageName: String, bundleClass: AnyClass) -> UIImage? {
let moduleBundle = Bundle(for: bundleClass)
if let resourceUrl = moduleBundle.resourceURL?.appendingPathComponent("XRPlayer.bundle") {
let resourceBundle = Bundle(url: resourceUrl)
let resImage = UIImage(named: imageName, in: resourceBundle, compatibleWith: nil)
return resImage
}
return nil
}
//MARK: - 颜色
// 颜色(RGB)
public func xrplayer_RGBA (r:CGFloat, g:CGFloat, b:CGFloat, a:CGFloat) -> UIColor
{
return UIColor (red: r/255.0, green: g/255.0, blue: b/255.0, alpha: a)
}
public func xrplayer_RGBCOLOR(r:CGFloat, g:CGFloat, b:CGFloat) -> UIColor
{
return UIColor (red: r/255.0, green: g/255.0, blue: b/255.0, alpha: 1)
}
//RGB颜色转换(16进制)
public func xrplayer_UIColorFromRGB(hexRGB: UInt32) -> UIColor
{
let redComponent = (hexRGB & 0xFF0000) >> 16
let greenComponent = (hexRGB & 0x00FF00) >> 8
let blueComponent = hexRGB & 0x0000FF
return xrplayer_RGBCOLOR(r: CGFloat(redComponent), g: CGFloat(greenComponent), b: CGFloat(blueComponent))
}
///延迟 afTime, 回调 block(in main 在主线程)
public func xrplayer_dispatch_after_in_main(_ afTime: TimeInterval,block: @escaping ()->()) {
let popTime = DispatchTime.now() + Double(Int64(afTime * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) // 1s * popTime
if popTime > DispatchTime(uptimeNanoseconds: 0) {
DispatchQueue.main.asyncAfter(deadline: popTime, execute: block)
}
}
|
8e8d31957a70137a8df78a52b16e2b56
| 39.08 | 355 | 0.7002 | false | false | false | false |
ZeldaIV/TDC2015-FP
|
refs/heads/master
|
Pods/RxBlocking/RxBlocking/Observable+Blocking.swift
|
mit
|
12
|
//
// Observable+Blocking.swift
// RxBlocking
//
// Created by Krunoslav Zaher on 7/12/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if !RX_NO_MODULE
import RxSwift
#endif
extension ObservableType {
/**
Blocks current thread until sequence terminates.
If sequence terminates with error, terminating error will be thrown.
- returns: All elements of sequence.
*/
public func toArray() throws -> [E] {
let condition = NSCondition()
var elements = [E]()
var error: ErrorType?
var ended = false
self.subscribe { e in
switch e {
case .Next(let element):
elements.append(element)
case .Error(let e):
error = e
condition.lock()
ended = true
condition.signal()
condition.unlock()
case .Completed:
condition.lock()
ended = true
condition.signal()
condition.unlock()
}
}
condition.lock()
while !ended {
condition.wait()
}
condition.unlock()
if let error = error {
throw error
}
return elements
}
}
extension ObservableType {
/**
Blocks current thread until sequence produces first element.
If sequence terminates with error before producing first element, terminating error will be thrown.
- returns: First element of sequence. If sequence is empty `nil` is returned.
*/
public func first() throws -> E? {
let condition = NSCondition()
var element: E?
var error: ErrorType?
var ended = false
let d = SingleAssignmentDisposable()
d.disposable = self.subscribe { e in
switch e {
case .Next(let e):
if element == nil {
element = e
}
break
case .Error(let e):
error = e
default:
break
}
condition.lock()
ended = true
condition.signal()
condition.unlock()
}
condition.lock()
while !ended {
condition.wait()
}
d.dispose()
condition.unlock()
if let error = error {
throw error
}
return element
}
}
extension ObservableType {
/**
Blocks current thread until sequence terminates.
If sequence terminates with error, terminating error will be thrown.
- returns: Last element in the sequence. If sequence is empty `nil` is returned.
*/
public func last() throws -> E? {
let condition = NSCondition()
var element: E?
var error: ErrorType?
var ended = false
let d = SingleAssignmentDisposable()
d.disposable = self.subscribe { e in
switch e {
case .Next(let e):
element = e
return
case .Error(let e):
error = e
default:
break
}
condition.lock()
ended = true
condition.signal()
condition.unlock()
}
condition.lock()
while !ended {
condition.wait()
}
d.dispose()
condition.unlock()
if let error = error {
throw error
}
return element
}
}
|
037d1cba9ab56362734ea340c6168382
| 22.176829 | 103 | 0.474737 | false | false | false | false |
BrisyIOS/TodayNewsSwift3.0
|
refs/heads/master
|
TodayNews-Swift3.0/TodayNews-Swift3.0/Classes/Home/View/HomeThreeImageCell.swift
|
apache-2.0
|
1
|
//
// HomeThreeImageCell.swift
// TodayNews-Swift3.0
//
// Created by zhangxu on 2016/10/26.
// Copyright © 2016年 zhangxu. All rights reserved.
//
import UIKit
class HomeThreeImageCell: HomeListCommonCell {
var homeListModel: HomeListModel? {
didSet {
// 取出可选类型中的数据
guard let homeListModel = homeListModel else {
return;
}
// 给titleLabel 赋值
if let title = homeListModel.title {
titleLabel.text = title;
homeListModel.titleLabelH = calculateLabelHeight(text: title, labelW: kScreenWidth - CGFloat(2) * 15, fontSize: 17);
}
// 时间
if let publish_time = homeListModel.publish_time {
timeLabel.text = changeTimestampToPublicTime(timestamp: publish_time);
homeListModel.timeLabelW = calculateWidth(title: timeLabel.text!, fontSize: 12);
}
// 头像
if let source_avatar = homeListModel.source_avatar {
if let source = homeListModel.source {
nameLabel.text = source;
homeListModel.nameLabelW = calculateWidth(title: source, fontSize: 12);
}
avatarImageView.zx_setImageWithURL(source_avatar);
}
if let mediaInfo = homeListModel.media_info {
nameLabel.text = mediaInfo.name;
avatarImageView.zx_setImageWithURL(mediaInfo.avatar_url);
}
// 评论
if let comment = homeListModel.comment_count {
commentLabel.text = (comment >= 10000) ? "\(comment/10000)万评论" : "\(comment)评论";
homeListModel.commentLabelW = calculateWidth(title: commentLabel.text!, fontSize: 12);
}
// 三张图
if let image_list = homeListModel.image_list {
if image_list.count != 0 {
for index in 0..<image_list.count {
let imageViewArray = [firstImage, secondImage, thirdImage];
let imageListModel = image_list[index];
var imageURL: String = "";
let url = imageListModel.url ?? "";
if url.hasSuffix(".webp") {
let range = url.range(of: ".webp")!;
imageURL = url.substring(to: range.lowerBound);
} else {
imageURL = url;
}
imageViewArray[index].zx_setImageWithURL(imageURL);
}
}
}
// 更新子控件的frame
layoutIfNeeded();
setNeedsLayout();
}
};
// 三张图
lazy var firstImage: UIImageView = UIImageView();
lazy var secondImage: UIImageView = UIImageView();
lazy var thirdImage: UIImageView = UIImageView();
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier);
// 添加第一张图品
contentView.addSubview(firstImage);
// 添加第二张图片
contentView.addSubview(secondImage);
// 添加第三张图片
contentView.addSubview(thirdImage);
}
// 更新子控件的frame
override func layoutSubviews() {
super.layoutSubviews();
guard let homeListModel = homeListModel else {
return;
}
let width = bounds.size.width;
// 设置titleLabel 的frame
let titleLabelX = realValue(15);
let titleLabelY = realValue(50/3);
let titleLabelW = width - titleLabelX * CGFloat(2);
let titleLabelH = homeListModel.titleLabelH;
titleLabel.frame = CGRect(x: titleLabelX, y: titleLabelY, width: titleLabelW, height: titleLabelH);
// 设置firstImage 的frame
let firstImageX = titleLabelX;
let firstImageY = titleLabel.frame.maxY + realValue(11);
let firstImageW = realValue(372/3);
let firstImageH = realValue(210/3);
firstImage.frame = CGRect(x: firstImageX, y: firstImageY, width: firstImageW, height: firstImageH);
// 设置secondImage 的frame
let secondImageX = firstImage.frame.maxX + realValue(20/3);
let secondImageY = firstImageY;
let secondImageW = firstImageW;
let secondImageH = firstImageH;
secondImage.frame = CGRect(x: secondImageX, y: secondImageY, width: secondImageW, height: secondImageH);
// 设置thirdImage 的frame
let thirdImageX = secondImage.frame.maxX + realValue(20/3);
let thirdImageY = firstImageY;
let thirdImageW = firstImageW;
let thirdImageH = firstImageH;
thirdImage.frame = CGRect(x: thirdImageX, y: thirdImageY, width: thirdImageW, height: thirdImageH);
// 设置avatarImageView 的frame
let avatarImageViewX = titleLabelX;
let avatarImageViewY = firstImage.frame.maxY + realValue(10);
let avatarImageViewW = realValue(49/3);
let avatarImageViewH = avatarImageViewW;
avatarImageView.frame = CGRect(x: avatarImageViewX, y: avatarImageViewY, width: avatarImageViewW, height: avatarImageViewH);
// 设置nameLabel 的frame
let nameLabelX = avatarImageView.frame.maxX + realValue(5);
let nameLabelY = firstImage.frame.maxY + realValue(36/3);
let nameLabelW = homeListModel.nameLabelW;
let nameLabelH = realValue(12);
nameLabel.frame = CGRect(x: nameLabelX, y: nameLabelY, width: nameLabelW, height: nameLabelH);
// 设置commentLabel 的frame
let commentLabelX = nameLabel.frame.maxX + realValue(5);
let commentLabelY = nameLabelY;
let commentLabelW = homeListModel.commentLabelW;
let commentLabelH = nameLabelH;
commentLabel.frame = CGRect(x: commentLabelX, y: commentLabelY, width: commentLabelW, height: commentLabelH);
// 设置timeLabel 的frame
let timeLabelX = commentLabel.frame.maxX + realValue(5);
let timeLabelY = nameLabelY;
let timeLabelW = homeListModel.timeLabelW;
let timeLabelH = nameLabelH;
timeLabel.frame = CGRect(x: timeLabelX, y: timeLabelY, width: timeLabelW, height: timeLabelH);
// 设置stickLabel 的frame
let stickLabelX = timeLabel.frame.maxX + realValue(5);
let stickLabelY = nameLabelY;
let stickLabelW = homeListModel.stickLabelW;
let stickLabelH = nameLabelH;
stickLabel.frame = CGRect(x: stickLabelX, y: stickLabelY, width: stickLabelW, height: stickLabelH);
// 设置圆角
let cornerRadii = CGSize(width: realValue(49/3/2), height: realValue(49/3/2));
setRoundCorner(currentView: avatarImageView, cornerRadii: cornerRadii);
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
|
f4b714371e3aabfcfb5b0460a30ff3f4
| 38.617486 | 132 | 0.584414 | false | false | false | false |
eRGoon/RGPageViewController
|
refs/heads/master
|
RGPageViewController/RGPageViewController/Source/Extensions/RGPageViewController+UICollectionViewDelegate.swift
|
mit
|
1
|
//
// RGPageViewController+UICollectionViewDelegate.swift
// RGPageViewController
//
// Created by Ronny Gerasch on 23.01.17.
// Copyright © 2017 Ronny Gerasch. All rights reserved.
//
import Foundation
// MARK: - UICollectionViewDelegate
extension RGPageViewController: UICollectionViewDelegate {
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if currentTabIndex != indexPath.row {
selectTabAtIndex(indexPath.row, updatePage: true)
}
}
public func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if let tabView = cell.contentView.subviews.first as? RGTabView {
if indexPath.row == currentTabIndex {
tabView.selected = true
} else {
tabView.selected = false
}
}
}
}
|
e01646be481ebcd969b30b6622c85850
| 30.142857 | 138 | 0.727064 | false | false | false | false |
JaSpa/swift
|
refs/heads/master
|
test/PrintAsObjC/mixed-framework-fwd.swift
|
apache-2.0
|
10
|
// RUN: rm -rf %t && mkdir -p %t
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -F %S/Inputs/ -module-name Mixed -import-underlying-module %s -typecheck -emit-objc-header-path %t/mixed.h
// RUN: %FileCheck -check-prefix=CHECK -check-prefix=NO-IMPORT %s < %t/mixed.h
// RUN: %check-in-clang -F %S/Inputs/ %t/mixed.h
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -module-name Mixed -import-objc-header %S/Inputs/Mixed.framework/Headers/Mixed.h %s -typecheck -emit-objc-header-path %t/mixed-header.h
// RUN: %FileCheck -check-prefix=CHECK -check-prefix=NO-IMPORT %s < %t/mixed-header.h
// RUN: %check-in-clang -include %S/Inputs/Mixed.framework/Headers/Mixed.h %t/mixed-header.h
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -F %S/Inputs/ -module-name Mixed -import-underlying-module %s -typecheck -emit-objc-header-path %t/mixed-proto.h -DREQUIRE
// RUN: %FileCheck -check-prefix=CHECK -check-prefix=FRAMEWORK %s < %t/mixed-proto.h
// RUN: %check-in-clang -F %S/Inputs/ %t/mixed-proto.h
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -module-name Mixed -import-objc-header %S/Inputs/Mixed.framework/Headers/Mixed.h %s -typecheck -emit-objc-header-path %t/mixed-header-proto.h -DREQUIRE
// RUN: %FileCheck -check-prefix=CHECK -check-prefix=HEADER %s < %t/mixed-header-proto.h
// RUN: %check-in-clang -include %S/Inputs/Mixed.framework/Headers/Mixed.h %t/mixed-header-proto.h
// REQUIRES: objc_interop
// CHECK-LABEL: #if defined(__has_feature) && __has_feature(modules)
// CHECK-NEXT: @import Foundation;
// CHECK-NEXT: #endif
// NO-IMPORT-NOT: #import
// NO-IMPORT: @protocol CustomProto;
// FRAMEWORK-LABEL: #import <Mixed/Mixed.h>
// HEADER-NOT: __ObjC
// HEADER: #import "{{.*}}Mixed.h"
// HEADER-NOT: __ObjC
import Foundation
public class Dummy: NSNumber {
public func getProto() -> CustomProto? {
return nil
}
}
#if REQUIRE
extension Dummy: CustomProto {}
#endif
|
4a107a9e337dd3dfad5c9d2ca26a0901
| 45.333333 | 213 | 0.710175 | false | false | false | false |
dduan/swift
|
refs/heads/master
|
benchmark/single-source/NSError.swift
|
apache-2.0
|
2
|
//===--- NSError.swift ----------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TestsUtils
import Foundation
protocol P {
func buzz() throws -> Int
}
class K : P {
init() {}
func buzz() throws -> Int {
throw NSError(domain: "AnDomain", code: 42, userInfo: nil)
}
}
class G : K {
override init() {}
override func buzz() throws -> Int { return 0 }
}
func caller(x : P) throws {
try x.buzz()
}
@inline(never)
public func run_NSError(N: Int) {
for _ in 1...N*1000 {
let k = K()
let g = G()
do {
try caller(g)
try caller(k)
} catch _ {
continue
}
}
}
|
6b23a379f28c85d1fd96700dc4d00dd2
| 21.333333 | 80 | 0.534515 | false | false | false | false |
Glucosio/glucosio-ios
|
refs/heads/develop
|
Pods/Charts/Source/Charts/Renderers/BubbleChartRenderer.swift
|
apache-2.0
|
4
|
//
// BubbleChartRenderer.swift
// Charts
//
// Bubble chart implementation:
// Copyright 2015 Pierre-Marc Airoldi
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
#if !os(OSX)
import UIKit
#endif
open class BubbleChartRenderer: BarLineScatterCandleBubbleRenderer
{
@objc open weak var dataProvider: BubbleChartDataProvider?
@objc public init(dataProvider: BubbleChartDataProvider, animator: Animator, viewPortHandler: ViewPortHandler)
{
super.init(animator: animator, viewPortHandler: viewPortHandler)
self.dataProvider = dataProvider
}
open override func drawData(context: CGContext)
{
guard
let dataProvider = dataProvider,
let bubbleData = dataProvider.bubbleData
else { return }
for set in bubbleData.dataSets as! [IBubbleChartDataSet] where set.isVisible
{
drawDataSet(context: context, dataSet: set)
}
}
private func getShapeSize(
entrySize: CGFloat,
maxSize: CGFloat,
reference: CGFloat,
normalizeSize: Bool) -> CGFloat
{
let factor: CGFloat = normalizeSize
? ((maxSize == 0.0) ? 1.0 : sqrt(entrySize / maxSize))
: entrySize
let shapeSize: CGFloat = reference * factor
return shapeSize
}
private var _pointBuffer = CGPoint()
private var _sizeBuffer = [CGPoint](repeating: CGPoint(), count: 2)
@objc open func drawDataSet(context: CGContext, dataSet: IBubbleChartDataSet)
{
guard let dataProvider = dataProvider else { return }
let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency)
let phaseY = animator.phaseY
_xBounds.set(chart: dataProvider, dataSet: dataSet, animator: animator)
let valueToPixelMatrix = trans.valueToPixelMatrix
_sizeBuffer[0].x = 0.0
_sizeBuffer[0].y = 0.0
_sizeBuffer[1].x = 1.0
_sizeBuffer[1].y = 0.0
trans.pointValuesToPixel(&_sizeBuffer)
context.saveGState()
defer { context.restoreGState() }
let normalizeSize = dataSet.isNormalizeSizeEnabled
// calcualte the full width of 1 step on the x-axis
let maxBubbleWidth: CGFloat = abs(_sizeBuffer[1].x - _sizeBuffer[0].x)
let maxBubbleHeight: CGFloat = abs(viewPortHandler.contentBottom - viewPortHandler.contentTop)
let referenceSize: CGFloat = min(maxBubbleHeight, maxBubbleWidth)
for j in stride(from: _xBounds.min, through: _xBounds.range + _xBounds.min, by: 1)
{
guard let entry = dataSet.entryForIndex(j) as? BubbleChartDataEntry else { continue }
_pointBuffer.x = CGFloat(entry.x)
_pointBuffer.y = CGFloat(entry.y * phaseY)
_pointBuffer = _pointBuffer.applying(valueToPixelMatrix)
let shapeSize = getShapeSize(entrySize: entry.size, maxSize: dataSet.maxSize, reference: referenceSize, normalizeSize: normalizeSize)
let shapeHalf = shapeSize / 2.0
guard
viewPortHandler.isInBoundsTop(_pointBuffer.y + shapeHalf),
viewPortHandler.isInBoundsBottom(_pointBuffer.y - shapeHalf),
viewPortHandler.isInBoundsLeft(_pointBuffer.x + shapeHalf)
else { continue }
guard viewPortHandler.isInBoundsRight(_pointBuffer.x - shapeHalf) else { break }
let color = dataSet.color(atIndex: Int(entry.x))
let rect = CGRect(
x: _pointBuffer.x - shapeHalf,
y: _pointBuffer.y - shapeHalf,
width: shapeSize,
height: shapeSize
)
context.setFillColor(color.cgColor)
context.fillEllipse(in: rect)
}
}
open override func drawValues(context: CGContext)
{
guard let
dataProvider = dataProvider,
let bubbleData = dataProvider.bubbleData,
isDrawingValuesAllowed(dataProvider: dataProvider),
let dataSets = bubbleData.dataSets as? [IBubbleChartDataSet]
else { return }
let phaseX = max(0.0, min(1.0, animator.phaseX))
let phaseY = animator.phaseY
var pt = CGPoint()
for i in 0..<dataSets.count
{
let dataSet = dataSets[i]
guard
shouldDrawValues(forDataSet: dataSet),
let formatter = dataSet.valueFormatter
else { continue }
let alpha = phaseX == 1 ? phaseY : phaseX
_xBounds.set(chart: dataProvider, dataSet: dataSet, animator: animator)
let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency)
let valueToPixelMatrix = trans.valueToPixelMatrix
let iconsOffset = dataSet.iconsOffset
for j in _xBounds.min..._xBounds.range + _xBounds.min
{
guard let e = dataSet.entryForIndex(j) as? BubbleChartDataEntry else { break }
let valueTextColor = dataSet.valueTextColorAt(j).withAlphaComponent(CGFloat(alpha))
pt.x = CGFloat(e.x)
pt.y = CGFloat(e.y * phaseY)
pt = pt.applying(valueToPixelMatrix)
guard viewPortHandler.isInBoundsRight(pt.x) else { break }
guard
viewPortHandler.isInBoundsLeft(pt.x),
viewPortHandler.isInBoundsY(pt.y)
else { continue }
let text = formatter.stringForValue(
Double(e.size),
entry: e,
dataSetIndex: i,
viewPortHandler: viewPortHandler)
// Larger font for larger bubbles?
let valueFont = dataSet.valueFont
let lineHeight = valueFont.lineHeight
if dataSet.isDrawValuesEnabled
{
ChartUtils.drawText(
context: context,
text: text,
point: CGPoint(
x: pt.x,
y: pt.y - (0.5 * lineHeight)),
align: .center,
attributes: [NSAttributedStringKey.font: valueFont, NSAttributedStringKey.foregroundColor: valueTextColor])
}
if let icon = e.icon, dataSet.isDrawIconsEnabled
{
ChartUtils.drawImage(context: context,
image: icon,
x: pt.x + iconsOffset.x,
y: pt.y + iconsOffset.y,
size: icon.size)
}
}
}
}
open override func drawExtras(context: CGContext)
{
}
open override func drawHighlighted(context: CGContext, indices: [Highlight])
{
guard
let dataProvider = dataProvider,
let bubbleData = dataProvider.bubbleData
else { return }
context.saveGState()
defer { context.restoreGState() }
let phaseY = animator.phaseY
for high in indices
{
guard
let dataSet = bubbleData.getDataSetByIndex(high.dataSetIndex) as? IBubbleChartDataSet,
dataSet.isHighlightEnabled,
let entry = dataSet.entryForXValue(high.x, closestToY: high.y) as? BubbleChartDataEntry,
isInBoundsX(entry: entry, dataSet: dataSet)
else { continue }
let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency)
_sizeBuffer[0].x = 0.0
_sizeBuffer[0].y = 0.0
_sizeBuffer[1].x = 1.0
_sizeBuffer[1].y = 0.0
trans.pointValuesToPixel(&_sizeBuffer)
let normalizeSize = dataSet.isNormalizeSizeEnabled
// calcualte the full width of 1 step on the x-axis
let maxBubbleWidth: CGFloat = abs(_sizeBuffer[1].x - _sizeBuffer[0].x)
let maxBubbleHeight: CGFloat = abs(viewPortHandler.contentBottom - viewPortHandler.contentTop)
let referenceSize: CGFloat = min(maxBubbleHeight, maxBubbleWidth)
_pointBuffer.x = CGFloat(entry.x)
_pointBuffer.y = CGFloat(entry.y * phaseY)
trans.pointValueToPixel(&_pointBuffer)
let shapeSize = getShapeSize(entrySize: entry.size, maxSize: dataSet.maxSize, reference: referenceSize, normalizeSize: normalizeSize)
let shapeHalf = shapeSize / 2.0
guard
viewPortHandler.isInBoundsTop(_pointBuffer.y + shapeHalf),
viewPortHandler.isInBoundsBottom(_pointBuffer.y - shapeHalf),
viewPortHandler.isInBoundsLeft(_pointBuffer.x + shapeHalf)
else { continue }
guard viewPortHandler.isInBoundsRight(_pointBuffer.x - shapeHalf) else { break }
let originalColor = dataSet.color(atIndex: Int(entry.x))
var h: CGFloat = 0.0
var s: CGFloat = 0.0
var b: CGFloat = 0.0
var a: CGFloat = 0.0
originalColor.getHue(&h, saturation: &s, brightness: &b, alpha: &a)
let color = NSUIColor(hue: h, saturation: s, brightness: b * 0.5, alpha: a)
let rect = CGRect(
x: _pointBuffer.x - shapeHalf,
y: _pointBuffer.y - shapeHalf,
width: shapeSize,
height: shapeSize)
context.setLineWidth(dataSet.highlightCircleWidth)
context.setStrokeColor(color.cgColor)
context.strokeEllipse(in: rect)
high.setDraw(x: _pointBuffer.x, y: _pointBuffer.y)
}
}
}
|
ef687111410422d113cda01f88c48b21
| 34.940351 | 145 | 0.559992 | false | false | false | false |
Daltron/BigBoard
|
refs/heads/master
|
Example/BigBoard/ExampleView.swift
|
mit
|
1
|
//
// ExampleView.swift
// BigBoard
//
// Created by Dalton Hinterscher on 5/18/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import UIKit
import SnapKit
protocol ExampleViewDelegate : class {
func numberOfStocks() -> Int
func stockAtIndex(_ index:Int) -> BigBoardStock
func stockSelectedAtIndex(_ index:Int)
func refreshControllPulled()
}
class ExampleView: UIView, UITableViewDataSource, UITableViewDelegate {
weak var delegate:ExampleViewDelegate?
var stocksTableView:UITableView!
var refreshControl:UIRefreshControl!
init(delegate:ExampleViewDelegate){
super.init(frame: CGRect.zero)
self.delegate = delegate
self.backgroundColor = UIColor.white
stocksTableView = UITableView(frame: CGRect.zero, style: .plain)
stocksTableView.dataSource = self
stocksTableView.delegate = self
stocksTableView.rowHeight = 50.0
addSubview(stocksTableView)
refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(refreshControllerPulled), for: .valueChanged)
stocksTableView.addSubview(refreshControl)
stocksTableView.snp.makeConstraints { (make) in
make.edges.equalTo(self)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func refreshControllerPulled(){
delegate!.refreshControllPulled()
}
// MARK: UITableViewDataSource and UITableViewDataSource Implementation
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return delegate!.numberOfStocks()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let reuseIdentifier = "ExampleCell"
var cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier) as UITableViewCell?
if cell == nil {
cell = UITableViewCell(style: .subtitle, reuseIdentifier: reuseIdentifier)
let currentPriceLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 150, height: 25))
currentPriceLabel.textAlignment = .right
cell?.accessoryView = currentPriceLabel
}
return cell!
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let stock = delegate!.stockAtIndex((indexPath as NSIndexPath).row)
cell.textLabel?.text = stock.name!
cell.detailTextLabel?.text = stock.symbol!
let currentPriceLabel = cell.accessoryView as! UILabel!
currentPriceLabel?.text = "$\(stock.lastTradePriceOnly!)"
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: false)
delegate!.stockSelectedAtIndex((indexPath as NSIndexPath).row)
}
}
|
8ca11853c0462582f910f08a4edafddd
| 32.793478 | 112 | 0.670634 | false | false | false | false |
invoy/CoreDataQueryInterface
|
refs/heads/master
|
CoreDataQueryInterface/Util.swift
|
mit
|
1
|
//
// Util.swift
// CoreDataQueryInterface
//
// Created by Gregory Higley on 10/5/16.
// Copyright © 2016 Prosumma LLC. All rights reserved.
//
import Foundation
var debug: Bool = {
for arg in ProcessInfo.processInfo.arguments {
if arg == "-com.prosumma.CoreDataQueryInterface.Debug" {
return true
}
}
return false
}()
infix operator ??= : AssignmentPrecedence
func ??=<T>(lhs: inout T?, rhs: @autoclosure () -> T?) {
if lhs != nil { return }
lhs = rhs()
}
|
aec342850e3911274408f48ebfed55e7
| 18.807692 | 64 | 0.609709 | false | false | false | false |
spamproject/spam
|
refs/heads/master
|
spam/spam.swift
|
mit
|
1
|
import Foundation
private let fileManager = NSFileManager()
private let spamDirectory = ".spam"
private let swiftc = "xcrun -sdk macosx swiftc"
private extension Module {
var installPath: String {
get {
return spamDirectory + "/src/" + username + "/" + repo
}
}
}
// MARK: helper functions
func findModules(path: String) -> [Module] {
var modules = [Module]()
if let streamReader = StreamReader(path: path) {
var line: String?
while let line = streamReader.nextLine() {
if let module = Module(importStatement: line) {
modules.append(module)
}
}
} else {
error("could not read \(path)")
}
return modules
}
func compile(modules: [Module]) -> String {
let s = spamDirectory
mkdir("\(s)/lib")
var command = "\(swiftc) -I \(s)/lib -L \(s)/lib "
for module in modules {
let modulePath = "\(spamDirectory)/lib/\(module.moduleName).swiftmodule"
if !fileManager.fileExistsAtPath(modulePath) {
compile(module)
}
command += "-l\(module.moduleName.lowercaseString) "
}
if let sourceFiles = filesOfType("swift", atPath: ".") {
return "\(command)\(sourceFiles)"
} else {
error("could not find any Swift files in the current directory")
}
}
func compile(module: Module) {
log("Compiling \(module.moduleName)…")
let s = spamDirectory
let u = module.username
let r = module.repo
let M = module.moduleName
let m = module.moduleName.lowercaseString
let path = "\(s)/src/\(u)/\(r)"
var sourceFiles = filesOfType("swift", atPath: "\(path)/\(r)")
?? filesOfType("swift", atPath: "\(path)/\(m)")
?? filesOfType("swift", atPath: "\(path)/Source")
?? filesOfType("swift", atPath: "\(path)/src")
?? filesOfType("swift", atPath: "\(path)")
if sourceFiles != nil {
call("\(swiftc) -emit-library -emit-object " +
"\(sourceFiles!) -module-name \(M)")
if let objectFiles = filesOfType("o", atPath: ".") {
call("ar rcs lib\(m).a \(objectFiles)")
call("rm \(objectFiles)")
call("mv lib\(m).a \(s)/lib/")
call("\(swiftc) -parse-as-library -emit-module \(sourceFiles!) " +
"-module-name \(M) -o \(s)/lib/")
} else {
error("could not find object files")
}
} else {
error("could not find any Swift files in \(path)")
}
}
// MARK: subcommands
func install() {
func install(module: Module) {
mkdir("\(spamDirectory)/src")
call("git clone \(module.path) \(module.installPath)")
if let version = module.version {
call("git --git-dir=\(module.installPath)/.git " +
"--work-tree=\(module.installPath) checkout \(version) -q")
}
}
if let sourceFiles = filesOfType("swift", atPath: ".") {
for file in split(sourceFiles, isSeparator: { $0 == " " }) {
let modules = findModules(file)
for module in modules {
if !fileManager.fileExistsAtPath(module.installPath) {
install(module)
}
}
}
} else {
error("could not find any Swift files in the current directory")
}
}
func uninstall() {
log("Removing .spam/ and its contents…")
call("rm -rf \(spamDirectory)")
}
func compile(#outputFile: String?) {
if let sourceFiles = filesOfType("swift", atPath: ".") {
var modules = [Module]()
for file in split(sourceFiles, isSeparator: { $0 == " " }) {
modules += findModules(file)
}
let finalCompilationCommand = compile(modules)
if let outputFile = outputFile {
log("Compiling \(outputFile)…")
call("\(finalCompilationCommand) -o \(outputFile)")
} else {
log("Compiling project…")
call(finalCompilationCommand)
}
} else {
error("could not find any Swift files in the current directory")
}
}
func build(#outputFile: String?) {
install()
compile(outputFile: outputFile)
}
|
ec561891929fae45ce14c58160342e3c
| 29.948148 | 80 | 0.561273 | false | false | false | false |
Jnosh/swift
|
refs/heads/master
|
test/IRGen/lazy_globals.swift
|
apache-2.0
|
3
|
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -parse-as-library -emit-ir -primary-file %s | %FileCheck %s
// REQUIRES: CPU=x86_64
// CHECK: @globalinit_[[T:.*]]_token0 = internal global i64 0, align 8
// CHECK: @_T012lazy_globals1xSiv = hidden global %TSi zeroinitializer, align 8
// CHECK: @_T012lazy_globals1ySiv = hidden global %TSi zeroinitializer, align 8
// CHECK: @_T012lazy_globals1zSiv = hidden global %TSi zeroinitializer, align 8
// CHECK: define internal swiftcc void @globalinit_[[T]]_func0() {{.*}} {
// CHECK: entry:
// CHECK: store i64 1, i64* getelementptr inbounds (%TSi, %TSi* @_T012lazy_globals1xSiv, i32 0, i32 0), align 8
// CHECK: store i64 2, i64* getelementptr inbounds (%TSi, %TSi* @_T012lazy_globals1ySiv, i32 0, i32 0), align 8
// CHECK: store i64 3, i64* getelementptr inbounds (%TSi, %TSi* @_T012lazy_globals1zSiv, i32 0, i32 0), align 8
// CHECK: ret void
// CHECK: }
// CHECK: define hidden swiftcc i8* @_T012lazy_globals1xSifau() {{.*}} {
// CHECK: entry:
// CHECK: call void @swift_once(i64* @globalinit_[[T]]_token0, i8* bitcast (void ()* @globalinit_[[T]]_func0 to i8*), i8* undef)
// CHECK: ret i8* bitcast (%TSi* @_T012lazy_globals1xSiv to i8*)
// CHECK: }
// CHECK: define hidden swiftcc i8* @_T012lazy_globals1ySifau() {{.*}} {
// CHECK: entry:
// CHECK: call void @swift_once(i64* @globalinit_[[T]]_token0, i8* bitcast (void ()* @globalinit_[[T]]_func0 to i8*), i8* undef)
// CHECK: ret i8* bitcast (%TSi* @_T012lazy_globals1ySiv to i8*)
// CHECK: }
// CHECK: define hidden swiftcc i8* @_T012lazy_globals1zSifau() {{.*}} {
// CHECK: entry:
// CHECK: call void @swift_once(i64* @globalinit_[[T]]_token0, i8* bitcast (void ()* @globalinit_[[T]]_func0 to i8*), i8* undef)
// CHECK: ret i8* bitcast (%TSi* @_T012lazy_globals1zSiv to i8*)
// CHECK: }
var (x, y, z) = (1, 2, 3)
// CHECK: define hidden swiftcc i64 @_T012lazy_globals4getXSiyF() {{.*}} {
// CHECK: entry:
// CHECK: %0 = call swiftcc i8* @_T012lazy_globals1xSifau()
// CHECK: %1 = bitcast i8* %0 to %TSi*
// CHECK: %._value = getelementptr inbounds %TSi, %TSi* %1, i32 0, i32 0
// CHECK: %2 = load i64, i64* %._value, align 8
// CHECK: ret i64 %2
// CHECK: }
func getX() -> Int { return x }
|
e96406a9946b9bd5d00ab3dc5dcb9adc
| 48.021739 | 132 | 0.647007 | false | false | false | false |
CNKCQ/oschina
|
refs/heads/master
|
Carthage/Checkouts/SnapKit/Source/ConstraintInsetTarget.swift
|
mit
|
3
|
//
// SnapKit
//
// Copyright (c) 2011-Present 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
public protocol ConstraintInsetTarget: ConstraintConstantTarget {
}
extension Int: ConstraintInsetTarget {
}
extension UInt: ConstraintInsetTarget {
}
extension Float: ConstraintInsetTarget {
}
extension Double: ConstraintInsetTarget {
}
extension CGFloat: ConstraintInsetTarget {
}
extension ConstraintInsets: ConstraintInsetTarget {
}
extension ConstraintInsetTarget {
internal var constraintInsetTargetValue: ConstraintInsets {
if let amount = self as? ConstraintInsets {
return amount
} else if let amount = self as? Float {
return ConstraintInsets(top: CGFloat(amount), left: CGFloat(amount), bottom: CGFloat(amount), right: CGFloat(amount))
} else if let amount = self as? Double {
return ConstraintInsets(top: CGFloat(amount), left: CGFloat(amount), bottom: CGFloat(amount), right: CGFloat(amount))
} else if let amount = self as? CGFloat {
return ConstraintInsets(top: amount, left: amount, bottom: amount, right: amount)
} else if let amount = self as? Int {
return ConstraintInsets(top: CGFloat(amount), left: CGFloat(amount), bottom: CGFloat(amount), right: CGFloat(amount))
} else if let amount = self as? UInt {
return ConstraintInsets(top: CGFloat(amount), left: CGFloat(amount), bottom: CGFloat(amount), right: CGFloat(amount))
} else {
return ConstraintInsets(top: 0, left: 0, bottom: 0, right: 0)
}
}
}
|
5e5e5a21d155bad4ff1b411727aec2ad
| 38.128571 | 129 | 0.711574 | false | false | false | false |
BrantSteven/SinaProject
|
refs/heads/master
|
BSweibo/BSweibo/class/newFeature/WelcomeVC.swift
|
mit
|
1
|
//
// WelcomeVC.swift
// BSweibo
//
// Created by 上海旅徒电子商务有限公司 on 16/9/27.
// Copyright © 2016年 白霜. All rights reserved.
//
import UIKit
class WelcomeVC: UIViewController {
/// 图像底部约束
private var iconBottomCons: NSLayoutConstraint?
override func viewDidLoad() {
super.viewDidLoad()
//1.初始化UI
createUI()
//2.设置用户信息
if let iconUrlStr = UserAccount.readAccount()?.avatar_large {
bsLog(message: iconUrlStr)
iconView.sd_setImage(with: NSURL(string: iconUrlStr) as URL!)
}
}
override func viewDidAppear(_ animated: Bool) {//头像从底部滑上去
super.viewDidAppear(animated)
UIView.animate(withDuration: 1.5, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: 1, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
self.iconView.frame = CGRect(x: BSWidth/2-50, y: 100, width: 100, height: 100)
self.message.frame = CGRect(x: self.iconView.left, y: self.iconView.bottom+10, width: 100, height: 39)
}) { (_) -> Void in
self.message.alpha = 1.0//完成头像的滑动 label展示
//去主页 注意点: 企业开发中如果要切换根控制器 最好都在appdelegate中切换
NotificationCenter.default.post(name: NSNotification.Name(rawValue: ChangeRootViewControllerNotifacationtion), object: true)
}
}
//初始化UI
func createUI(){
view.addSubview(imageView)
view.addSubview(iconView)
view.addSubview(message)
imageView.frame = view.bounds
iconView.frame = CGRect(x: BSWidth/2-50, y: BSHeight - 100, width: 100, height: 100)
// message.frame = CGRect(x: iconView.left, y: iconView.bottom+10, width: 100, height: 39)
}
//MARK:懒加载控件
//背景图片
lazy var imageView:UIImageView = {
let imageV = UIImageView.init(image: UIImage.init(named: "ad_background"))
return imageV
}()
///头像
lazy var iconView:UIImageView = {
let iconV = UIImageView(image: UIImage(named: "avatar_default_big"))
iconV.layer.masksToBounds = true
iconV.layer.cornerRadius = 50
return iconV
}()
///消息文字
lazy var message:UILabel = {
let messageLabel = UILabel.init()
messageLabel.text = "欢迎归来"
messageLabel.textAlignment = NSTextAlignment.center
messageLabel.alpha = 0//隐藏label
return messageLabel
}()
}
|
ab1eed7dc6018f0822f7aefdd778c3e8
| 36.40625 | 180 | 0.630744 | false | false | false | false |
github/codeql
|
refs/heads/main
|
swift/ql/test/query-tests/Security/CWE-311/testCoreData.swift
|
mit
|
1
|
// --- stubs ---
class NSObject
{
}
class NSManagedObject : NSObject
{
func value(forKey key: String) -> Any? { return "" }
func setValue(_ value: Any?, forKey key: String) {}
func primitiveValue(forKey key: String) -> Any? { return "" }
func setPrimitiveValue(_ value: Any?, forKey key: String) {}
}
class MyManagedObject : NSManagedObject
{
func setIndirect(value: String) {
setValue(value, forKey: "myKey")
}
var myValue: String {
get {
if let v = value(forKey: "myKey") as? String
{
return v
} else {
return ""
}
}
set {
setValue(newValue, forKey: "myKey")
}
}
}
func encrypt(_ data: String) -> String { return data }
func hash(data: inout String) { }
func getPassword() -> String { return "" }
func doSomething(password: String) { }
// --- tests ---
func test1(obj : NSManagedObject, password : String, password_hash : String) {
// NSManagedObject methods...
obj.setValue(password, forKey: "myKey") // BAD
obj.setValue(password_hash, forKey: "myKey") // GOOD (not sensitive)
obj.setPrimitiveValue(password, forKey: "myKey") // BAD
obj.setPrimitiveValue(password_hash, forKey: "myKey") // GOOD (not sensitive)
}
func test2(obj : MyManagedObject, password : String, password_file : String) {
// MyManagedObject methods...
obj.setValue(password, forKey: "myKey") // BAD
obj.setValue(password_file, forKey: "myKey") // GOOD (not sensitive)
obj.setIndirect(value: password) // BAD [reported on line 19]
obj.setIndirect(value: password_file) // GOOD (not sensitive)
obj.myValue = password // BAD [reported on line 32]
obj.myValue = password_file // GOOD (not sensitive)
}
class MyClass {
var harmless = "abc"
var password = "123"
}
func test3(obj : NSManagedObject, x : String) {
// alternative evidence of sensitivity...
obj.setValue(x, forKey: "myKey") // BAD [NOT REPORTED]
doSomething(password: x);
obj.setValue(x, forKey: "myKey") // BAD
var y = getPassword();
obj.setValue(y, forKey: "myKey") // BAD
var z = MyClass()
obj.setValue(z.harmless, forKey: "myKey") // GOOD (not sensitive)
obj.setValue(z.password, forKey: "myKey") // BAD
}
func test4(obj : NSManagedObject, passwd : String) {
// sanitizers...
var x = passwd;
var y = passwd;
var z = passwd;
obj.setValue(x, forKey: "myKey") // BAD
obj.setValue(y, forKey: "myKey") // BAD
obj.setValue(z, forKey: "myKey") // BAD
x = encrypt(x);
hash(data: &y);
z = "";
obj.setValue(x, forKey: "myKey") // GOOD (not sensitive)
obj.setValue(y, forKey: "myKey") // GOOD (not sensitive)
obj.setValue(z, forKey: "myKey") // GOOD (not sensitive)
}
|
b0a1b00efb679f6077c112221d1ce7ef
| 23.462264 | 78 | 0.66101 | false | false | false | false |
Keanyuan/SwiftContact
|
refs/heads/master
|
SwiftContent/SwiftContent/Classes/ContentView/shareView/YMShareButtonView.swift
|
mit
|
1
|
//
// YMShareButtonView.swift
// DanTang
//
// Created by 杨蒙 on 16/7/23.
// Copyright © 2016年 hrscy. All rights reserved.
//
import UIKit
typealias sendValueClosure = (_ shareButtonType: Int) -> Void
enum YMShareButtonType: Int {
/// 微信朋友圈
case WeChatTimeline = 0
/// 微信好友
case WeChatSession = 1
/// 微博
case Weibo = 2
/// QQ 空间
case QZone = 3
/// QQ 好友
case QQFriends = 4
/// 复制链接
case CopyLink = 5
}
class YMShareButtonView: UIView {
//声明一个闭包
var shareButtonBlock:sendValueClosure?
// 图片数组
let images = ["Share_WeChatTimelineIcon_70x70_", "Share_WeChatSessionIcon_70x70_", "Share_WeiboIcon_70x70_", "Share_QzoneIcon_70x70_", "Share_QQIcon_70x70_", "Share_CopyLinkIcon_70x70_"]
// 标题数组
let titles = ["微信朋友圈", "微信好友", "微博", "QQ 空间", "QQ 好友", "复制链接"]
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
private func setupUI() {
let maxCols = 3
let buttonW: CGFloat = 70
let buttonH: CGFloat = buttonW + 30
let buttonStartX: CGFloat = 20
let xMargin: CGFloat = (SCREENW - 20 - 2 * buttonStartX - CGFloat(maxCols) * buttonW) / CGFloat(maxCols - 1)
// 创建按钮
for index in 0..<images.count {
let button = YMVerticalButton()
button.tag = index
button.setImage(UIImage(named: images[index]), for: .normal)
button.setTitle(titles[index], for: .normal)
button.setTitleColor(UIColor.black, for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 12)
button.width = buttonW
button.height = buttonH
button.addTarget(self, action: #selector(shareButtonClick), for: .touchUpInside)
// 计算 X、Y
let row = Int(index / maxCols)
let col = index % maxCols
let buttonX: CGFloat = CGFloat(col) * (xMargin + buttonW) + buttonStartX
let buttonMaxY: CGFloat = CGFloat(row) * buttonH
let buttonY = buttonMaxY
button.frame = CGRect(x: buttonX, y: buttonY, width: buttonW, height: buttonH)
addSubview(button)
}
}
func shareButtonClick(button: UIButton) {
if let shareButtonType = YMShareButtonType(rawValue: button.tag) {
switch shareButtonType {
case .WeChatTimeline:
break
case .WeChatSession:
break
case .Weibo:
break
case .QZone:
break
case .QQFriends:
break
case .CopyLink:
break
}
}
print(button.titleLabel!.text!)
if (shareButtonBlock != nil){
shareButtonBlock!(button.tag)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
a6e98c9fa6499a7baf40a299b2004369
| 27.218182 | 190 | 0.535116 | false | false | false | false |
Kawoou/FlexibleImage
|
refs/heads/master
|
Sources/Filter/GammaFilter.swift
|
mit
|
1
|
//
// GammaFilter.swift
// FlexibleImage
//
// Created by Kawoou on 2017. 5. 12..
// Copyright © 2017년 test. All rights reserved.
//
#if !os(watchOS)
import Metal
#endif
internal class GammaFilter: ImageFilter {
// MARK: - Property
internal override var metalName: String {
get {
return "GammaFilter"
}
}
internal var gamma: Float = 1.0
// MARK: - Internal
#if !os(watchOS)
@available(OSX 10.11, iOS 8, tvOS 9, *)
internal override func processMetal(_ device: ImageMetalDevice, _ commandBuffer: MTLCommandBuffer, _ commandEncoder: MTLComputeCommandEncoder) -> Bool {
let factors: [Float] = [self.gamma]
for i in 0..<factors.count {
var factor = factors[i]
let size = max(MemoryLayout<Float>.size, 16)
let options: MTLResourceOptions
if #available(iOS 9.0, *) {
options = [.storageModeShared]
} else {
options = [.cpuCacheModeWriteCombined]
}
let buffer = device.device.makeBuffer(
bytes: &factor,
length: size,
options: options
)
#if swift(>=4.0)
commandEncoder.setBuffer(buffer, offset: 0, index: i)
#else
commandEncoder.setBuffer(buffer, offset: 0, at: i)
#endif
}
return super.processMetal(device, commandBuffer, commandEncoder)
}
#endif
override func processNone(_ device: ImageNoneDevice) -> Bool {
let memoryPool = device.memoryPool!
let width = Int(device.drawRect!.width)
let height = Int(device.drawRect!.height)
var index = 0
for _ in 0..<height {
for _ in 0..<width {
let r = Float(memoryPool[index + 0]) / 255.0
let g = Float(memoryPool[index + 1]) / 255.0
let b = Float(memoryPool[index + 2]) / 255.0
memoryPool[index + 0] = UInt8(powf(r, self.gamma) * 255.0)
memoryPool[index + 1] = UInt8(powf(g, self.gamma) * 255.0)
memoryPool[index + 2] = UInt8(powf(b, self.gamma) * 255.0)
index += 4
}
}
return super.processNone(device)
}
}
|
54b36369cbf6ad559aa64a8e63388485
| 29.710843 | 160 | 0.488035 | false | false | false | false |
DSanzh/GuideMe-iOS
|
refs/heads/master
|
Pavers/Sources/FRP/Sugar/OptionalComparison.swift
|
mit
|
7
|
import Foundation
precedencegroup Comparison {
associativity: left
higherThan: LogicalConjunctionPrecedence
}
infix operator ?= : Comparison
public func ?=<T>(left: inout T, right: T?) {
guard let value = right else { return }
left = value
}
public func ?=<T>(left: inout T?, right: T?) {
guard let value = right else { return }
left = value
}
|
55e265b3bd404c5915a45e61b91bdfc7
| 19 | 46 | 0.686111 | false | false | false | false |
alskipp/Monoid
|
refs/heads/master
|
MonoidTests/AllMonoidTests.swift
|
mit
|
1
|
// Copyright © 2016 Al Skipp. All rights reserved.
import XCTest
import Monoid
class AllMonoidTests: XCTestCase {
func testMempty() {
XCTAssertTrue(All.mempty.value == true)
}
func testMappend() {
XCTAssertTrue(All(true) <> All(true) <> All(true) == All(true))
XCTAssertTrue(All(true) <> All(true) <> All(false) == All(false))
}
func testMconcat() {
XCTAssertTrue(.mconcat([All(true), All(true), All(true)]) == All(true))
XCTAssertTrue(.mconcat([All(true), All(false), All(true)]) == All(false))
}
func testComparable() {
XCTAssertTrue(All(false) < All(true))
}
func testDescription() {
XCTAssertTrue(All(true).description == "All(true)")
}
}
|
6f5ba6a7b3b06db3233e43b9084c3188
| 22.333333 | 77 | 0.642857 | false | true | false | false |
overtake/TelegramSwift
|
refs/heads/master
|
Telegram-Mac/PeersListController.swift
|
gpl-2.0
|
1
|
//
// PeersListController.swift
// TelegramMac
//
// Created by keepcoder on 29/12/2016.
// Copyright © 2016 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
import Postbox
import TelegramCore
import Reactions
import SwiftSignalKit
private final class Arguments {
let context: AccountContext
let joinGroupCall:(ChatActiveGroupCallInfo)->Void
let joinGroup:(PeerId)->Void
let openPendingRequests:()->Void
let dismissPendingRequests:([PeerId])->Void
init(context: AccountContext, joinGroupCall:@escaping(ChatActiveGroupCallInfo)->Void, joinGroup:@escaping(PeerId)->Void, openPendingRequests:@escaping()->Void, dismissPendingRequests: @escaping([PeerId])->Void) {
self.context = context
self.joinGroupCall = joinGroupCall
self.joinGroup = joinGroup
self.openPendingRequests = openPendingRequests
self.dismissPendingRequests = dismissPendingRequests
}
}
final class RevealAllChatsView : Control {
let textView: TextView = TextView()
var layoutState: SplitViewState = .dual {
didSet {
needsLayout = true
}
}
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
textView.userInteractionEnabled = false
textView.isSelectable = false
addSubview(textView)
let layout = TextViewLayout(.initialize(string: strings().chatListCloseFilter, color: .white, font: .medium(.title)))
layout.measure(width: max(280, frame.width))
textView.update(layout)
let shadow = NSShadow()
shadow.shadowBlurRadius = 5
shadow.shadowColor = NSColor.black.withAlphaComponent(0.1)
shadow.shadowOffset = NSMakeSize(0, 2)
self.shadow = shadow
set(background: theme.colors.accent, for: .Normal)
}
override func cursorUpdate(with event: NSEvent) {
NSCursor.pointingHand.set()
}
override var backgroundColor: NSColor {
didSet {
textView.backgroundColor = backgroundColor
}
}
override func updateLocalizationAndTheme(theme: PresentationTheme) {
super.updateLocalizationAndTheme(theme: theme)
needsLayout = true
}
override func layout() {
super.layout()
textView.center()
layer?.cornerRadius = frame.height / 2
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
final class FilterTabsView : View {
let tabs: ScrollableSegmentView = ScrollableSegmentView(frame: NSZeroRect)
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
addSubview(tabs)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layout() {
super.layout()
tabs.frame = bounds
}
}
struct PeerListState : Equatable {
struct InputActivities : Equatable {
struct Activity : Equatable {
let peer: PeerEquatable
let activity: PeerInputActivity
init(_ peer: Peer, _ activity: PeerInputActivity) {
self.peer = PeerEquatable(peer)
self.activity = activity
}
}
var activities: [PeerActivitySpace: [Activity]]
}
struct ForumData : Equatable {
static func == (lhs: PeerListState.ForumData, rhs: PeerListState.ForumData) -> Bool {
if lhs.peer != rhs.peer {
return false
}
if let lhsCached = lhs.peerView.cachedData, let rhsCached = rhs.peerView.cachedData {
if !lhsCached.isEqual(to: rhsCached) {
return false
}
} else if (lhs.peerView.cachedData != nil) != (rhs.peerView.cachedData != nil) {
return false
}
if lhs.call != rhs.call {
return false
}
if lhs.online != rhs.online {
return false
}
if lhs.invitationState != rhs.invitationState {
return false
}
return true
}
var peer: TelegramChannel
var peerView: PeerView
var online: Int32
var call: ChatActiveGroupCallInfo?
var invitationState: PeerInvitationImportersState?
}
var proxySettings: ProxySettings
var connectionStatus: ConnectionStatus
var splitState: SplitViewState
var searchState: SearchFieldState = .None
var peer: PeerEquatable?
var forumPeer: ForumData?
var mode: PeerListMode
var activities: InputActivities
}
class PeerListContainerView : View {
private final class ProxyView : Control {
fileprivate let button:ImageButton = ImageButton()
private var connecting: ProgressIndicator?
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
addSubview(button)
button.userInteractionEnabled = false
button.isEventLess = true
}
func update(_ pref: ProxySettings, connection: ConnectionStatus, animated: Bool) {
switch connection {
case .connecting, .waitingForNetwork:
if pref.enabled {
let current: ProgressIndicator
if let view = self.connecting {
current = view
} else {
current = ProgressIndicator(frame: focus(NSMakeSize(11, 11)))
self.connecting = current
addSubview(current)
}
current.userInteractionEnabled = false
current.isEventLess = true
current.progressColor = theme.colors.accentIcon
} else if let view = connecting {
performSubviewRemoval(view, animated: animated)
self.connecting = nil
}
button.set(image: pref.enabled ? theme.icons.proxyState : theme.icons.proxyEnable, for: .Normal)
case .online, .updating:
if let view = connecting {
performSubviewRemoval(view, animated: animated)
self.connecting = nil
}
if pref.enabled {
button.set(image: theme.icons.proxyEnabled, for: .Normal)
} else {
button.set(image: theme.icons.proxyEnable, for: .Normal)
}
}
button.sizeToFit()
needsLayout = true
}
override func layout() {
super.layout()
button.center()
if let connecting = connecting {
var rect = connecting.centerFrame()
if backingScaleFactor == 2.0 {
rect.origin.x -= 0.5
rect.origin.y -= 0.5
}
connecting.frame = rect
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func updateLocalizationAndTheme(theme: PresentationTheme) {
super.updateLocalizationAndTheme(theme: theme)
connecting?.progressColor = theme.colors.accentIcon
}
}
private final class StatusView : Control {
fileprivate var button:PremiumStatusControl?
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
}
private var peer: Peer?
private weak var effectPanel: Window?
func update(_ peer: Peer, context: AccountContext, animated: Bool) {
var interactiveStatus: Reactions.InteractiveStatus? = nil
if visibleRect != .zero, window != nil, let interactive = context.reactions.interactiveStatus {
interactiveStatus = interactive
}
if let view = self.button, interactiveStatus != nil, interactiveStatus?.fileId != nil {
performSubviewRemoval(view, animated: animated, duration: 0.3)
self.button = nil
}
let control = PremiumStatusControl.control(peer, account: context.account, inlinePacksContext: context.inlinePacksContext, isSelected: false, isBig: true, playTwice: true, cached: self.button, animated: animated)
if let control = control {
self.button = control
addSubview(control)
control.center()
} else {
self.button?.removeFromSuperview()
self.button = nil
}
self.peer = peer
if let interactive = interactiveStatus {
self.playAnimation(interactive, context: context)
}
}
private func playAnimation(_ status: Reactions.InteractiveStatus, context: AccountContext) {
guard let control = self.button, let window = self.window else {
return
}
guard let fileId = status.fileId else {
return
}
control.isHidden = true
let play:(StatusView)->Void = { [weak control] superview in
guard let control = control else {
return
}
control.isHidden = false
let panel = Window(contentRect: NSMakeRect(0, 0, 160, 120), styleMask: [.fullSizeContentView], backing: .buffered, defer: false)
panel._canBecomeMain = false
panel._canBecomeKey = false
panel.ignoresMouseEvents = true
panel.level = .popUpMenu
panel.backgroundColor = .clear
panel.isOpaque = false
panel.hasShadow = false
let player = CustomReactionEffectView(frame: NSMakeSize(160, 120).bounds, context: context, fileId: fileId)
player.isEventLess = true
player.triggerOnFinish = { [weak panel] in
if let panel = panel {
panel.parent?.removeChildWindow(panel)
panel.orderOut(nil)
}
}
superview.effectPanel = panel
let controlRect = superview.convert(control.frame, to: nil)
var rect = CGRect(origin: CGPoint(x: controlRect.midX - player.frame.width / 2, y: controlRect.midY - player.frame.height / 2), size: player.frame.size)
rect = window.convertToScreen(rect)
panel.setFrame(rect, display: true)
panel.contentView?.addSubview(player)
window.addChildWindow(panel, ordered: .above)
}
if let fromRect = status.rect {
let layer = InlineStickerItemLayer(account: context.account, inlinePacksContext: context.inlinePacksContext, emoji: .init(fileId: fileId, file: nil, emoji: ""), size: control.frame.size)
let toRect = control.convert(control.frame.size.bounds, to: nil)
let from = fromRect.origin.offsetBy(dx: fromRect.width / 2, dy: fromRect.height / 2)
let to = toRect.origin.offsetBy(dx: toRect.width / 2, dy: toRect.height / 2)
let completed: (Bool)->Void = { [weak self] _ in
DispatchQueue.main.async {
if let container = self {
play(container)
NSHapticFeedbackManager.defaultPerformer.perform(.levelChange, performanceTime: .default)
}
}
}
parabollicReactionAnimation(layer, fromPoint: from, toPoint: to, window: context.window, completion: completed)
} else {
play(self)
}
}
override func layout() {
super.layout()
button?.center()
}
deinit {
if let panel = effectPanel {
panel.parent?.removeChildWindow(panel)
panel.orderOut(nil)
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func updateLocalizationAndTheme(theme: PresentationTheme) {
super.updateLocalizationAndTheme(theme: theme)
}
}
private final class ActionView : Control {
private let textView = TextView()
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
addSubview(textView)
textView.userInteractionEnabled = false
textView.isSelectable = false
border = [.Top, .Right]
}
override func updateLocalizationAndTheme(theme: PresentationTheme) {
super.updateLocalizationAndTheme(theme: theme)
textView.backgroundColor = theme.colors.background
}
func update(action: @escaping(PeerId)->Void, peerId: PeerId, title: String) {
let layout = TextViewLayout(.initialize(string: title, color: theme.colors.accent, font: .normal(.text)))
layout.measure(width: .greatestFiniteMagnitude)
textView.update(layout)
self.set(background: theme.colors.background, for: .Normal)
self.set(background: theme.colors.grayBackground, for: .Highlight)
self.removeAllHandlers()
self.set(handler: { _ in
action(peerId)
}, for: .Click)
needsLayout = true
}
override func layout() {
super.layout()
textView.center()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
private var callView: ChatGroupCallView?
private var header: NSView?
private let backgroundView = BackgroundView(frame: NSZeroRect)
let tableView = TableView(frame:NSZeroRect, drawBorder: true)
private let containerView: View = View()
let searchView:SearchView = SearchView(frame:NSMakeRect(10, 0, 0, 0))
let compose:ImageButton = ImageButton()
private var premiumStatus: StatusView?
private var downloads: DownloadsControl?
private var proxy: ProxyView?
private var actionView: ActionView?
fileprivate var showDownloads:(()->Void)? = nil
fileprivate var hideDownloads:(()->Void)? = nil
var mode: PeerListMode = .plain {
didSet {
switch mode {
case .folder:
compose.isHidden = true
case .plain:
compose.isHidden = false
case .filter:
compose.isHidden = true
case .forum:
compose.isHidden = true
}
updateLayout(self.frame.size, transition: .immediate)
}
}
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
self.border = [.Right]
compose.autohighlight = false
autoresizesSubviews = false
addSubview(containerView)
addSubview(tableView)
containerView.addSubview(compose)
containerView.addSubview(searchView)
addSubview(backgroundView)
backgroundView.isHidden = true
tableView.getBackgroundColor = {
.clear
}
updateLocalizationAndTheme(theme: theme)
}
private var state: PeerListState?
var openProxy:((Control)->Void)? = nil
var openStatus:((Control)->Void)? = nil
fileprivate func updateState(_ state: PeerListState, arguments: Arguments, animated: Bool) {
let animated = animated && self.state?.splitState == state.splitState && self.state != nil
self.state = state
var voiceChat: ChatActiveGroupCallInfo?
if state.forumPeer?.call?.data?.groupCall == nil {
if let data = state.forumPeer?.call?.data, data.participantCount == 0 && state.forumPeer?.call?.activeCall.scheduleTimestamp == nil {
voiceChat = nil
} else {
voiceChat = state.forumPeer?.call
}
} else {
voiceChat = nil
}
self.updateAdditionHeader(state, size: frame.size, arguments: arguments, animated: animated)
if let info = voiceChat, state.splitState != .minimisize {
let current: ChatGroupCallView
var offset: CGFloat = -44
if let header = header {
offset += header.frame.height
}
let rect = NSMakeRect(0, offset, frame.width, 44)
if let view = self.callView {
current = view
} else {
current = .init({ _, _ in
arguments.joinGroupCall(info)
}, context: arguments.context, state: .none(info), frame: rect)
self.callView = current
containerView.addSubview(current, positioned: .below, relativeTo: header)
}
current.border = [.Right, .Bottom]
current.update(info, animated: animated)
} else if let view = self.callView {
performSubviewRemoval(view, animated: animated)
self.callView = nil
}
if let peer = state.forumPeer?.peer, peer.participationStatus == .left, state.splitState != .minimisize {
let current: ActionView
if let view = self.actionView {
current = view
} else {
current = ActionView(frame: NSMakeRect(0, frame.height - 50, frame.width, 50))
self.actionView = current
addSubview(current)
if animated {
current.layer?.animateAlpha(from: 0, to: 1, duration: 0.2)
}
}
current.update(action: arguments.joinGroup, peerId: peer.id, title: strings().chatInputJoin)
} else if let view = self.actionView {
performSubviewRemoval(view, animated: animated)
self.actionView = nil
}
self.searchView.isHidden = state.splitState == .minimisize
let componentSize = NSMakeSize(40, 30)
var controlPoint = NSMakePoint(frame.width - 12 - compose.frame.width, floorToScreenPixels(backingScaleFactor, (containerView.frame.height - componentSize.height)/2.0))
let hasControls = state.splitState != .minimisize && state.searchState != .Focus && mode.isPlain
let hasProxy = (!state.proxySettings.servers.isEmpty || state.proxySettings.effectiveActiveServer != nil) && hasControls
let hasStatus = state.peer?.peer.isPremium ?? false && hasControls
if hasProxy {
controlPoint.x -= componentSize.width
let current: ProxyView
if let view = self.proxy {
current = view
} else {
current = ProxyView(frame: CGRect(origin: controlPoint, size: componentSize))
self.proxy = current
self.containerView.addSubview(current, positioned: .below, relativeTo: searchView)
if animated {
current.layer?.animateAlpha(from: 0, to: 1, duration: 0.2)
}
current.set(handler: { [weak self] control in
self?.openProxy?(control)
}, for: .Click)
}
current.update(state.proxySettings, connection: state.connectionStatus, animated: animated)
} else if let view = self.proxy {
performSubviewRemoval(view, animated: animated)
self.proxy = nil
}
if hasStatus, let peer = state.peer?.peer {
controlPoint.x -= componentSize.width
let current: StatusView
if let view = self.premiumStatus {
current = view
} else {
current = StatusView(frame: CGRect(origin: controlPoint, size: componentSize))
self.premiumStatus = current
self.containerView.addSubview(current, positioned: .below, relativeTo: searchView)
if animated {
current.layer?.animateAlpha(from: 0, to: 1, duration: 0.2)
}
current.set(handler: { [weak self] control in
self?.openStatus?(control)
}, for: .Click)
}
current.update(peer, context: arguments.context, animated: animated)
} else if let view = self.premiumStatus {
performSubviewRemoval(view, animated: animated)
self.premiumStatus = nil
}
let transition: ContainedViewLayoutTransition
if animated {
transition = .animated(duration: 0.2, curve: .easeOut)
} else {
transition = .immediate
}
self.updateLayout(self.frame.size, transition: transition)
}
private func updateAdditionHeader(_ state: PeerListState, size: NSSize, arguments: Arguments, animated: Bool) {
let inviteRequestsPending = state.forumPeer?.invitationState?.waitingCount ?? 0
let hasInvites: Bool = state.forumPeer != nil && inviteRequestsPending > 0 && state.splitState != .minimisize
if let state = state.forumPeer?.invitationState, hasInvites {
self.updatePendingRequests(state, arguments: arguments, animated: animated)
} else {
self.updatePendingRequests(nil, arguments: arguments, animated: animated)
}
}
private func updatePendingRequests(_ state: PeerInvitationImportersState?, arguments: Arguments, animated: Bool) {
if let state = state {
let current: ChatPendingRequests
let headerState: ChatHeaderState = .pendingRequests(nil, Int(state.count), state.importers)
if let view = self.header as? ChatPendingRequests {
current = view
} else {
if let view = self.header {
performSubviewRemoval(view, animated: animated)
self.header = nil
}
current = .init(context: arguments.context, openAction: arguments.openPendingRequests, dismissAction: arguments.dismissPendingRequests, state: headerState, frame: NSMakeRect(0, 0, frame.width, 44))
current.border = [.Right, .Bottom]
self.header = current
containerView.addSubview(current)
}
current.update(with: headerState, animated: animated)
} else {
if let view = self.header {
performSubviewRemoval(view, animated: animated)
self.header = nil
}
}
}
private func updateTags(_ state: PeerListState,updateSearchTags: @escaping(SearchTags)->Void, updatePeerTag:@escaping(@escaping(Peer?)->Void)->Void, updateMessageTags: @escaping(@escaping(MessageTags?)->Void)->Void) {
var currentTag: MessageTags?
var currentPeerTag: Peer?
let tags:[(MessageTags?, String, CGImage)] = [(nil, strings().searchFilterClearFilter, theme.icons.search_filter),
(.photo, strings().searchFilterPhotos, theme.icons.search_filter_media),
(.video, strings().searchFilterVideos, theme.icons.search_filter_media),
(.webPage, strings().searchFilterLinks, theme.icons.search_filter_links),
(.music, strings().searchFilterMusic, theme.icons.search_filter_music),
(.voiceOrInstantVideo, strings().searchFilterVoice, theme.icons.search_filter_music),
(.gif, strings().searchFilterGIFs, theme.icons.search_filter_media),
(.file, strings().searchFilterFiles, theme.icons.search_filter_files)]
let collectTags: ()-> ([String], CGImage) = {
var values: [String] = []
let image: CGImage
if let tag = currentPeerTag {
values.append(tag.compactDisplayTitle.prefix(10))
}
if let tag = currentTag {
if let found = tags.first(where: { $0.0 == tag }) {
values.append(found.1)
image = found.2
} else {
image = theme.icons.search_filter
}
} else {
image = theme.icons.search_filter
}
return (values, image)
}
switch state.searchState {
case .Focus:
if searchView.customSearchControl == nil {
searchView.customSearchControl = CustomSearchController(clickHandler: { [weak self] control, updateTitle in
var items: [ContextMenuItem] = []
if state.forumPeer == nil {
items.append(ContextMenuItem(strings().chatListDownloadsTag, handler: { [weak self] in
updateSearchTags(SearchTags(messageTags: nil, peerTag: nil))
self?.showDownloads?()
}, itemImage: MenuAnimation.menu_save_as.value))
}
for tag in tags {
var append: Bool = false
if currentTag != tag.0 {
append = true
}
if append {
if let messagetag = tag.0 {
let itemImage: MenuAnimation?
switch messagetag {
case .photo:
itemImage = .menu_shared_media
case .video:
itemImage = .menu_video
case .webPage:
itemImage = .menu_copy_link
case .voiceOrInstantVideo:
itemImage = .menu_voice
case .gif:
itemImage = .menu_add_gif
case .file:
itemImage = .menu_file
default:
itemImage = nil
}
if let itemImage = itemImage {
items.append(ContextMenuItem(tag.1, handler: { [weak self] in
currentTag = tag.0
updateSearchTags(SearchTags(messageTags: currentTag, peerTag: currentPeerTag?.id))
let collected = collectTags()
updateTitle(collected.0, collected.1)
self?.hideDownloads?()
}, itemImage: itemImage.value))
}
}
}
}
let menu = ContextMenu()
for item in items {
menu.addItem(item)
}
let value = AppMenu(menu: menu)
if let event = NSApp.currentEvent {
value.show(event: event, view: control)
}
}, deleteTag: { [weak self] index in
var count: Int = 0
if currentTag != nil {
count += 1
}
if currentPeerTag != nil {
count += 1
}
if index == 1 || count == 1 {
currentTag = nil
}
if index == 0 {
currentPeerTag = nil
}
let collected = collectTags()
updateSearchTags(SearchTags(messageTags: currentTag, peerTag: currentPeerTag?.id))
self?.searchView.updateTags(collected.0, collected.1)
self?.hideDownloads?()
}, icon: theme.icons.search_filter)
}
updatePeerTag( { [weak self] updatedPeerTag in
guard let `self` = self else {
return
}
currentPeerTag = updatedPeerTag
updateSearchTags(SearchTags(messageTags: currentTag, peerTag: currentPeerTag?.id))
self.searchView.setString("")
let collected = collectTags()
self.searchView.updateTags(collected.0, collected.1)
})
updateMessageTags( { [weak self] updatedMessageTags in
guard let `self` = self else {
return
}
currentTag = updatedMessageTags
updateSearchTags(SearchTags(messageTags: currentTag, peerTag: currentPeerTag?.id))
let collected = collectTags()
self.searchView.updateTags(collected.0, collected.1)
})
case .None:
searchView.customSearchControl = nil
}
}
fileprivate func searchStateChanged(_ state: PeerListState, arguments: Arguments, animated: Bool, updateSearchTags: @escaping(SearchTags)->Void, updatePeerTag:@escaping(@escaping(Peer?)->Void)->Void, updateMessageTags: @escaping(@escaping(MessageTags?)->Void)->Void) {
self.updateTags(state, updateSearchTags: updateSearchTags, updatePeerTag: updatePeerTag, updateMessageTags: updateMessageTags)
self.updateState(state, arguments: arguments, animated: animated)
}
override func updateLocalizationAndTheme(theme: PresentationTheme) {
let theme = (theme as! TelegramPresentationTheme)
self.backgroundColor = theme.colors.background
compose.set(background: .clear, for: .Normal)
compose.set(background: .clear, for: .Hover)
compose.set(background: theme.colors.accent, for: .Highlight)
compose.set(image: theme.icons.composeNewChat, for: .Normal)
compose.set(image: theme.icons.composeNewChat, for: .Hover)
compose.set(image: theme.icons.composeNewChatActive, for: .Highlight)
compose.layer?.cornerRadius = .cornerRadius
super.updateLocalizationAndTheme(theme: theme)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layout() {
super.layout()
self.updateLayout(frame.size, transition: .immediate)
}
func updateLayout(_ size: NSSize, transition: ContainedViewLayoutTransition) {
guard let state = self.state else {
return
}
var offset: CGFloat
switch theme.controllerBackgroundMode {
case .background:
offset = 50
case .tiled:
offset = 50
default:
offset = 50
}
if state.splitState == .minimisize {
switch self.mode {
case .folder, .forum:
offset = 0
default:
break
}
}
var inset: CGFloat = 0
if let header = self.header {
offset += header.frame.height
transition.updateFrame(view: header, frame: NSMakeRect(0, inset, size.width, header.frame.height))
inset += header.frame.height
}
if let callView = self.callView {
offset += callView.frame.height
transition.updateFrame(view: callView, frame: NSMakeRect(0, inset, size.width, callView.frame.height))
inset += callView.frame.height
}
let componentSize = NSMakeSize(40, 30)
transition.updateFrame(view: self.containerView, frame: NSMakeRect(0, 0, size.width, offset))
var searchWidth = (size.width - 10 * 2)
if state.searchState != .Focus && state.mode.isPlain {
searchWidth -= (componentSize.width + 12)
}
if let _ = self.proxy {
searchWidth -= componentSize.width
}
if let _ = self.premiumStatus {
searchWidth -= componentSize.width
}
let searchRect = NSMakeRect(10, floorToScreenPixels(backingScaleFactor, inset + (offset - inset - componentSize.height)/2.0), searchWidth, componentSize.height)
transition.updateFrame(view: searchView, frame: searchRect)
transition.updateFrame(view: tableView, frame: NSMakeRect(0, offset, size.width, size.height - offset))
transition.updateFrame(view: backgroundView, frame: size.bounds)
if let downloads = downloads {
let rect = NSMakeRect(0, size.height - downloads.frame.height, size.width - .borderSize, downloads.frame.height)
transition.updateFrame(view: downloads, frame: rect)
}
if state.splitState == .minimisize {
transition.updateFrame(view: compose, frame: compose.centerFrame())
} else {
var controlPoint = NSMakePoint(size.width - 12, floorToScreenPixels(backingScaleFactor, (offset - componentSize.height)/2.0))
controlPoint.x -= componentSize.width
transition.updateFrame(view: compose, frame: CGRect(origin: controlPoint, size: componentSize))
if let view = proxy {
controlPoint.x -= componentSize.width
transition.updateFrame(view: view, frame: CGRect(origin: controlPoint, size: componentSize))
}
if let view = premiumStatus {
controlPoint.x -= componentSize.width
transition.updateFrame(view: view, frame: CGRect(origin: controlPoint, size: componentSize))
}
}
if let actionView = self.actionView {
transition.updateFrame(view: actionView, frame: CGRect(origin: CGPoint(x: 0, y: size.height - actionView.frame.height), size: actionView.frame.size))
}
}
func updateDownloads(_ state: DownloadsSummary.State, context: AccountContext, arguments: DownloadsControlArguments, animated: Bool) {
if !state.isEmpty {
let current: DownloadsControl
if let view = self.downloads {
current = view
} else {
current = DownloadsControl(frame: NSMakeRect(0, frame.height - 30, frame.width - .borderSize, 30))
self.downloads = current
addSubview(current, positioned: .above, relativeTo: self.tableView)
if animated {
current.layer?.animateAlpha(from: 0, to: 1, duration: 0.2)
current.layer?.animatePosition(from: NSMakePoint(current.frame.minX, current.frame.maxY), to: current.frame.origin)
}
}
current.update(state, context: context, arguments: arguments, animated: animated)
current.removeAllHandlers()
current.set(handler: { _ in
arguments.open()
}, for: .Click)
} else if let view = self.downloads {
self.downloads = nil
performSubviewPosRemoval(view, pos: NSMakePoint(0, frame.maxY), animated: true)
}
}
}
enum PeerListMode : Equatable {
case plain
case folder(EngineChatList.Group)
case filter(Int32)
case forum(PeerId)
var isPlain:Bool {
switch self {
case .plain:
return true
default:
return false
}
}
var groupId: EngineChatList.Group {
switch self {
case let .folder(groupId):
return groupId
default:
return .root
}
}
var filterId: Int32? {
switch self {
case let .filter(id):
return id
default:
return nil
}
}
var location: ChatListControllerLocation {
switch self {
case .plain:
return .chatList(groupId: .root)
case let .folder(group):
return .chatList(groupId: group._asGroup())
case let .forum(peerId):
return .forum(peerId: peerId)
case let .filter(filterId):
return .chatList(groupId: .group(filterId))
}
}
}
class PeersListController: TelegramGenericViewController<PeerListContainerView>, TableViewDelegate {
func findGroupStableId(for stableId: AnyHashable) -> AnyHashable? {
return nil
}
private let stateValue: Atomic<PeerListState?> = Atomic(value: nil)
private let stateSignal: ValuePromise<PeerListState?> = ValuePromise(nil, ignoreRepeated: true)
var stateUpdater: Signal<PeerListState?, NoError> {
return stateSignal.get()
}
private let progressDisposable = MetaDisposable()
private let createSecretChatDisposable = MetaDisposable()
private let actionsDisposable = DisposableSet()
private let followGlobal:Bool
private let searchOptions: AppSearchOptions
private var downloadsController: ViewController?
private var tempImportersContext: PeerInvitationImportersContext? = nil
let mode:PeerListMode
private(set) var searchController:SearchController? {
didSet {
if let controller = searchController {
genericView.customHandler.size = { [weak controller, weak self] size in
let frame = self?.genericView.tableView.frame ?? size.bounds
controller?.view.frame = frame
}
progressDisposable.set((controller.isLoading.get() |> deliverOnMainQueue).start(next: { [weak self] isLoading in
self?.genericView.searchView.isLoading = isLoading
}))
}
}
}
let topics: ForumChannelTopics?
init(_ context: AccountContext, followGlobal:Bool = true, mode: PeerListMode = .plain, searchOptions: AppSearchOptions = [.chats, .messages]) {
self.followGlobal = followGlobal
self.mode = mode
self.searchOptions = searchOptions
switch mode {
case let .forum(peerId):
self.topics = ForumChannelTopics(account: context.account, peerId: peerId)
default:
self.topics = nil
}
super.init(context)
self.bar = .init(height: !mode.isPlain ? 50 : 0)
}
override var redirectUserInterfaceCalls: Bool {
return true
}
override var responderPriority: HandlerPriority {
return .low
}
deinit {
progressDisposable.dispose()
createSecretChatDisposable.dispose()
actionsDisposable.dispose()
}
override func viewDidResized(_ size: NSSize) {
super.viewDidResized(size)
}
func showDownloads(animated: Bool) {
self.genericView.searchView.change(state: .Focus, true)
let context = self.context
if let controller = self.searchController {
let ready = controller.ready.get()
|> filter { $0 }
|> take(1)
_ = ready.start(next: { [weak self] _ in
guard let `self` = self else {
return
}
let controller: ViewController
if let current = self.downloadsController {
controller = current
} else {
controller = DownloadsController(context: context, searchValue: self.genericView.searchView.searchValue |> map { $0.request })
self.downloadsController = controller
controller.frame = self.genericView.tableView.frame
self.addSubview(controller.view)
if animated {
controller.view.layer?.animateAlpha(from: 0, to: 1, duration: 0.2)
controller.view.layer?.animateScaleSpring(from: 1.1, to: 1, duration: 0.2)
}
}
self.genericView.searchView.updateTags([strings().chatListDownloadsTag], theme.icons.search_filter_downloads)
})
}
}
private func hideDownloads(animated: Bool) {
if let downloadsController = downloadsController {
downloadsController.viewWillDisappear(animated)
self.downloadsController = nil
downloadsController.viewDidDisappear(animated)
let view = downloadsController.view
downloadsController.view.layer?.animateAlpha(from: 1, to: 0, duration: 0.2, removeOnCompletion: false, completion: { [weak view] _ in
view?.removeFromSuperview()
})
}
}
override func viewDidLoad() {
super.viewDidLoad()
let context = self.context
let mode = self.mode
genericView.showDownloads = { [weak self] in
self?.showDownloads(animated: true)
}
genericView.hideDownloads = { [weak self] in
self?.hideDownloads(animated: true)
}
let actionsDisposable = self.actionsDisposable
actionsDisposable.add((context.cancelGlobalSearch.get() |> deliverOnMainQueue).start(next: { [weak self] animated in
self?.genericView.searchView.cancel(animated)
}))
genericView.mode = mode
if followGlobal {
actionsDisposable.add((context.globalPeerHandler.get() |> deliverOnMainQueue).start(next: { [weak self] location in
guard let `self` = self else {return}
self.changeSelection(location)
if location == nil {
if !self.genericView.searchView.isEmpty {
_ = self.window?.makeFirstResponder(self.genericView.searchView.input)
}
}
}))
}
if self.navigationController?.modalAction is FWDNavigationAction {
self.setCenterTitle(strings().chatForwardActionHeader)
}
if self.navigationController?.modalAction is ShareInlineResultNavigationAction {
self.setCenterTitle(strings().chatShareInlineResultActionHeader)
}
genericView.tableView.delegate = self
let state = self.stateSignal
let stateValue = self.stateValue
let updateState:((PeerListState?)->PeerListState?) -> Void = { f in
state.set(stateValue.modify(f))
}
let layoutSignal = context.layoutValue
let proxy = proxySettings(accountManager: context.sharedContext.accountManager) |> mapToSignal { ps -> Signal<(ProxySettings, ConnectionStatus), NoError> in
return context.account.network.connectionStatus |> map { status -> (ProxySettings, ConnectionStatus) in
return (ps, status)
}
}
let peer: Signal<PeerEquatable?, NoError> = context.account.postbox.peerView(id: context.peerId) |> map { view in
if let peer = peerViewMainPeer(view) {
return PeerEquatable(peer)
} else {
return nil
}
}
let forumPeer: Signal<PeerListState.ForumData?, NoError>
if case let .forum(peerId) = self.mode {
let tempImportersContext = context.engine.peers.peerInvitationImporters(peerId: peerId, subject: .requests(query: nil))
self.tempImportersContext = tempImportersContext
let signal = combineLatest(context.account.postbox.peerView(id: peerId), getGroupCallPanelData(context: context, peerId: peerId), tempImportersContext.state)
forumPeer = signal |> mapToSignal { view, call, invitationState in
if let peer = peerViewMainPeer(view) as? TelegramChannel, let cachedData = view.cachedData as? CachedChannelData, peer.isForum {
let info: ChatActiveGroupCallInfo?
if let activeCall = cachedData.activeCall {
info = .init(activeCall: activeCall, data: call, callJoinPeerId: cachedData.callJoinPeerId, joinHash: nil, isLive: peer.isChannel || peer.isGigagroup)
} else {
info = nil
}
let membersCount = cachedData.participantsSummary.memberCount ?? 0
let online: Signal<Int32, NoError>
if membersCount < 200 {
online = context.peerChannelMemberCategoriesContextsManager.recentOnlineSmall(peerId: peerId)
} else {
online = context.peerChannelMemberCategoriesContextsManager.recentOnline(peerId: peerId)
}
return online |> map {
return .init(peer: peer, peerView: view, online: $0, call: info, invitationState: invitationState)
}
} else {
return .single(nil)
}
}
} else {
forumPeer = .single(nil)
}
let postbox = context.account.postbox
let previousPeerCache = Atomic<[PeerId: Peer]>(value: [:])
let previousActivities = Atomic<PeerListState.InputActivities?>(value: nil)
let inputActivities = context.account.allPeerInputActivities()
|> mapToSignal { activitiesByPeerId -> Signal<[PeerActivitySpace: [PeerListState.InputActivities.Activity]], NoError> in
var foundAllPeers = true
var cachedResult: [PeerActivitySpace: [PeerListState.InputActivities.Activity]] = [:]
previousPeerCache.with { dict -> Void in
for (chatPeerId, activities) in activitiesByPeerId {
var cachedChatResult: [PeerListState.InputActivities.Activity] = []
for (peerId, activity) in activities {
if let peer = dict[peerId] {
cachedChatResult.append(PeerListState.InputActivities.Activity(peer, activity))
} else {
foundAllPeers = false
break
}
cachedResult[chatPeerId] = cachedChatResult
}
}
}
if foundAllPeers {
return .single(cachedResult)
} else {
return postbox.transaction { transaction -> [PeerActivitySpace: [PeerListState.InputActivities.Activity]] in
var result: [PeerActivitySpace: [PeerListState.InputActivities.Activity]] = [:]
var peerCache: [PeerId: Peer] = [:]
for (chatPeerId, activities) in activitiesByPeerId {
var chatResult: [PeerListState.InputActivities.Activity] = []
for (peerId, activity) in activities {
if let peer = transaction.getPeer(peerId) {
chatResult.append(PeerListState.InputActivities.Activity(peer, activity))
peerCache[peerId] = peer
}
}
result[chatPeerId] = chatResult
}
let _ = previousPeerCache.swap(peerCache)
return result
}
}
}
|> map { activities -> PeerListState.InputActivities in
return previousActivities.modify { current in
var updated = false
let currentList: [PeerActivitySpace: [PeerListState.InputActivities.Activity]] = current?.activities ?? [:]
if currentList.count != activities.count {
updated = true
} else {
outer: for (space, currentValue) in currentList {
if let value = activities[space] {
if currentValue.count != value.count {
updated = true
break outer
} else {
for i in 0 ..< currentValue.count {
if currentValue[i] != value[i] {
updated = true
break outer
}
}
}
} else {
updated = true
break outer
}
}
}
if updated {
if activities.isEmpty {
return .init(activities: [:])
} else {
return .init(activities: activities)
}
} else {
return current
}
} ?? .init(activities: [:])
}
actionsDisposable.add(combineLatest(queue: .mainQueue(), proxy, layoutSignal, peer, forumPeer, inputActivities, appearanceSignal).start(next: { pref, layout, peer, forumPeer, inputActivities, _ in
updateState { state in
let state: PeerListState = .init(proxySettings: pref.0, connectionStatus: pref.1, splitState: layout, searchState: state?.searchState ?? .None, peer: peer, forumPeer: forumPeer, mode: mode, activities: inputActivities)
return state
}
}))
let pushController:(ViewController)->Void = { [weak self] c in
self?.context.bindings.rootNavigation().push(c)
}
let openProxySettings:()->Void = { [weak self] in
if let controller = self?.context.bindings.rootNavigation().controller as? InputDataController {
if controller.identifier == "proxy" {
return
}
}
let controller = proxyListController(accountManager: context.sharedContext.accountManager, network: context.account.network, share: { servers in
var message: String = ""
for server in servers {
message += server.link + "\n\n"
}
message = message.trimmed
showModal(with: ShareModalController(ShareLinkObject(context, link: message)), for: context.window)
}, pushController: { controller in
pushController(controller)
})
pushController(controller)
}
genericView.openProxy = { _ in
openProxySettings()
}
genericView.openStatus = { control in
let peer = stateValue.with { $0?.peer?.peer }
if let peer = peer as? TelegramUser {
let callback:(TelegramMediaFile, Int32?, CGRect?)->Void = { file, timeout, fromRect in
context.reactions.setStatus(file, peer: peer, timestamp: context.timestamp, timeout: timeout, fromRect: fromRect)
}
if control.popover == nil {
showPopover(for: control, with: PremiumStatusController(context, callback: callback, peer: peer), edge: .maxY, inset: NSMakePoint(-80, -35), static: true, animationMode: .reveal)
}
}
}
genericView.compose.contextMenu = { [weak self] in
let items = [ContextMenuItem(strings().composePopoverNewGroup, handler: { [weak self] in
self?.context.composeCreateGroup()
}, itemImage: MenuAnimation.menu_create_group.value),
ContextMenuItem(strings().composePopoverNewSecretChat, handler: { [weak self] in
self?.context.composeCreateSecretChat()
}, itemImage: MenuAnimation.menu_lock.value),
ContextMenuItem(strings().composePopoverNewChannel, handler: { [weak self] in
self?.context.composeCreateChannel()
}, itemImage: MenuAnimation.menu_channel.value)];
let menu = ContextMenu()
for item in items {
menu.addItem(item)
}
return menu
}
genericView.searchView.searchInteractions = SearchInteractions({ [weak self] state, animated in
switch state.state {
case .Focus:
assert(self?.searchController == nil)
self?.showSearchController(animated: animated)
case .None:
self?.hideSearchController(animated: animated)
}
updateState { current in
var current = current
current?.searchState = state.state
return current
}
}, { [weak self] state in
updateState { current in
var current = current
current?.searchState = state.state
return current
}
self?.searchController?.request(with: state.request)
}, responderModified: { [weak self] state in
self?.context.isInGlobalSearch = state.responder
})
let stateSignal = state.get()
|> filter { $0 != nil }
|> map { $0! }
let previousState: Atomic<PeerListState?> = Atomic(value: nil)
let arguments = Arguments(context: context, joinGroupCall: { info in
if case let .forum(peerId) = mode {
let join:(PeerId, Date?, Bool)->Void = { joinAs, _, _ in
_ = showModalProgress(signal: requestOrJoinGroupCall(context: context, peerId: peerId, joinAs: joinAs, initialCall: info.activeCall, initialInfo: info.data?.info, joinHash: nil), for: context.window).start(next: { result in
switch result {
case let .samePeer(callContext):
applyGroupCallResult(context.sharedContext, callContext)
case let .success(callContext):
applyGroupCallResult(context.sharedContext, callContext)
default:
alert(for: context.window, info: strings().errorAnError)
}
})
}
if let callJoinPeerId = info.callJoinPeerId {
join(callJoinPeerId, nil, false)
} else {
selectGroupCallJoiner(context: context, peerId: peerId, completion: join)
}
}
}, joinGroup: { peerId in
joinChannel(context: context, peerId: peerId)
}, openPendingRequests: { [weak self] in
if let importersContext = self?.tempImportersContext, case let .forum(peerId) = mode {
let navigation = context.bindings.rootNavigation()
navigation.push(RequestJoinMemberListController(context: context, peerId: peerId, manager: importersContext, openInviteLinks: { [weak navigation] in
navigation?.push(InviteLinksController(context: context, peerId: peerId, manager: nil))
}))
}
}, dismissPendingRequests: { peerIds in
if case let .forum(peerId) = mode {
FastSettings.dismissPendingRequests(peerIds, for: peerId)
updateState { current in
var current = current
current?.forumPeer?.invitationState = nil
return current
}
}
})
self.takeArguments = { [weak arguments] in
return arguments
}
actionsDisposable.add(stateSignal.start(next: { [weak self] state in
self?.updateState(state, previous: previousState.swap(state), arguments: arguments)
}))
centerBarView.set(handler: { _ in
switch mode {
case let .forum(peerId):
ForumUI.openInfo(peerId, context: context)
default:
break
}
}, for: .Click)
}
private var state: PeerListState? {
return self.stateValue.with { $0 }
}
private func updateState(_ state: PeerListState, previous: PeerListState?, arguments: Arguments) {
if previous?.forumPeer != state.forumPeer {
if state.forumPeer == nil {
switch self.mode {
case let .forum(peerId):
if state.splitState == .single {
let controller = ChatController(context: context, chatLocation: .peer(peerId))
self.navigationController?.push(controller)
self.navigationController?.removeImmediately(self, depencyReady: controller)
} else {
self.navigationController?.back()
}
default:
break
}
return
}
}
if previous?.splitState != state.splitState {
if case .minimisize = state.splitState {
if self.genericView.searchView.state == .Focus {
self.genericView.searchView.change(state: .None, false)
}
}
self.checkSearchMedia()
self.genericView.tableView.alwaysOpenRowsOnMouseUp = state.splitState == .single
self.genericView.tableView.reloadData()
self.requestUpdateBackBar()
}
setCenterTitle(self.defaultBarTitle)
if let forum = state.forumPeer {
let title = stringStatus(for: forum.peerView, context: context, onlineMemberCount: forum.online, expanded: true)
setCenterStatus(title.status.string)
} else {
setCenterStatus(nil)
}
self.genericView.searchStateChanged(state, arguments: arguments, animated: true, updateSearchTags: { [weak self] tags in
self?.searchController?.updateSearchTags(tags)
self?.sharedMediaWithToken(tags)
}, updatePeerTag: { [weak self] f in
self?.searchController?.setPeerAsTag = f
}, updateMessageTags: { [weak self] f in
self?.updateSearchMessageTags = f
})
if let forum = state.forumPeer {
if forum.peer.participationStatus == .left && previous?.forumPeer?.peer.participationStatus == .member {
self.navigationController?.back()
}
}
}
private var topicRightBar: ImageButton?
override func requestUpdateRightBar() {
super.requestUpdateRightBar()
topicRightBar?.style = navigationButtonStyle
topicRightBar?.set(image: theme.icons.chatActions, for: .Normal)
topicRightBar?.set(image: theme.icons.chatActionsActive, for: .Highlight)
topicRightBar?.setFrameSize(70, 50)
topicRightBar?.center()
}
private var takeArguments:()->Arguments? = {
return nil
}
override func getRightBarViewOnce() -> BarView {
switch self.mode {
case .forum:
let bar = BarView(70, controller: self)
let button = ImageButton()
bar.addSubview(button)
let context = self.context
self.topicRightBar = button
button.contextMenu = { [weak self] in
let menu = ContextMenu()
if let peer = self?.state?.forumPeer {
var items: [ContextMenuItem] = []
let chatController = context.bindings.rootNavigation().controller as? ChatController
let infoController = context.bindings.rootNavigation().controller as? PeerInfoController
let topicController = context.bindings.rootNavigation().controller as? InputDataController
if infoController == nil || (infoController?.peerId != peer.peer.id || infoController?.threadInfo != nil) {
items.append(ContextMenuItem(strings().forumTopicContextInfo, handler: {
ForumUI.openInfo(peer.peer.id, context: context)
}, itemImage: MenuAnimation.menu_show_info.value))
}
if chatController == nil || (chatController?.chatInteraction.chatLocation != .peer(peer.peer.id)) {
items.append(ContextMenuItem(strings().forumTopicContextShowAsMessages, handler: { [weak self] in
self?.open(with: .chatId(.chatList(peer.peer.id), peer.peer.id, -1), forceAnimated: true)
}, itemImage: MenuAnimation.menu_read.value))
}
if let call = self?.state?.forumPeer?.call {
if call.data?.groupCall == nil {
if let data = call.data, data.participantCount == 0 && call.activeCall.scheduleTimestamp == nil {
items.append(ContextMenuItem(strings().peerInfoActionVoiceChat, handler: { [weak self] in
self?.takeArguments()?.joinGroupCall(call)
}, itemImage: MenuAnimation.menu_video_chat.value))
}
}
}
if peer.peer.isAdmin && peer.peer.hasPermission(.manageTopics) {
if topicController?.identifier != "ForumTopic" {
if !items.isEmpty {
items.append(ContextSeparatorItem())
}
items.append(ContextMenuItem(strings().forumTopicContextNew, handler: {
ForumUI.createTopic(peer.peer.id, context: context)
}, itemImage: MenuAnimation.menu_edit.value))
}
}
if !items.isEmpty {
for item in items {
menu.addItem(item)
}
}
}
return menu
}
return bar
default:
break
}
return super.getRightBarViewOnce()
}
override var defaultBarTitle: String {
switch self.mode {
case .folder:
return strings().chatListArchivedChats
case .forum:
return state?.forumPeer?.peer.displayTitle ?? super.defaultBarTitle
default:
return super.defaultBarTitle
}
}
private func checkSearchMedia() {
let destroy:()->Void = { [weak self] in
if let previous = self?.mediaSearchController {
self?.context.bindings.rootNavigation().removeImmediately(previous)
}
}
guard context.layout == .dual else {
destroy()
return
}
guard let _ = self.searchController else {
destroy()
return
}
}
private weak var mediaSearchController: PeerMediaController?
private var updateSearchMessageTags: ((MessageTags?)->Void)? = nil
private func sharedMediaWithToken(_ tags: SearchTags) -> Void {
let destroy:()->Void = { [weak self] in
if let previous = self?.mediaSearchController {
self?.context.bindings.rootNavigation().removeImmediately(previous)
}
}
guard context.layout == .dual else {
destroy()
return
}
guard let searchController = self.searchController else {
destroy()
return
}
guard let messageTags = tags.messageTags else {
destroy()
return
}
if let peerId = tags.peerTag {
let onDeinit: ()->Void = { [weak self] in
self?.updateSearchMessageTags?(nil)
}
let navigation = context.bindings.rootNavigation()
let signal = searchController.externalSearchMessages
|> filter { $0 != nil && $0?.tags == messageTags }
let controller = PeerMediaController(context: context, peerId: peerId, isProfileIntended: false, externalSearchData: PeerMediaExternalSearchData(initialTags: messageTags, searchResult: signal, loadMore: { }))
controller.onDeinit = onDeinit
navigation.push(controller, false, style: nil)
if let previous = self.mediaSearchController {
previous.onDeinit = nil
navigation.removeImmediately(previous, depencyReady: controller)
}
self.mediaSearchController = controller
}
}
override func requestUpdateBackBar() {
self.leftBarView.minWidth = 70
super.requestUpdateBackBar()
}
override func getLeftBarViewOnce() -> BarView {
let view = BackNavigationBar(self, canBeEmpty: true)
view.minWidth = 70
return view
}
override func backSettings() -> (String, CGImage?) {
return context.layout == .minimisize ? ("", theme.icons.instantViewBack) : super.backSettings()
}
func changeSelection(_ location: ChatLocation?) {
if let location = location {
var id: UIChatListEntryId
switch location {
case .peer:
id = .chatId(.chatList(location.peerId), location.peerId, -1)
case let .thread(data):
let threadId = makeMessageThreadId(data.messageId)
switch self.mode {
case .plain, .filter, .folder:
id = .forum(location.peerId)
case .forum:
id = .chatId(.forum(threadId), location.peerId, -1)
}
}
if self.genericView.tableView.item(stableId: id) == nil {
let fId = UIChatListEntryId.forum(location.peerId)
if self.genericView.tableView.item(stableId: fId) != nil {
id = fId
}
}
self.genericView.tableView.changeSelection(stableId: id)
} else {
self.genericView.tableView.changeSelection(stableId: nil)
}
}
private func showSearchController(animated: Bool) {
if searchController == nil {
let initialTags: SearchTags
let target: SearchController.Target
switch self.mode {
case let .forum(peerId):
initialTags = .init(messageTags: nil, peerTag: nil)
target = .forum(peerId)
default:
initialTags = .init(messageTags: nil, peerTag: nil)
target = .common(.root)
}
let rect = self.genericView.tableView.frame
let frame = rect
let searchController = SearchController(context: self.context, open: { [weak self] (id, messageId, close) in
if let id = id {
self?.open(with: id, messageId: messageId, close: close)
} else {
self?.genericView.searchView.cancel(true)
}
}, options: self.searchOptions, frame: frame, target: target, tags: initialTags)
searchController.pinnedItems = self.collectPinnedItems
self.searchController = searchController
searchController.defaultQuery = self.genericView.searchView.query
searchController.navigationController = self.navigationController
searchController.viewWillAppear(true)
searchController.loadViewIfNeeded()
let signal = searchController.ready.get() |> take(1)
_ = signal.start(next: { [weak searchController, weak self] _ in
if let searchController = searchController {
if animated {
searchController.view.layer?.animateAlpha(from: 0.0, to: 1.0, duration: 0.25, completion:{ [weak self] complete in
if complete {
self?.searchController?.viewDidAppear(animated)
}
})
searchController.view.layer?.animateScaleSpring(from: 1.05, to: 1.0, duration: 0.4, bounce: false)
searchController.view.layer?.animatePosition(from: NSMakePoint(rect.minX, rect.minY + 15), to: rect.origin, duration: 0.4, timingFunction: .spring)
} else {
searchController.viewDidAppear(animated)
}
self?.addSubview(searchController.view)
}
})
}
}
private func hideSearchController(animated: Bool) {
if let downloadsController = downloadsController {
downloadsController.viewWillDisappear(animated)
self.downloadsController = nil
downloadsController.viewDidDisappear(animated)
let view = downloadsController.view
downloadsController.view.layer?.animateAlpha(from: 1, to: 0, duration: 0.2, removeOnCompletion: false, completion: { [weak view] _ in
view?.removeFromSuperview()
})
}
if let searchController = self.searchController {
let animated = animated && searchController.didSetReady
searchController.viewWillDisappear(animated)
searchController.view.layer?.opacity = animated ? 1.0 : 0.0
searchController.viewDidDisappear(true)
self.searchController = nil
self.genericView.tableView.isHidden = false
self.genericView.tableView.change(opacity: 1, animated: animated)
let view = searchController.view
searchController.view._change(opacity: 0, animated: animated, duration: 0.25, timingFunction: CAMediaTimingFunctionName.spring, completion: { [weak view] completed in
view?.removeFromSuperview()
})
if animated {
searchController.view.layer?.animateScaleSpring(from: 1.0, to: 1.05, duration: 0.4, removeOnCompletion: false, bounce: false)
genericView.tableView.layer?.animateScaleSpring(from: 0.95, to: 1.00, duration: 0.4, removeOnCompletion: false, bounce: false)
}
}
if let controller = mediaSearchController {
context.bindings.rootNavigation().removeImmediately(controller, upNext: false)
}
}
override func focusSearch(animated: Bool, text: String? = nil) {
genericView.searchView.change(state: .Focus, animated)
if let text = text {
genericView.searchView.setString(text)
}
}
var collectPinnedItems:[PinnedItemId] {
return []
}
public override func escapeKeyAction() -> KeyHandlerResult {
guard context.layout != .minimisize else {
return .invoked
}
if genericView.tableView.highlightedItem() != nil {
genericView.tableView.cancelHighlight()
return .invoked
}
if genericView.searchView.state == .None {
return genericView.searchView.changeResponder() ? .invoked : .rejected
} else if genericView.searchView.state == .Focus && genericView.searchView.query.length > 0 {
genericView.searchView.change(state: .None, true)
return .invoked
}
return .rejected
}
public override func returnKeyAction() -> KeyHandlerResult {
if let highlighted = genericView.tableView.highlightedItem() {
_ = genericView.tableView.select(item: highlighted)
return .invoked
}
return .rejected
}
func open(with entryId: UIChatListEntryId, messageId:MessageId? = nil, initialAction: ChatInitialAction? = nil, close:Bool = true, addition: Bool = false, forceAnimated: Bool = false) ->Void {
let navigation = context.bindings.rootNavigation()
var addition = addition
var close = close
if let searchTags = self.searchController?.searchTags {
if searchTags.peerTag != nil && searchTags.messageTags != nil {
addition = true
}
if !searchTags.isEmpty {
close = false
}
}
switch entryId {
case let .chatId(type, peerId, _):
switch type {
case let .chatList(peerId):
if let modalAction = navigation.modalAction as? FWDNavigationAction, peerId == context.peerId {
_ = Sender.forwardMessages(messageIds: modalAction.messages.map{$0.id}, context: context, peerId: context.peerId, replyId: nil).start()
_ = showModalSuccess(for: context.window, icon: theme.icons.successModalProgress, delay: 1.0).start()
modalAction.afterInvoke()
navigation.removeModalAction()
} else {
if let current = navigation.controller as? ChatController, peerId == current.chatInteraction.peerId, let messageId = messageId, current.mode == .history {
current.chatInteraction.focusMessageId(nil, messageId, .center(id: 0, innerId: nil, animated: false, focus: .init(focus: true), inset: 0))
} else {
let chatLocation: ChatLocation = .peer(peerId)
let chat: ChatController
if addition {
chat = ChatAdditionController(context: context, chatLocation: chatLocation, messageId: messageId)
} else {
chat = ChatController(context: self.context, chatLocation: chatLocation, messageId: messageId, initialAction: initialAction)
}
let animated = context.layout == .single || forceAnimated
navigation.push(chat, context.layout == .single || forceAnimated, style: animated ? .push : ViewControllerStyle.none)
}
}
case let .forum(threadId):
_ = ForumUI.openTopic(threadId, peerId: peerId, context: context, messageId: messageId).start()
}
case let .groupId(groupId):
self.navigationController?.push(ChatListController(context, modal: false, mode: .folder(groupId)))
case let .forum(peerId):
ForumUI.open(peerId, context: context)
case .reveal:
break
case .empty:
break
case .loading:
break
}
if close {
self.genericView.searchView.cancel(true)
}
}
func longSelect(row: Int, item: TableRowItem) {
}
func selectionWillChange(row:Int, item:TableRowItem, byClick: Bool) -> Bool {
return true
}
func selectionDidChange(row:Int, item:TableRowItem, byClick:Bool, isNew:Bool) -> Void {
}
func isSelectable(row:Int, item:TableRowItem) -> Bool {
return true
}
override func updateLocalizationAndTheme(theme: PresentationTheme) {
super.updateLocalizationAndTheme(theme: theme)
}
private var effectiveTableView: TableView {
switch genericView.searchView.state {
case .Focus:
return searchController?.genericView ?? genericView.tableView
case .None:
return genericView.tableView
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if context.layout == .single && animated {
context.globalPeerHandler.set(.single(nil))
}
context.window.set(handler: { [weak self] _ in
if let strongSelf = self {
return strongSelf.escapeKeyAction()
}
return .invokeNext
}, with: self, for: .Escape, priority:.low)
context.window.set(handler: { [weak self] _ in
if let strongSelf = self {
return strongSelf.returnKeyAction()
}
return .invokeNext
}, with: self, for: .Return, priority:.low)
context.window.set(handler: { [weak self] _ -> KeyHandlerResult in
if let item = self?.effectiveTableView.selectedItem(), item.index > 0 {
self?.effectiveTableView.selectPrev()
}
return .invoked
}, with: self, for: .UpArrow, priority: .medium, modifierFlags: [.option])
context.window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.effectiveTableView.selectNext()
return .invoked
}, with: self, for: .DownArrow, priority:.medium, modifierFlags: [.option])
context.window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.effectiveTableView.selectNext(turnDirection: false)
return .invoked
}, with: self, for: .Tab, priority: .modal, modifierFlags: [.control])
context.window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.effectiveTableView.selectPrev(turnDirection: false)
return .invoked
}, with: self, for: .Tab, priority: .modal, modifierFlags: [.control, .shift])
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
context.window.removeAllHandlers(for: self)
}
}
|
50a021e0dd652ab7dbc97cfe34eada9f
| 39.722503 | 272 | 0.539213 | false | false | false | false |
yashvyas29/YVSwiftTableForms
|
refs/heads/master
|
YVSwiftTableFormsExample/Resources/YVSwiftTableForms/YVSubClasses/YVTextFieldValidator.swift
|
gpl-3.0
|
1
|
//
// YVTextFieldValidator.swift
// YVSwiftTableForms
//
// Created by Yash on 10/05/16.
// Copyright © 2016 Yash. All rights reserved.
//
import UIKit
let numberCharacterSet = NSCharacterSet.decimalDigitCharacterSet()
let alphabetCharacterSet : NSCharacterSet = NSCharacterSet(charactersInString: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
let specialSymbolsCharacterSet : NSCharacterSet = NSCharacterSet(charactersInString: "!~`@#$%^&*-+();:=_{}[],.<>?\\/|\"\'")
class YVTextFieldValidator: UITextField, UITextFieldDelegate {
//** properties which will decide which kind of validation user wants
var ParentDelegate : AnyObject?
var checkForEmptyTextField : Bool = false
var allowOnlyNumbers : Bool = false
var allowOnlyAlphabets : Bool = false
var restrictSpecialSymbolsOnly : Bool = false
var checkForValidEmailAddress : Bool = false
var restrictTextFieldToLimitedCharecters : Bool = false
var setNumberOfCharectersToBeRestricted : Int = 0
var allowToShowAlertView : Bool = false
var alertControllerForNumberOnly = UIAlertController()
var alertControllerForAlphabetsOnly = UIAlertController()
var alertControllerForSpecialSymbols = UIAlertController()
var alertControllerForInvalidEmailAddress = UIAlertController()
//MARK: awakeFromNib
// Setting the delegate to Class's instance
override func awakeFromNib() {
super.awakeFromNib()
self.delegate = self
}
//MARK: validation methods
// 01. This method will check if there are any blank textFields in class
class func checkIfAllFieldsAreFilled(view:UIView) -> Bool{
let subviews : NSArray = view.subviews
if(subviews.count == 0){
return false
}
for currentObject in subviews{
if let currentObject = currentObject as? UITextField {
if((currentObject.text?.isEmpty) != nil){
YVTextFieldValidator.shaketextField(currentObject)
}
}
self.checkIfAllFieldsAreFilled(currentObject as! UIView)
}
return true
}
// 02. This method will check if there are any white space in the textField.
class func checkForWhiteSpaceInTextField(inputString : String) -> String{
let trimmedString = inputString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
return trimmedString
}
// 03. This method will allow only numbers in the textField.
func allowOnlyNumbersInTextField(string : String)->Bool{
let numberCharacterSet = NSCharacterSet.decimalDigitCharacterSet()
let inputString = string
let range = inputString.rangeOfCharacterFromSet(numberCharacterSet)
print(inputString)
// range will be nil if no numbers are found
if range != nil {
return true
}
else {
return false
// do your stuff
}
}
// 04. This method will allow only alphabets in the textField.
func allowOnlyAlphabetsInTextField(string : String)->Bool{
let inputString = string
let range = inputString.rangeOfCharacterFromSet(alphabetCharacterSet)
print(inputString)
// range will be nil if no alphabet are found
if range != nil {
return true
}
else {
return false
// do your stuff
}
}
// 05. This method will restrict only special symbols in the textField.
func restrictSpecialSymbols(string : String) -> Bool
{
let range = string.rangeOfCharacterFromSet(specialSymbolsCharacterSet.invertedSet)
print(string)
// range will be nil if no specialSymbol are found
if range != nil {
return true
}
else {
return false
// do your stuff
}
}
//MARK: UITextFieldDelegate
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
if(checkForValidEmailAddress){
let emailReg = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
let range = textField.text!.rangeOfString(emailReg, options:.RegularExpressionSearch)
let result = range != nil ? true : false
print(result)
if(result){
ParentDelegate as! UIViewController
ParentDelegate!.presentViewController(alertControllerForInvalidEmailAddress, animated: true, completion: nil)
return false
}
}
return true
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if(allowOnlyNumbers){
if(string == ""){
return true
}
let flag : Bool = self.allowOnlyNumbersInTextField(string)
if(flag){
return true
}
else{
if(allowToShowAlertView){
ParentDelegate as! UIViewController
ParentDelegate!.presentViewController(alertControllerForNumberOnly, animated: true, completion: nil)
return false
}
}
}
else if(allowOnlyAlphabets){
if(string == "") {
return true
}
let flag : Bool = self.allowOnlyAlphabetsInTextField(string)
if(flag) {
return true
}
else {
if(allowToShowAlertView) {
ParentDelegate as! UIViewController
ParentDelegate!.presentViewController(alertControllerForAlphabetsOnly, animated: true, completion: nil)
return false
}
}
}
else if(restrictSpecialSymbolsOnly){
if(string == ""){
return true
}
let flag : Bool = self.restrictSpecialSymbols(string)
if(flag){
return true
}
else{
if(allowToShowAlertView){
ParentDelegate as! UIViewController
ParentDelegate!.presentViewController(alertControllerForSpecialSymbols, animated: true, completion: nil)
return false
}
}
}
else if(restrictTextFieldToLimitedCharecters){
let newLength = textField.text!.characters.count + string.characters.count - range.length
return newLength <= setNumberOfCharectersToBeRestricted
}
else{
return true
}
return false
}
//MARK: Setter methods
func setFlagForAllowNumbersOnly(flagForNumbersOnly : Bool){
allowOnlyNumbers = flagForNumbersOnly
}
func setFlagForAllowAlphabetsOnly(flagForAlphabetsOnly : Bool){
allowOnlyAlphabets = flagForAlphabetsOnly
}
func setFlagForRestrictSpecialSymbolsOnly(RestrictSpecialSymbols : Bool){
restrictSpecialSymbolsOnly = RestrictSpecialSymbols
}
func setFlagForcheckForValidEmailAddressOnly(flagForValidEmailAddress : Bool){
checkForValidEmailAddress = flagForValidEmailAddress
}
func setFlagForLimitedNumbersOFCharecters(numberOfCharacters : Int,flagForLimitedNumbersOfCharacters : Bool){
restrictTextFieldToLimitedCharecters = flagForLimitedNumbersOfCharacters
setNumberOfCharectersToBeRestricted = numberOfCharacters
}
//MARK: show alert methods
func showAlertForNumberOnly(title: String, message: String, buttonTitles : NSArray, buttonActions: NSArray){
alertControllerForNumberOnly = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
for i in 0 ..< buttonActions.count {
let count = i
let buttonAction = UIAlertAction(title: buttonTitles[count] as? String, style: UIAlertActionStyle.Default, handler: { (UIAlertAction) -> Void in
if(buttonActions.count > 0){
let methodName = buttonActions[count] as! String
print(methodName)
NSTimer.scheduledTimerWithTimeInterval(0, target: self.ParentDelegate as! UIViewController, selector: Selector(methodName), userInfo: nil, repeats: false)
}
})
alertControllerForNumberOnly.addAction(buttonAction)
}
}
func showAlertForAlphabetsOnly(title: String, message: String, buttonTitles : NSArray, buttonActions: NSArray){
alertControllerForAlphabetsOnly = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
for i in 0 ..< buttonActions.count {
let count = i
let buttonAction = UIAlertAction(title: buttonTitles[count] as? String, style: UIAlertActionStyle.Default, handler: { (UIAlertAction) -> Void in
if(buttonActions.count > 0){
let methodName = buttonActions[count] as! String
print(methodName)
NSTimer.scheduledTimerWithTimeInterval(0, target: self.ParentDelegate as! UIViewController, selector: Selector(methodName), userInfo: nil, repeats: false)
}
})
alertControllerForAlphabetsOnly.addAction(buttonAction)
}
}
func showAlertForSpecialSymbolsOnly(title: String, message: String, buttonTitles : NSArray, buttonActions: NSArray){
alertControllerForSpecialSymbols = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
for i in 0 ..< buttonActions.count {
let count = i
let buttonAction = UIAlertAction(title: buttonTitles[count] as? String, style: UIAlertActionStyle.Default, handler: { (UIAlertAction) -> Void in
if(buttonActions.count > 0){
let methodName = buttonActions[count] as! String
print(methodName)
NSTimer.scheduledTimerWithTimeInterval(0, target: self.ParentDelegate as! UIViewController, selector: Selector(methodName), userInfo: nil, repeats: false)
}
})
alertControllerForSpecialSymbols.addAction(buttonAction)
}
}
func showAlertForinvalidEmailAddrress(title: String, message: String, buttonTitles : NSArray, buttonActions: NSArray){
alertControllerForInvalidEmailAddress = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
for i in 0 ..< buttonActions.count {
let count = i
let buttonAction = UIAlertAction(title: buttonTitles[count] as? String, style: UIAlertActionStyle.Default, handler: { (UIAlertAction) -> Void in
if(buttonActions.count > 0){
let methodName = buttonActions[count] as! String
print(methodName)
NSTimer.scheduledTimerWithTimeInterval(0, target: self.ParentDelegate as! UIViewController, selector: Selector(methodName), userInfo: nil, repeats: false)
}
})
alertControllerForInvalidEmailAddress.addAction(buttonAction)
}
}
//MARK: Shake TextField
class func shaketextField(textfield : UITextField) {
let shake:CABasicAnimation = CABasicAnimation(keyPath: "position")
shake.duration = 0.1
shake.repeatCount = 2
shake.autoreverses = true
let from_point:CGPoint = CGPointMake(textfield.center.x - 5, textfield.center.y)
let from_value:NSValue = NSValue(CGPoint: from_point)
let to_point:CGPoint = CGPointMake(textfield.center.x + 5, textfield.center.y)
let to_value:NSValue = NSValue(CGPoint: to_point)
shake.fromValue = from_value
shake.toValue = to_value
textfield.layer.addAnimation(shake, forKey: "position")
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
}
|
0722126da92eb8679acb3b7308b1fd56
| 33.516971 | 174 | 0.593116 | false | false | false | false |
marsal-silveira/Tonight
|
refs/heads/master
|
Tonight/src/Utils/Logger.swift
|
mit
|
1
|
//
// Logger.swift
// Tonight
//
// Created by Marsal on 29/02/16.
// Copyright © 2016 Marsal Silveira. All rights reserved.
//
class Logger
{
static func log(logMessage: String = "", file: String = __FILE__, function: String = __FUNCTION__, line: Int = __LINE__)
{
// __FILE__ : String - The name of the file in which it appears.
// __FUNCTION__ : String - The name of the declaration in which it appears.
// __LINE__ : Int - The line number on which it appears.
let fileURL = NSURL(fileURLWithPath: file)
let className = fileURL.lastPathComponent!.stringByReplacingOccurrencesOfString(fileURL.pathExtension!, withString: "")
print("[\(className)\(function)][\(line)] \(logMessage)")
}
}
|
7d0b576e6a4ebb2743497567270962f1
| 35.333333 | 127 | 0.62336 | false | false | false | false |
zpz1237/NirTableHeaderView
|
refs/heads/master
|
TableHeaderViewAlbum/TableViewController.swift
|
mit
|
1
|
//
// TableViewController.swift
// TableHeaderViewAlbum
//
// Created by Nirvana on 10/28/15.
// Copyright © 2015 NSNirvana. All rights reserved.
//
import UIKit
class TableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
//你想要展示的tableHeaderView
let imgView = UIImageView(frame: CGRectMake(0, 0, CGRectGetWidth(self.tableView.frame), 64))
imgView.contentMode = .ScaleAspectFill
imgView.image = UIImage(named: "header")
//若含有navigationController
//一、取消ScrollViewInsets自动调整
self.automaticallyAdjustsScrollViewInsets = false
//二、隐藏NavBar
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .Default)
self.navigationController?.navigationBar.shadowImage = UIImage()
//类型零
//let headerView = NirTableHeaderView(subview: imgView, andType: 0)
//类型一
//let headerView = NirTableHeaderView(subview: imgView, andType: 1)
//类型二
//let headerView = NirTableHeaderView(subview: imgView, andType: 2)
//类型三
//let headerView = NirTableHeaderView(subview: imgView, andType: 3)
//headerView.tableView = self.tableView
//headerView.maximumOffsetY = -90
//类型四
let headerView = NirTableHeaderView(subview: imgView, andType: 4)
self.tableView.tableHeaderView = headerView
self.tableView.delegate = self
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
// MARK: - Table view delegate
override func scrollViewDidScroll(scrollView: UIScrollView) {
let headerView = self.tableView.tableHeaderView as! NirTableHeaderView
headerView.layoutHeaderViewForScrollViewOffset(scrollView.contentOffset)
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 20
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("nirCell", forIndexPath: indexPath)
cell.textLabel?.text = "Just Try"
return cell
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .LightContent
}
}
extension UINavigationController {
override public func childViewControllerForStatusBarStyle() -> UIViewController? {
return self.topViewController
}
}
|
ba1548140446cf04b9f3e552e632b713
| 33.483516 | 118 | 0.678776 | false | false | false | false |
ontouchstart/swift3-playground
|
refs/heads/playgroundbook
|
Learn to Code 1.playgroundbook/Contents/Chapters/Document5.playgroundchapter/Pages/Exercise2.playgroundpage/Sources/Assessments.swift
|
mit
|
1
|
//
// Assessments.swift
//
// Copyright (c) 2016 Apple Inc. All Rights Reserved.
//
let solution = "```swift\nmoveForward()\n\nif isOnClosedSwitch {\n toggleSwitch()\n} else if isOnGem {\n collectGem()\n}\n\nmoveForward()\nif isOnClosedSwitch {\n toggleSwitch()\n} else if isOnGem {\n collectGem()\n}\n```"
import PlaygroundSupport
public func assessmentPoint() -> AssessmentResults {
let checker = ContentsChecker(contents: PlaygroundPage.current.text)
let success = "### Impressive! \nYou now know how to write your own `else if` statements.\n\n[**Next Page**](@next)"
var hints = [
"Start by moving Byte to the first tile and use an `if` statement to check whether Byte is on a closed switch.",
"Add an `if` statement and use the condition `isOnClosedSwitch` to check whether you should toggle a switch. Then add an `else if` block by tapping the word `if` in your code area and tapping \"Add 'else if' Statement\".",
"If Byte is on a closed switch, toggle it. Otherwise (the “else” part), if Byte is on a gem, collect it.",
]
if !checker.didUseConditionalStatement("if") {
hints[0] = "After you've added an `if` statement, tap the word `if` in your code and use the \"Add 'else if' Statement\" option."
hints.remove(at: 1)
} else if !checker.didUseConditionalStatement("else if") {
hints[0] = "To add an `else if` statement, tap the word `if` in your code and then tap \"Add else if statement\"."
}
return updateAssessment(successMessage: success, failureHints: hints, solution: solution)
}
|
e2c950d4a2a7fa398b2a9dcfa972d2f7
| 49.84375 | 234 | 0.668101 | false | false | false | false |
takeotsuchida/Watch-Connectivity
|
refs/heads/master
|
Connectivity WatchKit Extension/GlanceController.swift
|
gpl-2.0
|
1
|
//
// GlanceController.swift
// Connectivity WatchKit Extension
//
// Created by Takeo Tsuchida on 2015/07/31.
// Copyright © 2015年 MUMPK Limited Partnership. All rights reserved.
//
import WatchKit
import Foundation
import WatchConnectivity
class GlanceController: WKInterfaceController {
@IBOutlet var transferredImage: WKInterfaceImage!
@IBOutlet var contextLabel: WKInterfaceLabel!
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
// Configure interface objects here.
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
if let context = WCSession.defaultSession().receivedApplicationContext as? [String:String],
message = context[dataId] {
contextLabel.setText(message)
}
let url = try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory,
inDomain: .UserDomainMask, appropriateForURL: nil, create: false)
let urls = try! NSFileManager.defaultManager().contentsOfDirectoryAtURL(url, includingPropertiesForKeys: nil, options: .SkipsHiddenFiles)
for url in urls {
if let data = NSData(contentsOfURL: url), image = UIImage(data: data) {
self.transferredImage.setImage(image)
break
}
}
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
}
|
8d4af349b00b54a62454a4cfb37733be
| 32.4375 | 145 | 0.672897 | false | false | false | false |
jshultz/ios9-swift2-shake-app-random-sounds
|
refs/heads/master
|
shake-that-app/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// shake-that-app
//
// Created by Jason Shultz on 10/22/15.
// Copyright © 2015 HashRocket. All rights reserved.
//
import UIKit
import AVFoundation
class ViewController: UIViewController {
var player:AVAudioPlayer = AVAudioPlayer() // Create a player
var tune:String = ""
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let swipeRight = UISwipeGestureRecognizer(target: self, action: "swiped:")
swipeRight.direction = UISwipeGestureRecognizerDirection.Right
self.view.addGestureRecognizer(swipeRight)
let swipeUp = UISwipeGestureRecognizer(target: self, action: "swiped:")
swipeUp.direction = UISwipeGestureRecognizerDirection.Up
self.view.addGestureRecognizer(swipeUp)
}
override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent?) {
if event?.subtype == UIEventSubtype.MotionShake {
print("device was shaken, not stirred")
}
}
func playSound(tune:String) {
let audioPath = NSBundle.mainBundle().pathForResource(tune, ofType: "mp3")! // path to audio file
do {
try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath))
} catch {
print("siomething went wrong")
}
}
func swiped(gesture:UIGestureRecognizer){
if let swipegesture = gesture as? UISwipeGestureRecognizer {
switch swipegesture.direction {
case UISwipeGestureRecognizerDirection.Right:
print("swipe right")
case UISwipeGestureRecognizerDirection.Up:
let audioPath = NSBundle.mainBundle().pathForResource("mozart-k311-3-sasaki", ofType: "mp3")! // path to audio file
print("swipe up")
default:
break
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
02101d2e15c42eb11686ca68c3e70f12
| 27.746835 | 131 | 0.598855 | false | false | false | false |
searchs/grobox
|
refs/heads/master
|
learn.swift
|
mit
|
1
|
//Getting to know Swift Programming Language enough to build Mobile Automated Test Framework
import UIKit
var str = "Look what I can do"
2+2
var myVar: String = "Mobo Robots"
var myInt: Int = 18
var hungry: Bool = true
var costOfCandy: Double = 1.325
myVar = "Bad Robots"
let life: Int = 42
let pi: Double = 3.142
let canTouchThis: Bool = false
let captain: String = "Kirk"
//captain = "Hook" //immutable: gives an error
let favoriteNumber = 33
var dullNumber = 7
let batmanCoolness = 10
var supermanCoolness = 9
var aquamanCoolness = 1
batmanCoolness < aquamanCoolness
supermanCoolness >= 8
batmanCoolness == (aquamanCoolness + supermanCoolness)
batmanCoolness > aquamanCoolness && batmanCoolness == (aquamanCoolness + supermanCoolness)
batmanCoolness < supermanCoolness || aquamanCoolness < supermanCoolness
var spidermanCoolness = 6
if (batmanCoolness > spidermanCoolness) {
spidermanCoolness = spidermanCoolness - 1
} else if (batmanCoolness >= spidermanCoolness) {
spidermanCoolness = spidermanCoolness - 1
} else {
spidermanCoolness = spidermanCoolness + 1
}
print("Getting Swift into fingers!")
var apples = 5
print("Sally has \(apples) apples ")
var secondsLeft = 3
while (secondsLeft > 0) {
print(secondsLeft)
secondsLeft = secondsLeft - 1
}
print("Blast off!")
var cokesLeft = 7
var fantasLeft = 4
while(cokesLeft > 0) {
print("You have \(cokesLeft) Cokes left.")
cokesLeft = cokesLeft - 1
if(cokesLeft <= fantasLeft) {
break
}
}
print("You stop drinking Cokes.")
var numbers = 0
while(numbers <= 10) {
if(numbers == 9) {
numbers = numbers + 1
continue
}
print(numbers)
numbers = numbers + 1
}
var optionalNumber: Int? = 5
optionalNumber = nil
if let number = optionalNumber {
print(number)
}
else {
print("Nothing here")
}
var languagesLearned: String = "3"
var languagesLearnedNum: Int? = Int(languagesLearned)
print("\(languagesLearnedNum.dynamicType)")
var isDone = false
var statement: string = isDone ? ""Job done and we are ready" : "Time running out"
|
fada97eb402639d1bb1eeaba16fa8e42
| 18.650943 | 92 | 0.704753 | false | false | false | false |
HTWDD/htwcampus
|
refs/heads/develop
|
HTWDD/Main Categories/General/Models/Semester.swift
|
mit
|
1
|
//
// Semester.swift
// HTWDD
//
// Created by Benjamin Herzog on 05/01/2017.
// Copyright © 2017 HTW Dresden. All rights reserved.
//
import Foundation
import Marshal
enum Semester: Hashable, CustomStringConvertible, Comparable {
case summer(year: Int)
case winter(year: Int)
var year: Int {
switch self {
case .summer(let year):
return year
case .winter(let year):
return year
}
}
var localized: String {
switch self {
case .summer(let year):
return Loca.summerSemester + " \(year)"
case .winter(let year):
return Loca.winterSemester + " \(year)"
}
}
var description: String {
switch self {
case .summer(let year):
return "SS_\(year)"
case .winter(let year):
return "WS_\(year)"
}
}
var hashValue: Int {
return description.hashValue
}
static func <(lhs: Semester, rhs: Semester) -> Bool {
switch (lhs, rhs) {
case (.summer(let year1), .summer(let year2)):
return year1 < year2
case (.winter(let year1), .winter(let year2)):
return year1 < year2
case (.summer(let year1), .winter(let year2)):
if year1 == year2 {
return true
} else {
return year1 < year2
}
case (.winter(let year1), .summer(let year2)):
if year1 == year2 {
return false
} else {
return year1 < year2
}
}
}
static func ==(lhs: Semester, rhs: Semester) -> Bool {
switch (lhs, rhs) {
case (.summer(let year1), .summer(let year2)):
return year1 == year2
case (.winter(let year1), .winter(let year2)):
return year1 == year2
default:
return false
}
}
}
extension Semester: ValueType {
static func value(from object: Any) throws -> Semester {
guard let number = object as? Int else {
throw MarshalError.typeMismatch(expected: Int.self, actual: type(of: object))
}
let rawValue = "\(number)"
guard rawValue.count == 5 else {
throw MarshalError.typeMismatch(expected: 5, actual: rawValue.count)
}
var raw = rawValue
let rawType = raw.removeLast()
guard let year = Int(raw) else {
throw MarshalError.typeMismatch(expected: Int.self, actual: raw)
}
if rawType == "1" {
return .summer(year: year)
} else if rawType == "2" {
return .winter(year: year)
} else {
throw MarshalError.typeMismatch(expected: "1 or 2", actual: rawType)
}
}
}
extension Semester: Codable {
func encode(to encoder: Encoder) throws {
let semesterNumber: Int
switch self {
case .summer(_): semesterNumber = 1
case .winter(_): semesterNumber = 2
}
var container = encoder.singleValueContainer()
try container.encode(self.year*10 + semesterNumber)
}
init(from decoder: Decoder) throws {
let number = try decoder.singleValueContainer().decode(Int.self)
self = try Semester.value(from: number)
}
}
|
db48635b70948be0e5f1637f7c202355
| 25.140625 | 89 | 0.537956 | false | false | false | false |
v2panda/DaysofSwift
|
refs/heads/master
|
swift2.3/My-CollectionViewAnimation/My-CollectionViewAnimation/AnimationCollectionViewCell.swift
|
mit
|
1
|
//
// AnimationCollectionViewCell.swift
// My-CollectionViewAnimation
//
// Created by Panda on 16/3/7.
// Copyright © 2016年 v2panda. All rights reserved.
//
import UIKit
class AnimationCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var button: UIButton!
var backButtonTapped: (() -> Void)?
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func prepareCell(viewModel:AnimationCellModel) {
imageView.image = UIImage(named: viewModel.imagePath)
textView.scrollEnabled = false
button.hidden = true
button.addTarget(self, action: Selector("backButtonDidTouch"), forControlEvents: .TouchUpInside)
}
func backButtonDidTouch() {
backButtonTapped?()
}
func handleCellSelected() {
textView.scrollEnabled = false
button.hidden = false
self.superview?.bringSubviewToFront(self)
}
}
|
53cc3f456116cba3a0794c916644c41e
| 25.425 | 104 | 0.666036 | false | false | false | false |
jad6/CV
|
refs/heads/master
|
Swift/Jad's CV/Models/ExperienceObject.swift
|
bsd-3-clause
|
1
|
//
// ExperienceObject.swift
// Jad's CV
//
// Created by Jad Osseiran on 17/07/2014.
// Copyright (c) 2014 Jad. All rights reserved.
//
import UIKit
class ExperienceObject: ExtractedObject {
let startDate: NSDate
let endDate: NSDate
let organisationImage: UIImage?
let organisation: String
let position: String
let detailedDescription: String
class func sortedExperiences() -> [ExperienceObject] {
var error = NSError?()
var objects = self.extractObjects(&error)
error?.handle()
if var experiences = objects as? [ExperienceObject] {
experiences.sort() {
return ($0.startDate.compare($1.startDate) != .OrderedAscending) &&
($0.endDate.compare($1.endDate) != .OrderedAscending)
}
return experiences
} else {
return [ExperienceObject]()
}
}
required init(dictionary: NSDictionary) {
self.startDate = dictionary["startDate"] as NSDate
self.endDate = dictionary["endDate"] as NSDate
self.organisation = dictionary["organisation"] as String
self.position = dictionary["position"] as String
self.detailedDescription = dictionary["description"] as String
if let imageName = dictionary["imageName"] as? String {
self.organisationImage = UIImage(named: imageName)
}
super.init(dictionary: dictionary)
}
func timeSpentString(separator: String) -> String {
return startDate.combinedCondensedStringWithEndDate(endDate, withSeparator: separator)
}
}
class ExtraCurricularActivity: ExperienceObject {
class func extraCurricularActivitiesListData() -> ListData<ExtraCurricularActivity> {
var extraCurricularActivitiesListData = ListData<ExtraCurricularActivity>()
extraCurricularActivitiesListData.sections += [ListSection(rowObjects: ExtraCurricularActivity.extraCurricularActivities(), name: "Extra Curricular")]
return extraCurricularActivitiesListData
}
class func extraCurricularActivities() -> [ExtraCurricularActivity] {
return self.sortedExperiences() as [ExtraCurricularActivity]
}
override class func filePathForResource() -> String? {
return NSBundle.mainBundle().pathForResource("Extra Curricular", ofType: "plist")
}
required init(dictionary: NSDictionary) {
super.init(dictionary: dictionary)
}
}
class TimelineEvent: ExperienceObject {
enum Importance: Int, IntegerLiteralConvertible {
case None = 0, Major, Minor
static func convertFromIntegerLiteral(value: IntegerLiteralType) -> Importance {
if value == 1 {
return .Major
} else if value == 2 {
return .Minor
} else {
return .None
}
}
}
let color: UIColor
let importance: Importance
class func timelineEventsListData() -> ListData<TimelineEvent> {
var timelineEventsListData = ListData<TimelineEvent>()
timelineEventsListData.sections += [ListSection(rowObjects: TimelineEvent.timelineEvents(), name: "Timeline")]
return timelineEventsListData
}
class func timelineEvents() -> [TimelineEvent] {
return self.sortedExperiences() as [TimelineEvent]
}
override class func filePathForResource() -> String? {
return NSBundle.mainBundle().pathForResource("Experience", ofType: "plist")
}
required init(dictionary: NSDictionary) {
self.color = UIColor.colorFromRGBString(dictionary["color"] as String)
let importance = dictionary["importance"] as Int
self.importance = Importance.convertFromIntegerLiteral(importance)
super.init(dictionary: dictionary)
}
}
|
42345b373d4d071040f882a4107387c4
| 31.677686 | 158 | 0.64002 | false | false | false | false |
RocketChat/Rocket.Chat.iOS
|
refs/heads/develop
|
Rocket.Chat/Views/Chat/New Chat/Cells/ThreadReplyCollapsedCell.swift
|
mit
|
1
|
//
// ThreadReplyCollapsedCell.swift
// Rocket.Chat
//
// Created by Rafael Kellermann Streit on 17/04/19.
// Copyright © 2019 Rocket.Chat. All rights reserved.
//
import UIKit
import RocketChatViewController
final class ThreadReplyCollapsedCell: BaseMessageCell, SizingCell {
static let identifier = String(describing: ThreadReplyCollapsedCell.self)
static let sizingCell: UICollectionViewCell & ChatCell = {
guard let cell = ThreadReplyCollapsedCell.instantiateFromNib() else {
return ThreadReplyCollapsedCell()
}
return cell
}()
@IBOutlet weak var iconThread: UIImageView!
@IBOutlet weak var avatarContainerView: UIView! {
didSet {
avatarContainerView.layer.cornerRadius = 4
avatarView.frame = avatarContainerView.bounds
avatarContainerView.addSubview(avatarView)
}
}
@IBOutlet weak var labelThreadTitle: UILabel!
@IBOutlet weak var labelThreadReply: UILabel!
@IBOutlet weak var avatarWidthConstraint: NSLayoutConstraint!
@IBOutlet weak var avatarLeadingConstraint: NSLayoutConstraint!
@IBOutlet weak var labelTextTopConstraint: NSLayoutConstraint!
override func awakeFromNib() {
super.awakeFromNib()
let gesture = UITapGestureRecognizer(target: self, action: #selector(didTapContainerView))
gesture.delegate = self
contentView.addGestureRecognizer(gesture)
}
override func configure(completeRendering: Bool) {
configure(
with: avatarView,
date: nil,
status: nil,
and: nil,
completeRendering: completeRendering
)
guard
let model = viewModel?.base as? MessageReplyThreadChatItem
else {
return
}
let threadName = model.threadName
// If thread name is empty, it means we don't have the
// main message cell yet or it's not a valid title, so we
// can hide the entire header.
if model.isSequential || threadName == nil {
iconThread.isHidden = true
labelThreadTitle.text = nil
labelTextTopConstraint.constant = 0
} else {
iconThread.isHidden = false
labelThreadTitle.text = threadName
labelTextTopConstraint.constant = 4
}
updateText()
}
func updateText() {
guard
let viewModel = viewModel?.base as? MessageReplyThreadChatItem,
let message = viewModel.message
else {
return
}
labelThreadReply.text = message.threadReplyCompressedMessage
}
@objc func didTapContainerView() {
guard
let viewModel = viewModel,
let model = viewModel.base as? MessageReplyThreadChatItem,
let threadIdentifier = model.message?.threadMessageId
else {
return
}
delegate?.openThread(identifier: threadIdentifier)
}
}
extension ThreadReplyCollapsedCell {
override func applyTheme() {
super.applyTheme()
let theme = self.theme ?? .light
labelThreadTitle.textColor = theme.actionTintColor
updateText()
}
}
|
b4ccc791788bc1d5049fbe4b2881556e
| 27.226087 | 98 | 0.638016 | false | false | false | false |
AlDrago/SwiftyJSON
|
refs/heads/master
|
Tests/PrintableTests.swift
|
mit
|
1
|
// PrintableTests.swift
//
// Copyright (c) 2014 Pinglin Tang
//
// 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 XCTest
import SwiftyJSON3
class PrintableTests: XCTestCase {
func testNumber() {
let json:JSON = 1234567890.876623
XCTAssertEqual(json.description, "1234567890.876623")
XCTAssertEqual(json.debugDescription, "1234567890.876623")
}
func testBool() {
let jsonTrue:JSON = true
XCTAssertEqual(jsonTrue.description, "true")
XCTAssertEqual(jsonTrue.debugDescription, "true")
let jsonFalse:JSON = false
XCTAssertEqual(jsonFalse.description, "false")
XCTAssertEqual(jsonFalse.debugDescription, "false")
}
func testString() {
let json:JSON = "abcd efg, HIJK;LMn"
XCTAssertEqual(json.description, "abcd efg, HIJK;LMn")
XCTAssertEqual(json.debugDescription, "abcd efg, HIJK;LMn")
}
func testNil() {
let jsonNil_1:JSON = nil
XCTAssertEqual(jsonNil_1.description, "null")
XCTAssertEqual(jsonNil_1.debugDescription, "null")
let jsonNil_2:JSON = JSON(NSNull())
XCTAssertEqual(jsonNil_2.description, "null")
XCTAssertEqual(jsonNil_2.debugDescription, "null")
}
func testArray() {
let json:JSON = [1,2,"4",5,"6"]
var description = json.description.replacingOccurrences(of: "\n", with: "")
description = description.replacingOccurrences(of: " ", with: "")
XCTAssertEqual(description, "[1,2,\"4\",5,\"6\"]")
XCTAssertTrue(json.description.lengthOfBytes(using: String.Encoding.utf8) > 0)
XCTAssertTrue(json.debugDescription.lengthOfBytes(using: String.Encoding.utf8) > 0)
}
func testDictionary() {
let json:JSON = ["1":2,"2":"two", "3":3]
var debugDescription = json.debugDescription.replacingOccurrences(of: "\n", with: "")
debugDescription = debugDescription.replacingOccurrences(of: " ", with: "")
XCTAssertTrue(json.description.lengthOfBytes(using: String.Encoding.utf8) > 0)
XCTAssertTrue(debugDescription.range(of: "\"1\":2", options: NSString.CompareOptions.caseInsensitive) != nil)
XCTAssertTrue(debugDescription.range(of: "\"2\":\"two\"", options: NSString.CompareOptions.caseInsensitive) != nil)
XCTAssertTrue(debugDescription.range(of: "\"3\":3", options: NSString.CompareOptions.caseInsensitive) != nil)
}
}
|
e48054a0f331c749973e238a617837a1
| 45.44 | 123 | 0.689348 | false | true | false | false |
davidbutz/ChristmasFamDuels
|
refs/heads/master
|
iOS/Boat Aware/LoadingView.swift
|
mit
|
1
|
//
// LoadingView.swift
// ThriveIOSPrototype
//
// Created by Dave Butz on 1/11/16.
// Copyright © 2016 Dave Butz. All rights reserved.
//
import Foundation
import UIKit
public class LoadingOverlay{
var overlayView = UIView()
var activityIndicator = UIActivityIndicatorView()
var captionLabel = UILabel()
class var shared: LoadingOverlay {
struct Static {
static let instance: LoadingOverlay = LoadingOverlay()
}
return Static.instance
}
func setCaption(caption: String) {
captionLabel.text = caption
}
public func showOverlay(view: UIView) {
overlayView.frame = CGRectMake(0, 0, 300, 300)
overlayView.center = view.center
overlayView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.8)
overlayView.clipsToBounds = true
overlayView.layer.cornerRadius = 10
activityIndicator.frame = CGRectMake(0, 0, 40, 40)
activityIndicator.activityIndicatorViewStyle = .WhiteLarge
activityIndicator.center = CGPointMake(overlayView.bounds.width / 2, overlayView.bounds.height / 2)
captionLabel.frame = CGRectMake(10, 200, 290, 40);
// captionLabel.backgroundColor = UIColor.blackColor()
captionLabel.textColor = UIColor.whiteColor()
captionLabel.adjustsFontSizeToFitWidth = true
captionLabel.textAlignment = NSTextAlignment.Center
//captionLabel!.text = "Loading..."
overlayView.addSubview(captionLabel);
overlayView.addSubview(activityIndicator);
view.addSubview(overlayView)
activityIndicator.startAnimating()
}
public func hideOverlayView() {
activityIndicator.stopAnimating()
captionLabel.removeFromSuperview();
activityIndicator.removeFromSuperview();
overlayView.removeFromSuperview()
}
}
class LoadingView : UIView {
var captionLabel : UILabel?
func setCaption(caption: String) {
captionLabel!.text = caption
}
func done() {
self.removeFromSuperview()
}
override init(frame aRect: CGRect) {
super.init(frame: aRect)
let hudView = UIView(frame: CGRectMake(aRect.width/2.0 - (170/2.0), aRect.height/2.0 - (170/2.0), 170, 170))
hudView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5)
hudView.clipsToBounds = true
hudView.layer.cornerRadius = 10.0
let activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
activityIndicatorView.frame = CGRectMake(65, 40, activityIndicatorView.bounds.size.width, activityIndicatorView.bounds.size.width)
hudView.addSubview(activityIndicatorView)
activityIndicatorView.startAnimating()
captionLabel = UILabel(frame: CGRectMake(20, 115, 130, 22))
// captionLabel.backgroundColor = UIColor.blackColor()
captionLabel!.textColor = UIColor.whiteColor()
captionLabel!.adjustsFontSizeToFitWidth = true
captionLabel!.textAlignment = NSTextAlignment.Center
//captionLabel!.text = "Loading..."
hudView.addSubview(captionLabel!)
self.addSubview(hudView)
}
// convenience override init() {
// self.init(frame:CGRectZero)
// }
required init(coder aDecoder: NSCoder) {
fatalError("This class does not support NSCoding")
}
}
|
e8ccfc6606fee3c5286747371bf43165
| 32.761905 | 138 | 0.653315 | false | false | false | false |
gontovnik/DGElasticBounceTutorial
|
refs/heads/master
|
DGElasticBounceTutorial/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// DGElasticBounceTutorial
//
// Created by Danil Gontovnik on 10/13/15.
// Copyright © 2015 Danil Gontovnik. All rights reserved.
//
import UIKit
// MARK: -
// MARK: (UIView) Extension
extension UIView {
func dg_center(usePresentationLayerIfPossible: Bool) -> CGPoint {
if usePresentationLayerIfPossible, let presentationLayer = layer.presentationLayer() as? CALayer {
return presentationLayer.position
}
return center
}
}
// MARK: -
// MARK: ViewController
class ViewController: UIViewController {
// MARK: -
// MARK: Vars
private let minimalHeight: CGFloat = 50.0
private let maxWaveHeight: CGFloat = 100.0
private let shapeLayer = CAShapeLayer()
private var displayLink: CADisplayLink!
private var animating = false {
didSet {
view.userInteractionEnabled = !animating
displayLink.paused = !animating
}
}
private let l3ControlPointView = UIView()
private let l2ControlPointView = UIView()
private let l1ControlPointView = UIView()
private let cControlPointView = UIView()
private let r1ControlPointView = UIView()
private let r2ControlPointView = UIView()
private let r3ControlPointView = UIView()
// MARK: -
override func loadView() {
super.loadView()
shapeLayer.frame = CGRect(x: 0.0, y: 0.0, width: view.bounds.width, height: minimalHeight)
shapeLayer.fillColor = UIColor(red: 57/255.0, green: 67/255.0, blue: 89/255.0, alpha: 1.0).CGColor
shapeLayer.actions = ["position" : NSNull(), "bounds" : NSNull(), "path" : NSNull()]
view.layer.addSublayer(shapeLayer)
view.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: "panGestureDidMove:"))
view.addSubview(l3ControlPointView)
view.addSubview(l2ControlPointView)
view.addSubview(l1ControlPointView)
view.addSubview(cControlPointView)
view.addSubview(r1ControlPointView)
view.addSubview(r2ControlPointView)
view.addSubview(r3ControlPointView)
layoutControlPoints(baseHeight: minimalHeight, waveHeight: 0.0, locationX: view.bounds.width / 2.0)
updateShapeLayer()
displayLink = CADisplayLink(target: self, selector: Selector("updateShapeLayer"))
displayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode)
displayLink.paused = true
}
// MARK: -
// MARK: Methods
func panGestureDidMove(gesture: UIPanGestureRecognizer) {
if gesture.state == .Ended || gesture.state == .Failed || gesture.state == .Cancelled {
let centerY = minimalHeight
animating = true
UIView.animateWithDuration(0.9, delay: 0.0, usingSpringWithDamping: 0.57, initialSpringVelocity: 0.0, options: [], animations: { () -> Void in
self.l3ControlPointView.center.y = centerY
self.l2ControlPointView.center.y = centerY
self.l1ControlPointView.center.y = centerY
self.cControlPointView.center.y = centerY
self.r1ControlPointView.center.y = centerY
self.r2ControlPointView.center.y = centerY
self.r3ControlPointView.center.y = centerY
}, completion: { _ in
self.animating = false
})
} else {
let additionalHeight = max(gesture.translationInView(view).y, 0)
let waveHeight = min(additionalHeight * 0.6, maxWaveHeight)
let baseHeight = minimalHeight + additionalHeight - waveHeight
let locationX = gesture.locationInView(gesture.view).x
layoutControlPoints(baseHeight: baseHeight, waveHeight: waveHeight, locationX: locationX)
updateShapeLayer()
}
}
private func layoutControlPoints(baseHeight baseHeight: CGFloat, waveHeight: CGFloat, locationX: CGFloat) {
let width = view.bounds.width
let minLeftX = min((locationX - width / 2.0) * 0.28, 0.0)
let maxRightX = max(width + (locationX - width / 2.0) * 0.28, width)
let leftPartWidth = locationX - minLeftX
let rightPartWidth = maxRightX - locationX
l3ControlPointView.center = CGPoint(x: minLeftX, y: baseHeight)
l2ControlPointView.center = CGPoint(x: minLeftX + leftPartWidth * 0.44, y: baseHeight)
l1ControlPointView.center = CGPoint(x: minLeftX + leftPartWidth * 0.71, y: baseHeight + waveHeight * 0.64)
cControlPointView.center = CGPoint(x: locationX , y: baseHeight + waveHeight * 1.36)
r1ControlPointView.center = CGPoint(x: maxRightX - rightPartWidth * 0.71, y: baseHeight + waveHeight * 0.64)
r2ControlPointView.center = CGPoint(x: maxRightX - (rightPartWidth * 0.44), y: baseHeight)
r3ControlPointView.center = CGPoint(x: maxRightX, y: baseHeight)
}
func updateShapeLayer() {
shapeLayer.path = currentPath()
}
private func currentPath() -> CGPath {
let width = view.bounds.width
let bezierPath = UIBezierPath()
bezierPath.moveToPoint(CGPoint(x: 0.0, y: 0.0))
bezierPath.addLineToPoint(CGPoint(x: 0.0, y: l3ControlPointView.dg_center(animating).y))
bezierPath.addCurveToPoint(l1ControlPointView.dg_center(animating), controlPoint1: l3ControlPointView.dg_center(animating), controlPoint2: l2ControlPointView.dg_center(animating))
bezierPath.addCurveToPoint(r1ControlPointView.dg_center(animating), controlPoint1: cControlPointView.dg_center(animating), controlPoint2: r1ControlPointView.dg_center(animating))
bezierPath.addCurveToPoint(r3ControlPointView.dg_center(animating), controlPoint1: r1ControlPointView.dg_center(animating), controlPoint2: r2ControlPointView.dg_center(animating))
bezierPath.addLineToPoint(CGPoint(x: width, y: 0.0))
bezierPath.closePath()
return bezierPath.CGPath
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .LightContent
}
}
|
4138711be15ef7c36b724b207cbf9d11
| 39.335484 | 187 | 0.654511 | false | false | false | false |
SwiftFS/Swift-FS-China
|
refs/heads/master
|
Sources/SwiftFSChina/server/CollectServer.swift
|
mit
|
1
|
//
// CollectServer.swift
// PerfectChina
//
// Created by mubin on 2017/7/28.
//
//
import PerfectLib
import MySQL
struct CollectServer {
public static func cancel_collect(user_id:Int,topic_id:Int) throws -> Bool {
return try pool.execute{
try $0.query("delete from collect where user_id=? and topic_id=?",[user_id,topic_id])
}.affectedRows > 0
}
public static func collect(user_id:Int,topic_id:Int) throws -> Bool {
return try pool.execute{
try $0.query("insert into collect (user_id,topic_id) values(?,?) ON DUPLICATE KEY UPDATE create_time=CURRENT_TIMESTAMP ",[user_id,topic_id])
}.insertedID > 0
}
public static func get_all_of_user(user_id:Int,page_no:Int,page_size:Int) throws -> [CollectEntity] {
return try pool.execute{
try $0.query("select t.*, u.avatar as avatar, cc.name as category_name from collect c " +
" right join topic t on c.topic_id=t.id " +
" left join user u on t.user_id=u.id " +
" left join category cc on t.category_id=cc.id " +
" where c.user_id=? order by c.id desc limit ?,? "
,[user_id,(page_no - 1) * page_size,page_size])
}
}
public static func is_collect(current_userid:Int,topic_id:String) throws -> Bool {
let row:[Count] = try pool.execute{
try $0.query("select count(c.id) as count from collect c " +
" where c.user_id=? and c.topic_id=?",[current_userid,topic_id])
}
return !(row.count > 0 && row[0].count < 1)
}
}
|
50df2a5467e0ea708b8aef36c5690416
| 31.509804 | 152 | 0.568758 | false | false | false | false |
CanyFrog/HCComponent
|
refs/heads/master
|
HCSource/HCBaseRefreshView.swift
|
mit
|
1
|
//
// HCBaseRefreshView.swift
// HCComponents
//
// Created by Magee Huang on 6/13/17.
// Copyright © 2017 Person Inc. All rights reserved.
//
/// base on https://github.com/CoderMJLee/MJRefresh
import UIKit
public enum HCRefreshState {
case normal, draging, trigger, refreshing, empty
}
fileprivate let HCRefreshContentOffsetKey = "HCRefreshContentOffsetKey"
fileprivate let HCRefreshContentSizeKey = "HCRefreshContentSizeKey"
fileprivate let HCRefreshPanStateKey = "HCRefreshPanStateKey"
public class HCBaseRefreshView: UIView {
/// super scrollview infomation
public weak var scrollView: UIScrollView!
public var originInset: UIEdgeInsets!
/// state information
public var state: HCRefreshState = .normal {
didSet {
if state != oldValue {
changeState(oldState: oldValue, to: state)
}
}
}
public var isRefreshing: Bool {
return state == .refreshing || state == .trigger
}
public var isAutoChangeAlpha: Bool = false {
didSet {
guard !isRefreshing else { return }
alpha = isAutoChangeAlpha ? dragingRatio : 1.0
}
}
public var dragingRatio: CGFloat = 0.0 {
didSet {
guard !isRefreshing else { return }
if isAutoChangeAlpha {
alpha = dragingRatio
}
}
}
public var aniDuration: TimeInterval = 0.3
/// callback
internal var refreshHandler: EmptyExecute?
internal var beiginRefreshHandler: EmptyExecute?
internal var stopRefreshHandler: EmptyExecute?
internal var panGesture: UIPanGestureRecognizer {
return scrollView.panGestureRecognizer
}
public convenience init(refresh: @escaping EmptyExecute) {
self.init(frame: .zero)
refreshHandler = refresh
}
public override func draw(_ rect: CGRect) {
super.draw(rect)
if state == .trigger {
state = .refreshing // handler view not didapper when beigin refreshing
}
}
public override func willMove(toSuperview newSuperview: UIView?) {
super.willMove(toSuperview: newSuperview)
guard let newS = newSuperview else {
removeScrollViewObserver()
return
}
if let s = (newS as? UIScrollView) {
removeScrollViewObserver()
left = 0
width = s.width
s.alwaysBounceVertical = true
originInset = s.contentInset // recording origin contentInset
addScrollViewObserver()
}
}
public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if !isUserInteractionEnabled { return }
if keyPath == HCRefreshContentSizeKey { // Must be change size even througn isHidden
scrollViewDidChanged(size: change)
}
if isHidden { return }
if keyPath == HCRefreshContentOffsetKey {
scrollViewDidChanged(offset: change)
}
else if keyPath == HCRefreshPanStateKey {
scrollViewDidCahnged(panState: change)
}
}
fileprivate func removeScrollViewObserver() {
let options: NSKeyValueObservingOptions = [.new, .old]
scrollView.addObserver(self, forKeyPath: HCRefreshContentOffsetKey, options: options, context: nil)
scrollView.addObserver(self, forKeyPath: HCRefreshContentSizeKey, options: options, context: nil)
panGesture.addObserver(self, forKeyPath: HCRefreshPanStateKey, options: options, context: nil)
}
fileprivate func addScrollViewObserver() {
scrollView.removeObserver(self, forKeyPath: HCRefreshContentOffsetKey)
scrollView.removeObserver(self, forKeyPath: HCRefreshContentSizeKey)
scrollView.removeObserver(self, forKeyPath: HCRefreshPanStateKey)
}
public func scrollViewDidChanged(size: [NSKeyValueChangeKey : Any]?) {
}
public func scrollViewDidChanged(offset: [NSKeyValueChangeKey : Any]?) {
}
public func scrollViewDidCahnged(panState: [NSKeyValueChangeKey : Any]?) {
}
public func changeState(oldState: HCRefreshState ,to newState: HCRefreshState) {
DispatchQueue.main.async {
self.setNeedsLayout()
}
}
public func beginRefreshing(_ completion: EmptyExecute? = nil) {
beiginRefreshHandler = completion
UIView.animate(withDuration: aniDuration) {
self.alpha = 1.0
}
dragingRatio = 1.0
if let _ = window {
state = .refreshing
}
else {
// 预防正在刷新中时,调用本方法使得header inset回置失败
if state != .refreshing {
state = .trigger
setNeedsDisplay() // 预防从另一个控制器回到这个控制器的情况,回来要重新刷新一下
}
}
}
public func stopRefreshing(_ completion: EmptyExecute? = nil) {
stopRefreshHandler = completion
DispatchQueue.main.async {
self.state = .normal
}
}
public func execRefreshing() {
DispatchQueue.main.async {
self.refreshHandler?()
}
}
}
|
a7f38ee7ce44c15721e5b567f0b23dcd
| 30.511905 | 158 | 0.625614 | false | false | false | false |
slavapestov/swift
|
refs/heads/master
|
test/SILGen/address_only_types.swift
|
apache-2.0
|
1
|
// RUN: %target-swift-frontend -parse-as-library -parse-stdlib -emit-silgen %s | FileCheck %s
typealias Int = Builtin.Int64
enum Bool { case true_, false_ }
protocol Unloadable {
func foo() -> Int
var address_only_prop : Unloadable { get }
var loadable_prop : Int { get }
}
// CHECK-LABEL: sil hidden @_TF18address_only_types21address_only_argument
func address_only_argument(let x: Unloadable) {
// CHECK: bb0([[XARG:%[0-9]+]] : $*Unloadable):
// CHECK: debug_value_addr [[XARG]]
// CHECK-NEXT: destroy_addr [[XARG]]
// CHECK-NEXT: tuple
// CHECK-NEXT: return
}
// CHECK-LABEL: sil hidden @_TF18address_only_types29address_only_ignored_argument
func address_only_ignored_argument(_: Unloadable) {
// CHECK: bb0([[XARG:%[0-9]+]] : $*Unloadable):
// CHECK: destroy_addr [[XARG]]
// CHECK-NOT: dealloc_stack {{.*}} [[XARG]]
// CHECK: return
}
// CHECK-LABEL: sil hidden @_TF18address_only_types19address_only_return
func address_only_return(let x: Unloadable, let y: Int) -> Unloadable {
// CHECK: bb0([[RET:%[0-9]+]] : $*Unloadable, [[XARG:%[0-9]+]] : $*Unloadable, [[YARG:%[0-9]+]] : $Builtin.Int64):
// CHECK-NEXT: debug_value_addr [[XARG]] : $*Unloadable, let, name "x"
// CHECK-NEXT: debug_value [[YARG]] : $Builtin.Int64, let, name "y"
// CHECK-NEXT: copy_addr [take] [[XARG]] to [initialization] [[RET]]
// CHECK-NEXT: [[VOID:%[0-9]+]] = tuple ()
// CHECK-NEXT: return [[VOID]]
return x
}
// CHECK-LABEL: sil hidden @_TF18address_only_types27address_only_missing_return
func address_only_missing_return() -> Unloadable {
// CHECK: unreachable
}
// CHECK-LABEL: sil hidden @_TF18address_only_types39address_only_conditional_missing_return
func address_only_conditional_missing_return(let x: Unloadable) -> Unloadable {
// CHECK: bb0({{%.*}} : $*Unloadable, {{%.*}} : $*Unloadable):
// CHECK: switch_enum {{%.*}}, case #Bool.true_!enumelt: [[TRUE:bb[0-9]+]], case #Bool.false_!enumelt: [[FALSE:bb[0-9]+]]
switch Bool.true_ {
case .true_:
// CHECK: [[TRUE]]:
// CHECK: copy_addr [take] %1 to [initialization] %0 : $*Unloadable
// CHECK: return
return x
case .false_:
()
}
// CHECK: [[FALSE]]:
// CHECK: unreachable
}
// CHECK-LABEL: sil hidden @_TF18address_only_types41address_only_conditional_missing_return
func address_only_conditional_missing_return_2(x: Unloadable) -> Unloadable {
// CHECK: bb0({{%.*}} : $*Unloadable, {{%.*}} : $*Unloadable):
// CHECK: switch_enum {{%.*}}, case #Bool.true_!enumelt: [[TRUE1:bb[0-9]+]], case #Bool.false_!enumelt: [[FALSE1:bb[0-9]+]]
switch Bool.true_ {
case .true_:
return x
case .false_:
()
}
// CHECK: [[FALSE1]]:
// CHECK: switch_enum {{%.*}}, case #Bool.true_!enumelt: [[TRUE2:bb[0-9]+]], case #Bool.false_!enumelt: [[FALSE2:bb[0-9]+]]
switch Bool.true_ {
case .true_:
return x
case .false_:
()
}
// CHECK: [[FALSE2]]:
// CHECK: unreachable
// CHECK: bb{{.*}}:
// CHECK: return
}
var crap : Unloadable = some_address_only_function_1()
func some_address_only_function_1() -> Unloadable { return crap }
func some_address_only_function_2(x: Unloadable) -> () {}
// CHECK-LABEL: sil hidden @_TF18address_only_types19address_only_call
func address_only_call_1() -> Unloadable {
// CHECK: bb0([[RET:%[0-9]+]] : $*Unloadable):
return some_address_only_function_1()
// FIXME emit into
// CHECK: [[FUNC:%[0-9]+]] = function_ref @_TF18address_only_types28some_address_only_function_1FT_PS_10Unloadable_
// CHECK: apply [[FUNC]]([[RET]])
// CHECK: return
}
// CHECK-LABEL: sil hidden @_TF18address_only_types33address_only_call_1_ignore_returnFT_T_
func address_only_call_1_ignore_return() {
// CHECK: bb0:
some_address_only_function_1()
// CHECK: [[FUNC:%[0-9]+]] = function_ref @_TF18address_only_types28some_address_only_function_1FT_PS_10Unloadable_
// CHECK: [[TEMP:%[0-9]+]] = alloc_stack $Unloadable
// CHECK: apply [[FUNC]]([[TEMP]])
// CHECK: destroy_addr [[TEMP]]
// CHECK: dealloc_stack [[TEMP]]
// CHECK: return
}
// CHECK-LABEL: sil hidden @_TF18address_only_types19address_only_call_2
func address_only_call_2(let x: Unloadable) {
// CHECK: bb0([[XARG:%[0-9]+]] : $*Unloadable):
// CHECK: debug_value_addr [[XARG]] : $*Unloadable
some_address_only_function_2(x)
// CHECK: [[FUNC:%[0-9]+]] = function_ref @_TF18address_only_types28some_address_only_function_2
// CHECK: [[X_CALL_ARG:%[0-9]+]] = alloc_stack $Unloadable
// CHECK: copy_addr [[XARG]] to [initialization] [[X_CALL_ARG]]
// CHECK: apply [[FUNC]]([[X_CALL_ARG]])
// CHECK: dealloc_stack [[X_CALL_ARG]]
// CHECK: return
}
// CHECK-LABEL: sil hidden @_TF18address_only_types24address_only_call_1_in_2
func address_only_call_1_in_2() {
// CHECK: bb0:
some_address_only_function_2(some_address_only_function_1())
// CHECK: [[FUNC2:%[0-9]+]] = function_ref @_TF18address_only_types28some_address_only_function_2
// CHECK: [[FUNC1:%[0-9]+]] = function_ref @_TF18address_only_types28some_address_only_function_1
// CHECK: [[TEMP:%[0-9]+]] = alloc_stack $Unloadable
// CHECK: apply [[FUNC1]]([[TEMP]])
// CHECK: apply [[FUNC2]]([[TEMP]])
// CHECK: dealloc_stack [[TEMP]]
// CHECK: return
}
// CHECK-LABEL: sil hidden @_TF18address_only_types24address_only_materialize
func address_only_materialize() -> Int {
// CHECK: bb0:
return some_address_only_function_1().foo()
// CHECK: [[FUNC:%[0-9]+]] = function_ref @_TF18address_only_types28some_address_only_function_1
// CHECK: [[TEMP:%[0-9]+]] = alloc_stack $Unloadable
// CHECK: apply [[FUNC]]([[TEMP]])
// CHECK: [[TEMP_PROJ:%[0-9]+]] = open_existential_addr [[TEMP]] : $*Unloadable to $*[[OPENED:@opened(.*) Unloadable]]
// CHECK: [[FOO_METHOD:%[0-9]+]] = witness_method $[[OPENED]], #Unloadable.foo!1
// CHECK: [[RET:%[0-9]+]] = apply [[FOO_METHOD]]<[[OPENED]]>([[TEMP_PROJ]])
// CHECK: destroy_addr [[TEMP_PROJ]]
// CHECK: dealloc_stack [[TEMP]]
// CHECK: return [[RET]]
}
// CHECK-LABEL: sil hidden @_TF18address_only_types33address_only_assignment_from_temp
func address_only_assignment_from_temp(inout dest: Unloadable) {
// CHECK: bb0([[DEST:%[0-9]+]] : $*Unloadable):
// CHECK: [[DEST_LOCAL:%.*]] = alloc_box $Unloadable
// CHECK: [[PB:%.*]] = project_box [[DEST_LOCAL]]
// CHECK: copy_addr [[DEST]] to [initialization] [[PB]]
dest = some_address_only_function_1()
// CHECK: [[TEMP:%[0-9]+]] = alloc_stack $Unloadable
// CHECK: copy_addr [take] [[TEMP]] to [[PB]] :
// CHECK-NOT: destroy_addr [[TEMP]]
// CHECK: dealloc_stack [[TEMP]]
// CHECK: copy_addr [[PB]] to [[DEST]]
// CHECK: release [[DEST_LOCAL]]
}
// CHECK-LABEL: sil hidden @_TF18address_only_types31address_only_assignment_from_lv
func address_only_assignment_from_lv(inout dest: Unloadable, v: Unloadable) {
var v = v
// CHECK: bb0([[DEST:%[0-9]+]] : $*Unloadable, [[VARG:%[0-9]+]] : $*Unloadable):
// CHECK: [[DEST_LOCAL:%.*]] = alloc_box $Unloadable
// CHECK: [[PB:%.*]] = project_box [[DEST_LOCAL]]
// CHECK: copy_addr [[DEST]] to [initialization] [[PB]]
// CHECK: [[VBOX:%.*]] = alloc_box $Unloadable
// CHECK: [[PBOX:%[0-9]+]] = project_box [[VBOX]]
// CHECK: copy_addr [[VARG]] to [initialization] [[PBOX]] : $*Unloadable
dest = v
// FIXME: emit into?
// CHECK: copy_addr [[PBOX]] to [[PB]] :
// CHECK: release [[VBOX]]
// CHECK: copy_addr [[PB]] to [[DEST]]
// CHECK: release [[DEST_LOCAL]]
}
var global_prop : Unloadable {
get {
return crap
}
set {}
}
// CHECK-LABEL: sil hidden @_TF18address_only_types45address_only_assignment_from_temp_to_property
func address_only_assignment_from_temp_to_property() {
// CHECK: bb0:
global_prop = some_address_only_function_1()
// CHECK: [[TEMP:%[0-9]+]] = alloc_stack $Unloadable
// CHECK: [[SETTER:%[0-9]+]] = function_ref @_TF18address_only_typess11global_propPS_10Unloadable_
// CHECK: apply [[SETTER]]([[TEMP]])
// CHECK: dealloc_stack [[TEMP]]
}
// CHECK-LABEL: sil hidden @_TF18address_only_types43address_only_assignment_from_lv_to_property
func address_only_assignment_from_lv_to_property(let v: Unloadable) {
// CHECK: bb0([[VARG:%[0-9]+]] : $*Unloadable):
// CHECK: debug_value_addr [[VARG]] : $*Unloadable
// CHECK: [[TEMP:%[0-9]+]] = alloc_stack $Unloadable
// CHECK: copy_addr [[VARG]] to [initialization] [[TEMP]]
// CHECK: [[SETTER:%[0-9]+]] = function_ref @_TF18address_only_typess11global_propPS_10Unloadable_
// CHECK: apply [[SETTER]]([[TEMP]])
// CHECK: dealloc_stack [[TEMP]]
global_prop = v
}
// CHECK-LABEL: sil hidden @_TF18address_only_types16address_only_varFT_PS_10Unloadable_
func address_only_var() -> Unloadable {
// CHECK: bb0([[RET:%[0-9]+]] : $*Unloadable):
var x = some_address_only_function_1()
// CHECK: [[XBOX:%[0-9]+]] = alloc_box $Unloadable
// CHECK: [[XPB:%.*]] = project_box [[XBOX]]
// CHECK: apply {{%.*}}([[XPB]])
return x
// CHECK: copy_addr [[XPB]] to [initialization] [[RET]]
// CHECK: release [[XBOX]]
// CHECK: return
}
func unloadable_to_unloadable(x: Unloadable) -> Unloadable { return x }
var some_address_only_nontuple_arg_function : (Unloadable) -> Unloadable = unloadable_to_unloadable
// CHECK-LABEL: sil hidden @_TF18address_only_types39call_address_only_nontuple_arg_function
func call_address_only_nontuple_arg_function(x: Unloadable) {
some_address_only_nontuple_arg_function(x)
}
|
cd9bf315228e7c2b629df9589ff2ee6c
| 38.686441 | 127 | 0.636237 | false | false | false | false |
Bouke/HAP
|
refs/heads/master
|
Sources/VaporHTTP/Body/HTTPBody.swift
|
mit
|
1
|
import Foundation
/// Represents an `HTTPMessage`'s body.
///
/// let body = HTTPBody(string: "Hello, world!")
///
/// This can contain any data (streaming or static) and should match the message's `"Content-Type"` header.
public struct HTTPBody: LosslessHTTPBodyRepresentable, CustomStringConvertible, CustomDebugStringConvertible {
/// An empty `HTTPBody`.
public static let empty: HTTPBody = .init()
/// Returns the body's contents as `Data`. `nil` if the body is streaming.
public var data: Data? {
storage.data
}
/// The size of the body's contents. `nil` if the body is streaming.
public var count: Int? {
storage.count
}
/// See `CustomStringConvertible`.
public var description: String {
switch storage {
case .data, .buffer, .dispatchData, .staticString, .string, .none: return debugDescription
}
}
/// See `CustomDebugStringConvertible`.
public var debugDescription: String {
switch storage {
case .none: return "<no body>"
case .buffer(let buffer): return buffer.getString(at: 0, length: buffer.readableBytes) ?? "n/a"
case .data(let data): return String(data: data, encoding: .ascii) ?? "n/a"
case .dispatchData(let data): return String(data: Data(data), encoding: .ascii) ?? "n/a"
case .staticString(let string): return string.description
case .string(let string): return string
}
}
/// Internal storage.
var storage: HTTPBodyStorage
/// Creates an empty body. Useful for `GET` requests where HTTP bodies are forbidden.
public init() {
self.storage = .none
}
/// Create a new body wrapping `Data`.
public init(data: Data) {
storage = .data(data)
}
/// Create a new body wrapping `DispatchData`.
public init(dispatchData: DispatchData) {
storage = .dispatchData(dispatchData)
}
/// Create a new body from the UTF8 representation of a `StaticString`.
public init(staticString: StaticString) {
storage = .staticString(staticString)
}
/// Create a new body from the UTF8 representation of a `String`.
public init(string: String) {
self.storage = .string(string)
}
/// Create a new body from a Swift NIO `ByteBuffer`.
public init(buffer: ByteBuffer) {
self.storage = .buffer(buffer)
}
/// Internal init.
internal init(storage: HTTPBodyStorage) {
self.storage = storage
}
/// See `LosslessHTTPBodyRepresentable`.
public func convertToHTTPBody() -> HTTPBody {
self
}
}
/// Maximum streaming body size to use for `debugPrint(_:)`.
private let maxDebugStreamingBodySize: Int = 1_000_000
|
c309c9ee33a9379dda76219e65bbaccc
| 30.837209 | 110 | 0.642075 | false | false | false | false |
wireapp/wire-ios
|
refs/heads/develop
|
Wire-iOS Tests/AudioMessageViewTests.swift
|
gpl-3.0
|
1
|
//
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import XCTest
@testable import Wire
extension MockMessage: AudioTrack {
public var title: String? {
return .none
}
public var author: String? {
return .none
}
public var duration: TimeInterval {
return 9999
}
public var streamURL: URL? {
return .none
}
public var previewStreamURL: URL? {
return .none
}
public var failedToLoad: Bool {
get {
return false
}
set {
// no-op
}
}
}
final class AudioMessageViewTests: XCTestCase {
var sut: AudioMessageView!
var mediaPlaybackManager: MediaPlaybackManager!
override func setUp() {
super.setUp()
let url = Bundle(for: type(of: self)).url(forResource: "audio_sample", withExtension: "m4a")!
let audioMessage = MockMessageFactory.audioMessage(config: {
$0.backingFileMessageData?.transferState = .uploaded
$0.backingFileMessageData?.downloadState = .downloaded
$0.backingFileMessageData.fileURL = url
})
mediaPlaybackManager = MediaPlaybackManager(name: "conversationMedia")
sut = AudioMessageView(mediaPlaybackManager: mediaPlaybackManager)
sut.audioTrackPlayer?.load(audioMessage, sourceMessage: audioMessage)
sut.configure(for: audioMessage, isInitial: true)
}
override func tearDown() {
sut = nil
mediaPlaybackManager = nil
super.tearDown()
}
func testThatAudioMessageIsResumedAfterIncomingCallIsTerminated() {
// GIVEN & WHEN
// play
sut.playButton.sendActions(for: .touchUpInside)
XCTAssert((sut.audioTrackPlayer?.isPlaying)!)
// THEN
let incomingState = CallState.incoming(video: false, shouldRing: true, degraded: false)
sut.callCenterDidChange(callState: incomingState, conversation: ZMConversation(), caller: ZMUser(), timestamp: nil, previousCallState: nil)
XCTAssertFalse((sut.audioTrackPlayer?.isPlaying)!)
sut.callCenterDidChange(callState: .terminating(reason: WireSyncEngine.CallClosedReason.normal), conversation: ZMConversation(), caller: ZMUser(), timestamp: nil, previousCallState: incomingState)
XCTAssert((sut.audioTrackPlayer?.isPlaying)!)
}
func testThatAudioMessageIsNotResumedIfItIsPausedAfterIncomingCallIsTerminated() {
// GIVEN & WHEN
// play
sut.playButton.sendActions(for: .touchUpInside)
XCTAssert((sut.audioTrackPlayer?.isPlaying)!)
// pause
sut.playButton.sendActions(for: .touchUpInside)
XCTAssertFalse((sut.audioTrackPlayer?.isPlaying)!)
// THEN
let incomingState = CallState.incoming(video: false, shouldRing: true, degraded: false)
sut.callCenterDidChange(callState: incomingState, conversation: ZMConversation(), caller: ZMUser(), timestamp: nil, previousCallState: nil)
XCTAssertFalse((sut.audioTrackPlayer?.isPlaying)!)
sut.callCenterDidChange(callState: .terminating(reason: WireSyncEngine.CallClosedReason.normal), conversation: ZMConversation(), caller: ZMUser(), timestamp: nil, previousCallState: incomingState)
XCTAssertFalse((sut.audioTrackPlayer?.isPlaying)!)
}
}
|
fad5a5e04ecfae195ceff3fa52acfa9f
| 31.300813 | 204 | 0.684621 | false | false | false | false |
DarrenKong/firefox-ios
|
refs/heads/master
|
Client/Frontend/Browser/LocalRequestHelper.swift
|
mpl-2.0
|
6
|
/* 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 WebKit
class LocalRequestHelper: TabContentScript {
func scriptMessageHandlerName() -> String? {
return "localRequestHelper"
}
func userContentController(_ userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
guard message.frameInfo.request.url?.isLocal ?? false else { return }
let params = message.body as! [String: String]
if params["type"] == "load",
let urlString = params["url"],
let url = URL(string: urlString) {
_ = message.webView?.load(PrivilegedRequest(url: url) as URLRequest)
} else if params["type"] == "reload" {
_ = message.webView?.reload()
} else {
assertionFailure("Invalid message: \(message.body)")
}
}
class func name() -> String {
return "LocalRequestHelper"
}
}
|
e256df649608e43bde92b6547f1ebd11
| 33.875 | 132 | 0.640681 | false | false | false | false |
garygriswold/Bible.js
|
refs/heads/master
|
Plugins/AudioPlayer/src/ios/AudioPlayer_TestHarness/AudioPlayer_TestHarness/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// AudioPlayer
//
// Created by Gary Griswold on 7/31/17.
// Copyright © 2017 ShortSands. All rights reserved.
//
import UIKit
import AudioPlayer
class ViewController: UIViewController {
let audioController = AudioBibleController.shared
override func viewDidLoad() {
super.viewDidLoad()
let readVersion = "KJVPD"//WEB"//KJVPD"//
let readLang = "eng"
let readBook = "JHN"
let readChapter = 2
self.audioController.findAudioVersion(version: readVersion, silLang: readLang,
complete: { bookIdList in
print("BOOKS: \(bookIdList)")
self.audioController.present(view: self.view, book: readBook,
chapterNum: readChapter, complete: { error in
print("ViewController.present did finish error: \(String(describing: error))")
})
})
// let readBook2 = "MAT"
// self.audioController.present(view: self.view, book: readBook2, chapterNum: readChapter,
// complete: { error in }
// )
//
// let readBook3 = "EPH"
// self.audioController.present(view: self.view, book: readBook3, chapterNum: readChapter,
// complete: { error in }
// )
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
print("****** viewWillDisappear *****")
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
print("****** viewDidDisappear *****")
}
}
|
0f58a4d57a80b7a288a9115e025c60ec
| 33.224138 | 118 | 0.532997 | false | false | false | false |
zmian/xcore.swift
|
refs/heads/main
|
Sources/Xcore/Cocoa/Components/UIImage/ImageFetcher/ImageDownloader.swift
|
mit
|
1
|
//
// Xcore
// Copyright © 2018 Xcore
// MIT license, see LICENSE file for details
//
import UIKit
import SDWebImage
extension ImageSourceType.CacheType {
fileprivate init(_ type: SDImageCacheType) {
switch type {
case .none:
self = .none
case .disk:
self = .disk
case .memory:
self = .memory
default:
fatalError(because: .unknownCaseDetected(type))
}
}
}
/// An internal class to download remote images.
///
/// Currently, it uses `SDWebImage` for download requests.
enum ImageDownloader {
typealias CancelToken = () -> Void
/// Downloads the image at the given URL, if not present in cache or return the
/// cached version otherwise.
static func load(
url: URL,
completion: @escaping (
_ image: UIImage?,
_ data: Data?,
_ error: Error?,
_ finished: Bool,
_ cacheType: ImageSourceType.CacheType
) -> Void
) -> CancelToken? {
let token = SDWebImageManager.shared.loadImage(
with: url,
options: [.avoidAutoSetImage],
progress: nil
) { image, data, error, cacheType, finished, _ in
completion(image, data, error, finished, .init(cacheType))
}
return token?.cancel
}
/// Downloads the image from the given url.
static func download(
url: URL,
completion: @escaping (
_ image: UIImage?,
_ data: Data?,
_ error: Error?,
_ finished: Bool
) -> Void
) {
SDWebImageDownloader.shared.downloadImage(
with: url,
options: [],
progress: nil
) { image, data, error, finished in
completion(image, data, error, finished)
}
}
static func removeCache() {
SDImageCache.shared.apply {
$0.clearMemory()
$0.clearDisk()
$0.deleteOldFiles()
}
}
}
|
5aa3b4fbc4ee62b3c2ff69380fa3041c
| 24.9125 | 83 | 0.527255 | false | false | false | false |
tbergmen/TableViewModel
|
refs/heads/master
|
Example/Tests/ViewControllerTestingHelper.swift
|
mit
|
1
|
/*
Copyright (c) 2016 Tunca Bergmen <tunca@bergmen.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
import UIKit
public class ViewControllerTestingHelper {
class func wait() {
NSRunLoop.mainRunLoop().runUntilDate(NSDate(timeIntervalSinceNow: 0.01))
}
class func emptyViewController() -> UIViewController {
let viewController = UIViewController()
viewController.view = UIView()
return viewController
}
class func prepareWindowWithRootViewController(viewController: UIViewController) -> UIWindow {
let window: UIWindow = UIWindow(frame: CGRect())
window.makeKeyAndVisible()
window.rootViewController = viewController
wait()
return window
}
class func presentViewController(viewController: UIViewController) {
let window: UIWindow = prepareWindowWithRootViewController(emptyViewController())
window.rootViewController?.presentViewController(viewController, animated: false, completion: nil)
wait()
}
class func dismissViewController(viewController: UIViewController) {
viewController.dismissViewControllerAnimated(false, completion: nil)
wait()
}
class func presentAndDismissViewController(viewController: UIViewController) {
presentViewController(viewController)
dismissViewController(viewController)
}
class func pushViewController(viewController: UIViewController) -> UINavigationController {
let navigationController: UINavigationController = UINavigationController(rootViewController: emptyViewController())
_ = prepareWindowWithRootViewController(navigationController)
navigationController.pushViewController(viewController, animated: false)
wait()
return navigationController
}
}
|
816314495a98593209a12c93d0f08ef1
| 39.271429 | 124 | 0.759404 | false | false | false | false |
kfix/MacPin
|
refs/heads/main
|
modules/Linenoise/History.swift
|
gpl-3.0
|
1
|
/*
Copyright (c) 2017, Andy Best <andybest.net at gmail dot com>
Copyright (c) 2010-2014, Salvatore Sanfilippo <antirez at gmail dot com>
Copyright (c) 2010-2013, Pieter Noordhuis <pcnoordhuis at gmail dot com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
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 Foundation
internal class History {
public enum HistoryDirection: Int {
case previous = -1
case next = 1
}
var maxLength: UInt = 0 {
didSet {
if history.count > maxLength && maxLength > 0 {
history.removeFirst(history.count - Int(maxLength))
}
}
}
private var index: Int = 0
var currentIndex: Int {
return index
}
private var hasTempItem: Bool = false
private var history: [String] = [String]()
var historyItems: [String] {
return history
}
public func add(_ item: String) {
// Don't add a duplicate if the last item is equal to this one
if let lastItem = history.last {
if lastItem == item {
// Reset the history pointer to the end index
index = history.endIndex
return
}
}
// Remove an item if we have reached maximum length
if maxLength > 0 && history.count >= maxLength {
_ = history.removeFirst()
}
history.append(item)
// Reset the history pointer to the end index
index = history.endIndex
}
func replaceCurrent(_ item: String) {
history[index] = item
}
// MARK: - History Navigation
internal func navigateHistory(direction: HistoryDirection) -> String? {
if history.count == 0 {
return nil
}
switch direction {
case .next:
index += HistoryDirection.next.rawValue
case .previous:
index += HistoryDirection.previous.rawValue
}
// Stop at the beginning and end of history
if index < 0 {
index = 0
return nil
} else if index >= history.count {
index = history.count
return nil
}
return history[index]
}
// MARK: - Saving and loading
internal func save(toFile path: String) throws {
let output = history.joined(separator: "\n")
try output.write(toFile: path, atomically: true, encoding: .utf8)
}
internal func load(fromFile path: String) throws {
let input = try String(contentsOfFile: path, encoding: .utf8)
input.split(separator: "\n").forEach {
add(String($0))
}
}
}
|
aeff0f713deecefcc7512d5ab5849cba
| 30.76 | 80 | 0.625189 | false | false | false | false |
PlutoMa/Swift-LeetCode
|
refs/heads/master
|
Code/Problem009.playground/Contents.swift
|
mit
|
1
|
//: Playground - noun: a place where people can play
import UIKit
class Solution {
func isPalindrome(_ x: Int) -> Bool {
if x < 0 {
return false
}
let xString = String(x)
if xString.characters.count == 1 {
return true
}
let count = xString.characters.count / 2
for i in 1...count {
let startString = xString.substring(to: xString.index(xString.startIndex, offsetBy: i))
let startChar = startString.substring(from: startString.index(before: startString.endIndex))
let endString = xString.substring(from: xString.index(xString.endIndex, offsetBy: -i))
let endChar = endString.substring(to: endString.index(after: endString.startIndex))
if startChar != endChar {
return false
}
}
return true
}
}
print(Solution().isPalindrome(123))
print(Solution().isPalindrome(1221))
print(Solution().isPalindrome(-123))
|
331ad6bf93f95f8f02175c5eebd04bc8
| 31 | 104 | 0.589443 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
refs/heads/master
|
Modules/FeatureAuthentication/Sources/FeatureAuthenticationDomain/DIKit.swift
|
lgpl-3.0
|
1
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import BlockchainNamespace
import DIKit
import WalletPayloadKit
extension DependencyContainer {
// MARK: - FeatureAuthenticationDomain Module
public static var featureAuthenticationDomain = module {
// MARK: - Services
factory { JWTService() as JWTServiceAPI }
factory { AccountRecoveryService() as AccountRecoveryServiceAPI }
factory { MobileAuthSyncService() as MobileAuthSyncServiceAPI }
factory { ResetPasswordService() as ResetPasswordServiceAPI }
single { PasswordValidator() as PasswordValidatorAPI }
single { SeedPhraseValidator() as SeedPhraseValidatorAPI }
single { SharedKeyParsingService() }
// MARK: - NabuAuthentication
single { NabuAuthenticationExecutor() as NabuAuthenticationExecutorAPI }
single { NabuAuthenticationErrorBroadcaster() }
factory { () -> WalletRepositoryAPI in
let walletRepositoryProvider: WalletRepositoryProvider = DIKit.resolve()
return walletRepositoryProvider.repository as WalletRepositoryAPI
}
factory { () -> WalletRecoveryService in
WalletRecoveryService.live(
walletManager: DIKit.resolve(),
walletRecovery: DIKit.resolve(),
nativeWalletEnabled: { nativeWalletFlagEnabled() }
)
}
factory { () -> WalletCreationService in
let app: AppProtocol = DIKit.resolve()
let settingsClient: UpdateSettingsClientAPI = DIKit.resolve()
return WalletCreationService.live(
walletManager: DIKit.resolve(),
walletCreator: DIKit.resolve(),
nabuRepository: DIKit.resolve(),
updateCurrencyService: provideUpdateCurrencyForWallets(app: app, client: settingsClient),
nativeWalletCreationEnabled: { nativeWalletCreationFlagEnabled() }
)
}
factory { () -> WalletFetcherService in
WalletFetcherService.live(
walletManager: DIKit.resolve(),
accountRecoveryService: DIKit.resolve(),
walletFetcher: DIKit.resolve(),
nativeWalletEnabled: { nativeWalletFlagEnabled() }
)
}
factory { () -> NabuAuthenticationErrorReceiverAPI in
let broadcaster: NabuAuthenticationErrorBroadcaster = DIKit.resolve()
return broadcaster as NabuAuthenticationErrorReceiverAPI
}
factory { () -> UserAlreadyRestoredHandlerAPI in
let broadcaster: NabuAuthenticationErrorBroadcaster = DIKit.resolve()
return broadcaster as UserAlreadyRestoredHandlerAPI
}
factory { () -> NabuAuthenticationExecutorProvider in
{ () -> NabuAuthenticationExecutorAPI in
DIKit.resolve()
} as NabuAuthenticationExecutorProvider
}
}
}
|
0089525ed512b6c827af03614446aabe
| 34.247059 | 105 | 0.644192 | false | false | false | false |
tinyfool/GoodMorning
|
refs/heads/master
|
GoodMorning/GoodMorning/GoodMorning/BaseViewController.swift
|
mit
|
1
|
//
// BaseViewController.swift
// GoodMorning
//
// Created by pei hao on 3/16/15.
// Copyright (c) 2015 pei hao. All rights reserved.
//
import UIKit
import AVFoundation
class BaseViewController: UIViewController,AVSpeechSynthesizerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func speak(words:String) {
var synthesizer = AVSpeechSynthesizer();
var utterance = AVSpeechUtterance(string: "");
utterance = AVSpeechUtterance(string:words);
utterance.voice = AVSpeechSynthesisVoice(language:"zh-CN");
utterance.rate = 0.1;
synthesizer.delegate = self
synthesizer.speakUtterance(utterance);
}
func speechSynthesizer(synthesizer: AVSpeechSynthesizer!, didFinishSpeechUtterance utterance: AVSpeechUtterance!) {
//self.parentViewController
}
/*
// 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.
}
*/
}
|
42920cff4e19899c5c6963c6578869c5
| 27.442308 | 119 | 0.676133 | false | false | false | false |
cwaffles/Soulcast
|
refs/heads/master
|
Soulcast/IncomingQueue.swift
|
mit
|
1
|
import Foundation
import UIKit
let soloQueue = IncomingQueue()
protocol IncomingQueueDelegate: class {
func didEnqueue()
func didDequeue()
func didBecomeEmpty()
}
class IncomingQueue: NSObject, UICollectionViewDataSource {
let cellIdentifier:String = NSStringFromClass(IncomingCollectionCell)
var count:Int {return soulQueue.count}
fileprivate let soulQueue = Queue<Soul>()
weak var delegate:IncomingQueueDelegate?
func enqueue(_ someSoul:Soul) {
soulQueue.append(someSoul)
delegate?.didEnqueue()
}
var isEmpty:Bool { return count == 0 }
func peek() -> Soul? {
return soulQueue.head?.value
}
func purge() {
for _ in 0...count {
soulQueue.dequeue()
}
}
func dequeue() -> Soul? {
let tempSoul = soulQueue.dequeue()
if tempSoul != nil {
delegate?.didDequeue()
}
if soulQueue.count == 0 {
self.delegate?.didBecomeEmpty()
}
return tempSoul
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return soulQueue.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! IncomingCollectionCell
var someNode = soulQueue.head
if indexPath.row != 0 {
for _ in 1 ... indexPath.row {
someNode = someNode?.next
}
}
let theSoul = someNode!.value
cell.radius = Float(theSoul.radius!)
cell.epoch = theSoul.epoch!
return cell
}
}
// singly rather than doubly linked list implementation
// private, as users of Queue never use this directly
private final class QueueNode<T> {
// note, not optional – every node has a value
var value: T
// but the last node doesn't have a next
var next: QueueNode<T>? = nil
init(value: T) { self.value = value }
}
// Ideally, Queue would be a struct with value semantics but
// I'll leave that for now
public final class Queue<T> {
// note, these are both optionals, to handle
// an empty queue
fileprivate var head: QueueNode<T>? = nil
fileprivate var tail: QueueNode<T>? = nil
public init() { }
}
extension Queue {
// append is the standard name in Swift for this operation
public func append(_ newElement: T) {
let oldTail = tail
self.tail = QueueNode(value: newElement)
if head == nil { head = tail }
else { oldTail?.next = self.tail }
}
public func dequeue() -> T? {
if let head = self.head {
self.head = head.next
if head.next == nil { tail = nil }
return head.value
}
else {
return nil
}
}
}
public struct QueueIndex<T>: Comparable {
/// Returns a Boolean value indicating whether the value of the first
/// argument is less than that of the second argument.
///
/// This function is the only requirement of the `Comparable` protocol. The
/// remainder of the relational operator functions are implemented by the
/// standard library for any type that conforms to `Comparable`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func <(lhs: QueueIndex<T>, rhs: QueueIndex<T>) -> Bool {
return lhs.node === rhs.node
}
fileprivate let node: QueueNode<T>?
public func successor() -> QueueIndex<T> {
return QueueIndex(node: node?.next)
}
}
public func ==<T>(lhs: QueueIndex<T>, rhs: QueueIndex<T>) -> Bool {
return lhs.node === rhs.node
}
extension Queue: MutableCollection {
/// Returns the position immediately after the given index.
///
/// - Parameter i: A valid index of the collection. `i` must be less than
/// `endIndex`.
/// - Returns: The index value immediately after `i`.
public func index(after i: QueueIndex<T>) -> QueueIndex<T> {
return i
}
public typealias Index = QueueIndex<T>
public var startIndex: Index { return Index(node: head) }
public var endIndex: Index { return Index(node: nil) }
public subscript(idx: Index) -> T {
get {
precondition(idx.node != nil, "Attempt to subscript out of bounds")
return idx.node!.value
}
set(newValue) {
precondition(idx.node != nil, "Attempt to subscript out of bounds")
idx.node!.value = newValue
}
}
public typealias Iterator = IndexingIterator<Queue>
public func makeIterator() -> Iterator {
return Iterator(_elements: self)
}
}
|
11e5078c34ef4ed5b94c29c6cdadfab3
| 25.436782 | 129 | 0.66413 | false | false | false | false |
eoger/firefox-ios
|
refs/heads/master
|
Shared/GeneralUtils.swift
|
mpl-2.0
|
2
|
/* 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
/**
Assertion for checking that the call is being made on the main thread.
- parameter message: Message to display in case of assertion.
*/
public func assertIsMainThread(_ message: String) {
assert(Thread.isMainThread, message)
}
// Simple timer for manual profiling. Not for production use.
// Prints only if timing is longer than a threshold (to reduce noisy output).
open class PerformanceTimer {
let startTime: CFAbsoluteTime
var endTime: CFAbsoluteTime?
let threshold: Double
let label: String
public init(thresholdSeconds: Double = 0.001, label: String = "") {
self.threshold = thresholdSeconds
self.label = label
startTime = CFAbsoluteTimeGetCurrent()
}
public func stopAndPrint() {
if let t = stop() {
print("Ran for \(t) seconds. [\(label)]")
}
}
public func stop() -> String? {
endTime = CFAbsoluteTimeGetCurrent()
if let duration = duration {
return "\(duration)"
}
return nil
}
public var duration: CFAbsoluteTime? {
if let endTime = endTime {
let time = endTime - startTime
return time > threshold ? time : nil
} else {
return nil
}
}
}
|
ba1c65ccbfb3bbc4448eddfba0ac4b36
| 27.711538 | 77 | 0.628935 | false | false | false | false |
dbart01/Rigid
|
refs/heads/master
|
Rigid/IfElseWritable.swift
|
bsd-2-clause
|
1
|
//
// IfElseWritable.swift
// Rigid
//
// Copyright (c) 2015 Dima Bart
// 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.
//
// The views and conclusions contained in the software and documentation are those
// of the authors and should not be interpreted as representing official policies,
// either expressed or implied, of the FreeBSD Project.
import Foundation
struct IfElseWritable: Writable {
typealias IfElsePair = (ifBlock: Writable, elseBlock: Writable)
var indent: Int = 0
let condition: String
let pair: IfElsePair
let useLineBreaks: Bool
// ----------------------------------
// MARK: - Init -
//
init(condition: String, pair: IfElsePair, useLineBreaks: Bool = false) {
self.condition = condition
self.pair = pair
self.useLineBreaks = useLineBreaks
}
// ----------------------------------
// MARK: - Writable -
//
func content() -> String {
var content = "\n"
content += "#if \(self.condition)"
if self.useLineBreaks {
content += "\n"
}
content += pair.ifBlock.content()
content += "#else"
if self.useLineBreaks {
content += "\n"
}
content += pair.elseBlock.content()
content += "#endif\n"
return content
}
}
|
15740605b967f052ca5004a1c0394182
| 35.418919 | 83 | 0.648478 | false | false | false | false |
pendowski/PopcornTimeIOS
|
refs/heads/master
|
Popcorn Time/API/AirPlayManager.swift
|
gpl-3.0
|
1
|
import Foundation
import MediaPlayer
enum TableViewUpdates {
case Reload
case Insert
case Delete
}
protocol ConnectDevicesProtocol: class {
func updateTableView(dataSource newDataSource: [AnyObject], updateType: TableViewUpdates, indexPaths: [NSIndexPath]?)
func didConnectToDevice(deviceIsChromecast chromecast: Bool)
}
class AirPlayManager: NSObject {
var dataSourceArray = [MPAVRouteProtocol]()
weak var delegate: ConnectDevicesProtocol?
let MPAudioDeviceControllerClass: NSObject.Type = NSClassFromString("MPAudioDeviceController") as! NSObject.Type
let MPAVRoutingControllerClass: NSObject.Type = NSClassFromString("MPAVRoutingController") as! NSObject.Type
var routingController: MPAVRoutingControllerProtocol
var audioDeviceController: MPAudioDeviceControllerProtocol
override init() {
routingController = MPAVRoutingControllerClass.init() as MPAVRoutingControllerProtocol
audioDeviceController = MPAudioDeviceControllerClass.init() as MPAudioDeviceControllerProtocol
super.init()
audioDeviceController.setRouteDiscoveryEnabled!(true)
routingController.setDelegate!(self)
updateAirPlayDevices()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(updateAirPlayDevices), name: MPVolumeViewWirelessRouteActiveDidChangeNotification, object: nil)
}
func mirrorChanged(sender: UISwitch, selectedRoute: MPAVRouteProtocol) {
if sender.on {
routingController.pickRoute!(selectedRoute.wirelessDisplayRoute!())
} else {
routingController.pickRoute!(selectedRoute)
}
}
func updateAirPlayDevices() {
routingController.fetchAvailableRoutesWithCompletionHandler! { (routes) in
if routes.count > self.dataSourceArray.count {
var indexPaths = [NSIndexPath]()
for index in self.dataSourceArray.count..<routes.count {
indexPaths.append(NSIndexPath(forRow: index, inSection: 0))
}
self.dataSourceArray = routes
self.delegate?.updateTableView(dataSource: self.dataSourceArray, updateType: .Insert, indexPaths: indexPaths)
} else if routes.count < self.dataSourceArray.count {
var indexPaths = [NSIndexPath]()
for (index, route) in self.dataSourceArray.enumerate() {
if !routes.contains({ $0.routeUID!() == route.routeUID!() }) // If the new array doesn't contain an object in the old array it must have been removed
{
indexPaths.append(NSIndexPath(forRow: index, inSection: 0))
}
}
self.dataSourceArray = routes
self.delegate?.updateTableView(dataSource: self.dataSourceArray, updateType: .Delete, indexPaths: indexPaths)
} else {
self.dataSourceArray = routes
self.delegate?.updateTableView(dataSource: self.dataSourceArray, updateType: .Reload, indexPaths: nil)
}
}
}
func airPlayItemImage(row: Int) -> UIImage {
if let routeType = self.audioDeviceController.routeDescriptionAtIndex!(row)["AirPlayPortExtendedInfo"]?["model"] as? String {
if routeType.containsString("AppleTV") {
return UIImage(named: "AirTV")!
} else {
return UIImage(named: "AirSpeaker")!
}
} else {
return UIImage(named: "AirAudio")!
}
}
func didSelectRoute(selectedRoute: MPAVRouteProtocol) {
self.routingController.pickRoute!(selectedRoute)
}
// MARK: - MPAVRoutingControllerDelegate
func routingControllerAvailableRoutesDidChange(controller: MPAVRoutingControllerProtocol) {
updateAirPlayDevices()
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
audioDeviceController.setRouteDiscoveryEnabled!(false)
}
}
// MARK: - MPProtocols
@objc protocol MPAVRoutingControllerProtocol {
optional func availableRoutes() -> NSArray
optional func discoveryMode() -> Int
optional func fetchAvailableRoutesWithCompletionHandler(completion: (routes: [MPAVRouteProtocol]) -> Void)
optional func name() -> AnyObject
optional func pickRoute(route: MPAVRouteProtocol) -> Bool
optional func pickRoute(route: MPAVRouteProtocol, withPassword: String) -> Bool
optional func videoRouteForRoute(route: MPAVRouteProtocol) -> MPAVRouteProtocol
optional func clearCachedRoutes()
optional func setDelegate(delegate: NSObject)
}
@objc protocol MPAVRouteProtocol {
optional func routeName() -> String
optional func routeSubtype() -> Int
optional func routeType() -> Int
optional func requiresPassword() -> Bool
optional func routeUID() -> String
optional func isPicked() -> Bool
optional func passwordType() -> Int
optional func wirelessDisplayRoute() -> MPAVRouteProtocol
}
@objc protocol MPAudioDeviceControllerProtocol {
optional func setRouteDiscoveryEnabled(enabled: Bool)
optional func routeDescriptionAtIndex(index: Int) -> [String: AnyObject]
}
extension NSObject : MPAVRoutingControllerProtocol, MPAVRouteProtocol, MPAudioDeviceControllerProtocol {
}
|
5634991026eda311b64a6ddcdfadc87e
| 39.75 | 178 | 0.687988 | false | false | false | false |
powerytg/Accented
|
refs/heads/master
|
Accented/UI/PearlFX/FilterUI/BrightnessFilterViewController.swift
|
bsd-3-clause
|
2
|
//
// BrightnessFilterViewController.swift
// PearlCam
//
// Created by Tiangong You on 6/10/17.
// Copyright © 2017 Tiangong You. All rights reserved.
//
import UIKit
class BrightnessFilterViewController: AdjustmentUIViewController {
@IBOutlet weak var brightnessSlider: FXSlider!
@IBOutlet weak var contrastSlider: FXSlider!
@IBOutlet weak var vibranceSlider: FXSlider!
override func viewDidLoad() {
super.viewDidLoad()
brightnessSlider.value = filterManager.exposure!
contrastSlider.value = filterManager.contrast!
vibranceSlider.value = filterManager.vibrance!
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func brightnessValueDidChange(_ sender: Any) {
filterManager.exposure = brightnessSlider.value
}
@IBAction func contrastValueDidChange(_ sender: Any) {
filterManager.contrast = contrastSlider.value
}
@IBAction func vibranceValueDidChange(_ sender: Any) {
filterManager.vibrance = vibranceSlider.value
}
}
|
d04a9971579385d8ea993e61c255f8bf
| 27.25641 | 66 | 0.701452 | false | false | false | false |
xiaomudegithub/viossvc
|
refs/heads/master
|
viossvc/General/Base/BaseCustomTableViewController.swift
|
apache-2.0
|
1
|
//
// BaseCustomTableViewController.swift
// viossvc
//
// Created by yaowang on 2016/10/29.
// Copyright © 2016年 ywwlcom.yundian. All rights reserved.
//
import UIKit
class BaseCustomTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource,TableViewHelperProtocol {
@IBOutlet weak var tableView: UITableView!
var tableViewHelper:TableViewHelper = TableViewHelper();
override func viewDidLoad() {
super.viewDidLoad()
initTableView();
}
//友盟页面统计
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
MobClick.beginLogPageView(NSStringFromClass(self.classForCoder))
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
MobClick.endLogPageView(NSStringFromClass(self.classForCoder))
}
final func initTableView() {
if tableView == nil {
for view:UIView in self.view.subviews {
if view.isKindOfClass(UITableView) {
tableView = view as? UITableView;
break;
}
}
}
if tableView.tableFooterView == nil {
tableView.tableFooterView = UIView(frame:CGRectMake(0,0,0,0.5));
}
tableView.delegate = self;
tableView.dataSource = self;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//MARK:TableViewHelperProtocol
func isSections() ->Bool {
return false;
}
func isCacheCellHeight() -> Bool {
return false;
}
func isCalculateCellHeight() ->Bool {
return isCacheCellHeight();
}
func tableView(tableView:UITableView ,cellIdentifierForRowAtIndexPath indexPath: NSIndexPath) -> String? {
return tableViewHelper.tableView(tableView, cellIdentifierForRowAtIndexPath: indexPath, controller: self);
}
func tableView(tableView:UITableView ,cellDataForRowAtIndexPath indexPath: NSIndexPath) -> AnyObject? {
return nil;
}
//MARK: -UITableViewDelegate
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return tableViewHelper.tableView(tableView, cellForRowAtIndexPath: indexPath, controller: self);
}
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
tableViewHelper.tableView(tableView, willDisplayCell: cell, forRowAtIndexPath: indexPath, controller: self);
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if( isCalculateCellHeight() ) {
let cellHeight:CGFloat = tableViewHelper.tableView(tableView, heightForRowAtIndexPath: indexPath, controller: self);
if( cellHeight != CGFloat.max ) {
return cellHeight;
}
}
return tableView.rowHeight;
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1;
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 0;
}
}
class BaseCustomRefreshTableViewController :BaseCustomTableViewController {
override func viewDidLoad() {
super.viewDidLoad();
self.setupRefreshControl();
}
internal func didRequestComplete(data:AnyObject?) {
endRefreshing();
self.tableView.reloadData();
}
func completeBlockFunc()->CompleteBlock {
return { [weak self] (obj) in
self?.didRequestComplete(obj)
}
}
override func didRequestError(error:NSError) {
self.endRefreshing()
super.didRequestError(error)
}
deinit {
performSelectorRemoveRefreshControl();
}
}
class BaseCustomListTableViewController :BaseCustomRefreshTableViewController {
internal var dataSource:Array<AnyObject>?;
override func didRequestComplete(data: AnyObject?) {
dataSource = data as? Array<AnyObject>;
super.didRequestComplete(dataSource);
}
//MARK: -UITableViewDelegate
override func numberOfSectionsInTableView(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: NSIndexPath) -> 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 BaseCustomPageListTableViewController :BaseCustomListTableViewController {
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);
}
override func didRequestError(error:NSError) {
if (!(self.pageIndex == 1) ) {
self.errorLoadMore()
}
self.setIsLoadData(true)
super.didRequestError(error)
}
deinit {
removeLoadMore();
}
}
|
949839950e2a8b86e87d00219fff5527
| 29.756345 | 128 | 0.636244 | false | false | false | false |
IngmarStein/swift
|
refs/heads/master
|
test/1_stdlib/OptionalRenames.swift
|
apache-2.0
|
6
|
// RUN: %target-parse-verify-swift
func getInt(x: Int) -> Int? {
if x == 0 {
return .None // expected-error {{'None' has been renamed to 'none'}} {{13-17=none}}
}
return .Some(1) // expected-error {{'Some' has been renamed to 'some'}} {{11-15=some}}
}
let x = Optional.Some(1) // expected-error {{'Some' has been renamed to 'some'}} {{18-22=some}}
switch x {
case .None: break // expected-error {{'None' has been renamed to 'none'}} {{9-13=none}}
case .Some(let x): print(x) // expected-error {{'Some' has been renamed to 'some'}} {{9-13=some}}
}
let optionals: (Int?, Int?) = (Optional.Some(1), .None)
// expected-error@-1 {{'Some' has been renamed to 'some'}} {{41-45=some}}
// expected-error@-2 {{'None' has been renamed to 'none'}} {{51-55=none}}
switch optionals {
case (.None, .none): break // expected-error {{'None' has been renamed to 'none'}} {{10-14=none}}
case (.Some(let left), .some(let right)): break // expected-error {{'Some' has been renamed to 'some'}} {{10-14=some}}
default: break
}
|
4f0d233f4f2784a140206829889c97a4
| 38.615385 | 120 | 0.619417 | false | false | false | false |
ZhangMingNan/MNMeiTuan
|
refs/heads/master
|
15-MeiTuan/Kingfisher-master/Kingfisher/ImageCache.swift
|
apache-2.0
|
8
|
//
// ImageCache.swift
// Kingfisher
//
// Created by Wei Wang on 15/4/6.
//
// Copyright (c) 2015 Wei Wang <onevcat@gmail.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
/**
This notification will be sent when the disk cache got cleaned either there are cached files expired or the total size exceeding the max allowed size. The `clearDiskCache` method will not trigger this notification.
The `object` of this notification is the `ImageCache` object which sends the notification.
A list of removed hashes (files) could be retrieved by accessing the array under `KingfisherDiskCacheCleanedHashKey` key in `userInfo` of the notification object you received. By checking the array, you could know the hash codes of files are removed.
*/
public let KingfisherDidCleanDiskCacheNotification = "com.onevcat.Kingfisher.KingfisherDidCleanDiskCacheNotification"
/**
Key for array of cleaned hashes in `userInfo` of `KingfisherDidCleanDiskCacheNotification`.
*/
public let KingfisherDiskCacheCleanedHashKey = "com.onevcat.Kingfisher.cleanedHash"
private let defaultCacheName = "default"
private let cacheReverseDNS = "com.onevcat.Kingfisher.ImageCache."
private let ioQueueName = "com.onevcat.Kingfisher.ImageCache.ioQueue."
private let processQueueName = "com.onevcat.Kingfisher.ImageCache.processQueue."
private let defaultCacheInstance = ImageCache(name: defaultCacheName)
private let defaultMaxCachePeriodInSecond: NSTimeInterval = 60 * 60 * 24 * 7 //Cache exists for 1 week
public typealias RetrieveImageDiskTask = dispatch_block_t
/**
Cache type of a cached image.
- Memory: The image is cached in memory.
- Disk: The image is cached in disk.
*/
public enum CacheType {
case None, Memory, Disk, Watch
}
/**
* `ImageCache` represents both the memory and disk cache system of Kingfisher. While a default image cache object will be used if you prefer the extension methods of Kingfisher, you can create your own cache object and configure it as your need. You should use an `ImageCache` object to manipulate memory and disk cache for Kingfisher.
*/
public class ImageCache {
//Memory
private let memoryCache = NSCache()
/// The largest cache cost of memory cache. The total cost is pixel count of all cached images in memory.
public var maxMemoryCost: UInt = 0 {
didSet {
self.memoryCache.totalCostLimit = Int(maxMemoryCost)
}
}
//Disk
private let ioQueue: dispatch_queue_t
private let diskCachePath: String
private var fileManager: NSFileManager!
/// The longest time duration of the cache being stored in disk. Default is 1 week.
public var maxCachePeriodInSecond = defaultMaxCachePeriodInSecond
/// The largest disk size can be taken for the cache. It is the total allocated size of cached files in bytes. Default is 0, which means no limit.
public var maxDiskCacheSize: UInt = 0
private let processQueue: dispatch_queue_t
/// The default cache.
public class var defaultCache: ImageCache {
return defaultCacheInstance
}
/**
Init method. Passing a name for the cache. It represents a cache folder in the memory and disk.
:param: name Name of the cache. It will be used as the memory cache name and the disk cache folder name. This value should not be an empty string.
:returns: The cache object.
*/
public init(name: String) {
if name.isEmpty {
fatalError("[Kingfisher] You should specify a name for the cache. A cache with empty name is not permitted.")
}
let cacheName = cacheReverseDNS + name
memoryCache.name = cacheName
let paths = NSSearchPathForDirectoriesInDomains(.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true)
diskCachePath = paths.first!.stringByAppendingPathComponent(cacheName)
ioQueue = dispatch_queue_create(ioQueueName + name, DISPATCH_QUEUE_SERIAL)
processQueue = dispatch_queue_create(processQueueName + name, DISPATCH_QUEUE_CONCURRENT)
dispatch_sync(ioQueue, { () -> Void in
self.fileManager = NSFileManager()
})
NSNotificationCenter.defaultCenter().addObserver(self, selector: "clearMemoryCache", name: UIApplicationDidReceiveMemoryWarningNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "cleanExpiredDiskCache", name: UIApplicationWillTerminateNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "backgroundCleanExpiredDiskCache", name: UIApplicationDidEnterBackgroundNotification, object: nil)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
}
// MARK: - Store & Remove
public extension ImageCache {
/**
Store an image to cache. It will be saved to both memory and disk.
It is an async operation, if you need to do something about the stored image, use `-storeImage:forKey:toDisk:completionHandler:`
instead.
:param: image The image will be stored.
:param: key Key for the image.
*/
public func storeImage(image: UIImage, forKey key: String) {
storeImage(image, forKey: key, toDisk: true, completionHandler: nil)
}
/**
Store an image to cache. It is an async operation.
:param: image The image will be stored.
:param: key Key for the image.
:param: toDisk Whether this image should be cached to disk or not. If false, the image will be only cached in memory.
:param: completionHandler Called when stroe operation completes.
*/
public func storeImage(image: UIImage, forKey key: String, toDisk: Bool, completionHandler: (() -> ())?) {
memoryCache.setObject(image, forKey: key, cost: image.kf_imageCost)
if toDisk {
dispatch_async(ioQueue, { () -> Void in
if let data = UIImagePNGRepresentation(image) {
if !self.fileManager.fileExistsAtPath(self.diskCachePath) {
self.fileManager.createDirectoryAtPath(self.diskCachePath, withIntermediateDirectories: true, attributes: nil, error: nil)
}
self.fileManager.createFileAtPath(self.cachePathForKey(key), contents: data, attributes: nil)
if let handler = completionHandler {
dispatch_async(dispatch_get_main_queue()) {
handler()
}
}
} else {
if let handler = completionHandler {
dispatch_async(dispatch_get_main_queue()) {
handler()
}
}
}
})
} else {
if let handler = completionHandler {
handler()
}
}
}
/**
Remove the image for key for the cache. It will be opted out from both memory and disk.
It is an async operation, if you need to do something about the stored image, use `-removeImageForKey:fromDisk:completionHandler:`
instead.
:param: key Key for the image.
*/
public func removeImageForKey(key: String) {
removeImageForKey(key, fromDisk: true, completionHandler: nil)
}
/**
Remove the image for key for the cache. It is an async operation.
:param: key Key for the image.
:param: fromDisk Whether this image should be removed from disk or not. If false, the image will be only removed from memory.
:param: completionHandler Called when removal operation completes.
*/
public func removeImageForKey(key: String, fromDisk: Bool, completionHandler: (() -> ())?) {
memoryCache.removeObjectForKey(key)
if fromDisk {
dispatch_async(ioQueue, { () -> Void in
self.fileManager.removeItemAtPath(self.cachePathForKey(key), error: nil)
if let handler = completionHandler {
dispatch_async(dispatch_get_main_queue()) {
handler()
}
}
})
} else {
if let handler = completionHandler {
handler()
}
}
}
}
// MARK: - Get data from cache
extension ImageCache {
/**
Get an image for a key from memory or disk.
:param: key Key for the image.
:param: options Options of retriving image.
:param: completionHandler Called when getting operation completes with image result and cached type of this image. If there is no such key cached, the image will be `nil`.
:returns: The retriving task.
*/
public func retrieveImageForKey(key: String, options:KingfisherManager.Options, completionHandler: ((UIImage?, CacheType!) -> ())?) -> RetrieveImageDiskTask? {
// No completion handler. Not start working and early return.
if (completionHandler == nil) {
return dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS) {}
}
let block = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS) {
if let image = self.retrieveImageInMemoryCacheForKey(key) {
//Found image in memory cache.
if options.shouldDecode {
dispatch_async(self.processQueue, { () -> Void in
let result = image.kf_decodedImage(scale: options.scale)
dispatch_async(options.queue, { () -> Void in
completionHandler?(result, .Memory)
return
})
})
} else {
completionHandler?(image, .Memory)
}
} else {
//Begin to load image from disk
dispatch_async(self.ioQueue, { () -> Void in
if let image = self.retrieveImageInDiskCacheForKey(key, scale: options.scale) {
if options.shouldDecode {
dispatch_async(self.processQueue, { () -> Void in
let result = image.kf_decodedImage(scale: options.scale)
self.storeImage(result!, forKey: key, toDisk: false, completionHandler: nil)
dispatch_async(options.queue, { () -> Void in
completionHandler?(result, .Memory)
return
})
})
} else {
self.storeImage(image, forKey: key, toDisk: false, completionHandler: nil)
dispatch_async(options.queue, { () -> Void in
if let completionHandler = completionHandler {
completionHandler(image, .Disk)
}
})
}
} else {
// No image found from either memory or disk
dispatch_async(options.queue, { () -> Void in
if let completionHandler = completionHandler {
completionHandler(nil, nil)
}
})
}
})
}
}
dispatch_async(options.queue, block)
return block
}
/**
Get an image for a key from memory.
:param: key Key for the image.
:returns: The image object if it is cached, or `nil` if there is no such key in the cache.
*/
public func retrieveImageInMemoryCacheForKey(key: String) -> UIImage? {
return memoryCache.objectForKey(key) as? UIImage
}
/**
Get an image for a key from disk.
:param: key Key for the image.
:param: scale The scale factor to assume when interpreting the image data.
:returns: The image object if it is cached, or `nil` if there is no such key in the cache.
*/
public func retrieveImageInDiskCacheForKey(key: String, scale: CGFloat = KingfisherManager.DefaultOptions.scale) -> UIImage? {
return diskImageForKey(key, scale: scale)
}
}
// MARK: - Clear & Clean
extension ImageCache {
/**
Clear memory cache.
*/
@objc public func clearMemoryCache() {
memoryCache.removeAllObjects()
}
/**
Clear disk cache. This is an async operation.
*/
public func clearDiskCache() {
clearDiskCacheWithCompletionHandler(nil)
}
/**
Clear disk cache. This is an async operation.
:param: completionHander Called after the operation completes.
*/
public func clearDiskCacheWithCompletionHandler(completionHander: (()->())?) {
dispatch_async(ioQueue, { () -> Void in
self.fileManager.removeItemAtPath(self.diskCachePath, error: nil)
self.fileManager.createDirectoryAtPath(self.diskCachePath, withIntermediateDirectories: true, attributes: nil, error: nil)
if let completionHander = completionHander {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completionHander()
})
}
})
}
/**
Clean expired disk cache. This is an async operation.
*/
@objc public func cleanExpiredDiskCache() {
cleanExpiredDiskCacheWithCompletionHander(nil)
}
/**
Clean expired disk cache. This is an async operation.
:param: completionHandler Called after the operation completes.
*/
public func cleanExpiredDiskCacheWithCompletionHander(completionHandler: (()->())?) {
// Do things in cocurrent io queue
dispatch_async(ioQueue, { () -> Void in
if let diskCacheURL = NSURL(fileURLWithPath: self.diskCachePath) {
let resourceKeys = [NSURLIsDirectoryKey, NSURLContentModificationDateKey, NSURLTotalFileAllocatedSizeKey]
let expiredDate = NSDate(timeIntervalSinceNow: -self.maxCachePeriodInSecond)
var cachedFiles = [NSURL: [NSObject: AnyObject]]()
var URLsToDelete = [NSURL]()
var diskCacheSize: UInt = 0
if let fileEnumerator = self.fileManager.enumeratorAtURL(diskCacheURL,
includingPropertiesForKeys: resourceKeys,
options: NSDirectoryEnumerationOptions.SkipsHiddenFiles,
errorHandler: nil) {
for fileURL in fileEnumerator.allObjects as! [NSURL] {
if let resourceValues = fileURL.resourceValuesForKeys(resourceKeys, error: nil) {
// If it is a Directory. Continue to next file URL.
if let isDirectory = resourceValues[NSURLIsDirectoryKey]?.boolValue {
if isDirectory {
continue
}
}
// If this file is expired, add it to URLsToDelete
if let modificationDate = resourceValues[NSURLContentModificationDateKey] as? NSDate {
if modificationDate.laterDate(expiredDate) == expiredDate {
URLsToDelete.append(fileURL)
continue
}
}
if let fileSize = resourceValues[NSURLTotalFileAllocatedSizeKey] as? NSNumber {
diskCacheSize += fileSize.unsignedLongValue
cachedFiles[fileURL] = resourceValues
}
}
}
}
for fileURL in URLsToDelete {
self.fileManager.removeItemAtURL(fileURL, error: nil)
}
if self.maxDiskCacheSize > 0 && diskCacheSize > self.maxDiskCacheSize {
let targetSize = self.maxDiskCacheSize / 2
// Sort files by last modify date. We want to clean from the oldest files.
let sortedFiles = cachedFiles.keysSortedByValue({ (resourceValue1, resourceValue2) -> Bool in
if let date1 = resourceValue1[NSURLContentModificationDateKey] as? NSDate {
if let date2 = resourceValue2[NSURLContentModificationDateKey] as? NSDate {
return date1.compare(date2) == .OrderedAscending
}
}
// Not valid date information. This should not happen. Just in case.
return true
})
for fileURL in sortedFiles {
if (self.fileManager.removeItemAtURL(fileURL, error: nil)) {
URLsToDelete.append(fileURL)
if let fileSize = cachedFiles[fileURL]?[NSURLTotalFileAllocatedSizeKey] as? NSNumber {
diskCacheSize -= fileSize.unsignedLongValue
}
if diskCacheSize < targetSize {
break
}
}
}
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if URLsToDelete.count != 0 {
let cleanedHashes = URLsToDelete.map({ (url) -> String in
return url.lastPathComponent!
})
NSNotificationCenter.defaultCenter().postNotificationName(KingfisherDidCleanDiskCacheNotification, object: self, userInfo: [KingfisherDiskCacheCleanedHashKey: cleanedHashes])
}
if let completionHandler = completionHandler {
completionHandler()
}
})
} else {
println("Bad disk cache path. \(self.diskCachePath) is not a valid local directory path.")
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if let completionHandler = completionHandler {
completionHandler()
}
})
}
})
}
/**
Clean expired disk cache when app in background. This is an async operation.
In most cases, you should not call this method explicitly.
It will be called automatically when `UIApplicationDidEnterBackgroundNotification` received.
*/
@objc public func backgroundCleanExpiredDiskCache() {
func endBackgroundTask(inout task: UIBackgroundTaskIdentifier) {
UIApplication.sharedApplication().endBackgroundTask(task)
task = UIBackgroundTaskInvalid
}
var backgroundTask: UIBackgroundTaskIdentifier!
backgroundTask = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler { () -> Void in
endBackgroundTask(&backgroundTask!)
}
cleanExpiredDiskCacheWithCompletionHander { () -> () in
endBackgroundTask(&backgroundTask!)
}
}
}
// MARK: - Check cache status
public extension ImageCache {
/**
* Cache result for checking whether an image is cached for a key.
*/
public struct CacheCheckResult {
public let cached: Bool
public let cacheType: CacheType?
}
/**
Check whether an image is cached for a key.
:param: key Key for the image.
:returns: The check result.
*/
public func isImageCachedForKey(key: String) -> CacheCheckResult {
if memoryCache.objectForKey(key) != nil {
return CacheCheckResult(cached: true, cacheType: .Memory)
}
let filePath = cachePathForKey(key)
if fileManager.fileExistsAtPath(filePath) {
return CacheCheckResult(cached: true, cacheType: .Disk)
}
return CacheCheckResult(cached: false, cacheType: nil)
}
/**
Get the hash for the key. This could be used for matching files.
:param: key The key which is used for caching.
:returns: Corresponding hash.
*/
public func hashForKey(key: String) -> String {
return cacheFileNameForKey(key)
}
/**
Calculate the disk size taken by cache.
It is the total allocated size of the cached files in bytes.
:param: completionHandler Called with the calculated size when finishes.
*/
public func calculateDiskCacheSizeWithCompletionHandler(completionHandler: ((size: UInt) -> ())?) {
dispatch_async(ioQueue, { () -> Void in
if let diskCacheURL = NSURL(fileURLWithPath: self.diskCachePath) {
let resourceKeys = [NSURLIsDirectoryKey, NSURLTotalFileAllocatedSizeKey]
var diskCacheSize: UInt = 0
if let fileEnumerator = self.fileManager.enumeratorAtURL(diskCacheURL,
includingPropertiesForKeys: resourceKeys,
options: NSDirectoryEnumerationOptions.SkipsHiddenFiles,
errorHandler: nil) {
for fileURL in fileEnumerator.allObjects as! [NSURL] {
if let resourceValues = fileURL.resourceValuesForKeys(resourceKeys, error: nil) {
// If it is a Directory. Continue to next file URL.
if let isDirectory = resourceValues[NSURLIsDirectoryKey]?.boolValue {
if isDirectory {
continue
}
}
if let fileSize = resourceValues[NSURLTotalFileAllocatedSizeKey] as? NSNumber {
diskCacheSize += fileSize.unsignedLongValue
}
}
}
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if let completionHandler = completionHandler {
completionHandler(size: diskCacheSize)
}
})
} else {
println("Bad disk cache path. \(self.diskCachePath) is not a valid local directory path.")
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if let completionHandler = completionHandler {
completionHandler(size: 0)
}
})
}
})
}
}
// MARK: - Internal Helper
extension ImageCache {
func diskImageForKey(key: String, scale: CGFloat) -> UIImage? {
if let data = diskImageDataForKey(key) {
if let image = UIImage(data: data, scale: scale) {
return image
} else {
return nil
}
} else {
return nil
}
}
func diskImageDataForKey(key: String) -> NSData? {
let filePath = cachePathForKey(key)
return NSData(contentsOfFile: filePath)
}
func cachePathForKey(key: String) -> String {
let fileName = cacheFileNameForKey(key)
return diskCachePath.stringByAppendingPathComponent(fileName)
}
func cacheFileNameForKey(key: String) -> String {
return key.kf_MD5()
}
}
extension UIImage {
var kf_imageCost: Int {
return Int(size.height * size.width * scale * scale)
}
}
extension Dictionary {
func keysSortedByValue(isOrderedBefore:(Value, Value) -> Bool) -> [Key] {
var array = Array(self)
sort(&array) {
let (lk, lv) = $0
let (rk, rv) = $1
return isOrderedBefore(lv, rv)
}
return array.map {
let (k, v) = $0
return k
}
}
}
|
c21f26a8a603d1202f928414c2dabbbb
| 39.781734 | 335 | 0.563029 | false | false | false | false |
bara86/BSImagePicker
|
refs/heads/master
|
Pod/Classes/Model/AssetCollectionDataSource.swift
|
mit
|
6
|
// The MIT License (MIT)
//
// Copyright (c) 2015 Joakim Gyllström
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Photos
final class AssetCollectionDataSource : NSObject, SelectableDataSource {
private var assetCollection: PHAssetCollection
var selections: [PHObject] = []
var delegate: SelectableDataDelegate?
var allowsMultipleSelection: Bool = false
var maxNumberOfSelections: Int = 1
var selectedIndexPaths: [NSIndexPath] {
get {
if selections.count > 0 {
return [NSIndexPath(forItem: 0, inSection: 0)]
} else {
return []
}
}
}
required init(assetCollection: PHAssetCollection) {
self.assetCollection = assetCollection
super.init()
}
// MARK: SelectableDataSource
var sections: Int {
get {
return 1
}
}
func numberOfObjectsInSection(section: Int) -> Int {
return 1
}
func objectAtIndexPath(indexPath: NSIndexPath) -> PHObject {
assert(indexPath.section < 1 && indexPath.row < 1, "AssetCollectionDataSource can only contain 1 section and row")
return assetCollection
}
func selectObjectAtIndexPath(indexPath: NSIndexPath) {
assert(indexPath.section < 1 && indexPath.row < 1, "AssetCollectionDataSource can only contain 1 section and row")
selections = [assetCollection]
}
func deselectObjectAtIndexPath(indexPath: NSIndexPath) {
assert(indexPath.section < 1 && indexPath.row < 1, "AssetCollectionDataSource can only contain 1 section and row")
selections = []
}
func isObjectAtIndexPathSelected(indexPath: NSIndexPath) -> Bool {
assert(indexPath.section < 1 && indexPath.row < 1, "AssetCollectionDataSource can only contain 1 section and row")
return selections.count > 0
}
}
|
e1d73580a6dccde4454badf1e5dbcf05
| 36.443038 | 122 | 0.682894 | false | false | false | false |
onemonth/TakePhotos
|
refs/heads/master
|
TakePhotos/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// TakePictures
//
// Created by Alfred Hanssen on 3/1/16.
// Copyright © 2016 One Month. 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 UIKit
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate
{
// MARK: Actions
@IBAction func presentCamera()
{
let sourceType = UIImagePickerControllerSourceType.Camera
self.presentImagePicker(sourceType: sourceType)
}
@IBAction func presentPhotoLibrary()
{
let sourceType = UIImagePickerControllerSourceType.PhotoLibrary
self.presentImagePicker(sourceType: sourceType)
}
@IBAction func presentSavedPhotosAlbum()
{
let sourceType = UIImagePickerControllerSourceType.SavedPhotosAlbum
self.presentImagePicker(sourceType: sourceType)
}
// MARK: Private API
private func presentImagePicker(sourceType sourceType: UIImagePickerControllerSourceType)
{
if UIImagePickerController.isSourceTypeAvailable(sourceType) == false
{
// The sourceType is not available
return
}
let viewController = UIImagePickerController()
viewController.sourceType = sourceType
viewController.delegate = self
self.presentViewController(viewController, animated: true, completion: nil)
}
// MARK: UIImagePickerControllerDelegate
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject])
{
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage
{
// Do something with the image
}
else if let URL = info[UIImagePickerControllerMediaURL] as? NSURL
{
// Do something with the URL
print(URL.absoluteString)
}
picker.dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController)
{
picker.dismissViewControllerAnimated(true, completion: nil)
}
}
|
cf22f8a298857b269c07793fbe7c3c19
| 33.354839 | 121 | 0.709546 | false | false | false | false |
ScoutHarris/WordPress-iOS
|
refs/heads/develop
|
WordPress/Classes/ViewRelated/Plans/FeatureItemRow.swift
|
gpl-2.0
|
2
|
import UIKit
import WordPressShared
struct FeatureItemRow: ImmuTableRow {
static let cell = ImmuTableCell.class(FeatureItemCell.self)
let title: String
let description: String
let iconURL: URL?
let action: ImmuTableAction? = nil
func configureCell(_ cell: UITableViewCell) {
guard let cell = cell as? FeatureItemCell else { return }
cell.featureTitleLabel?.text = title
if let featureDescriptionLabel = cell.featureDescriptionLabel {
cell.featureDescriptionLabel?.attributedText = attributedDescriptionText(description, font: featureDescriptionLabel.font)
}
if let iconURL = iconURL {
cell.featureIconImageView?.setImageWith(iconURL, placeholderImage: nil)
}
cell.featureTitleLabel.textColor = WPStyleGuide.darkGrey()
cell.featureDescriptionLabel.textColor = WPStyleGuide.grey()
WPStyleGuide.configureTableViewCell(cell)
}
fileprivate func attributedDescriptionText(_ text: String, font: UIFont) -> NSAttributedString {
let lineHeight: CGFloat = 18
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.maximumLineHeight = lineHeight
paragraphStyle.minimumLineHeight = lineHeight
let attributedText = NSMutableAttributedString(string: text, attributes: [NSParagraphStyleAttributeName: paragraphStyle, NSFontAttributeName: font])
return attributedText
}
}
|
9aa17ab57982f984188d1fbf5b98dd79
| 35.325 | 156 | 0.723331 | false | false | false | false |
qutheory/vapor
|
refs/heads/master
|
Sources/Vapor/Utilities/Storage.swift
|
mit
|
1
|
public struct Storage {
var storage: [ObjectIdentifier: AnyStorageValue]
struct Value<T>: AnyStorageValue {
var value: T
var onShutdown: ((T) throws -> ())?
func shutdown(logger: Logger) {
do {
try self.onShutdown?(self.value)
} catch {
logger.error("Could not shutdown \(T.self): \(error)")
}
}
}
let logger: Logger
public init(logger: Logger = .init(label: "codes.vapor.storage")) {
self.storage = [:]
self.logger = logger
}
public mutating func clear() {
self.storage = [:]
}
public subscript<Key>(_ key: Key.Type) -> Key.Value?
where Key: StorageKey
{
get {
self.get(Key.self)
}
set {
self.set(Key.self, to: newValue)
}
}
public func contains<Key>(_ key: Key.Type) -> Bool {
self.storage.keys.contains(ObjectIdentifier(Key.self))
}
public func get<Key>(_ key: Key.Type) -> Key.Value?
where Key: StorageKey
{
guard let value = self.storage[ObjectIdentifier(Key.self)] as? Value<Key.Value> else {
return nil
}
return value.value
}
public mutating func set<Key>(
_ key: Key.Type,
to value: Key.Value?,
onShutdown: ((Key.Value) throws -> ())? = nil
)
where Key: StorageKey
{
let key = ObjectIdentifier(Key.self)
if let value = value {
self.storage[key] = Value(value: value, onShutdown: onShutdown)
} else if let existing = self.storage[key] {
self.storage[key] = nil
existing.shutdown(logger: self.logger)
}
}
public func shutdown() {
self.storage.values.forEach {
$0.shutdown(logger: self.logger)
}
}
}
protocol AnyStorageValue {
func shutdown(logger: Logger)
}
public protocol StorageKey {
associatedtype Value
}
|
4b3642b4b518c8186b4a3fd478063a46
| 23.8875 | 94 | 0.542441 | false | false | false | false |
malaonline/iOS
|
refs/heads/master
|
mala-ios/View/Course/SingleCourseView.swift
|
mit
|
1
|
//
// SingleCourseView.swift
// mala-ios
//
// Created by 王新宇 on 16/6/15.
// Copyright © 2016年 Mala Online. All rights reserved.
//
import UIKit
class SingleCourseView: UIView {
// MARK: - Property
/// 单次课程数据模型
var model: StudentCourseModel? {
didSet {
DispatchQueue.main.async {
self.changeDisplayMode()
self.setupCourseInfo()
}
}
}
// MARK: - Components
/// 信息背景视图
private lazy var headerBackground: UIView = {
let view = UIView(UIColor(named: .Disabled))
view.layer.cornerRadius = 2
view.layer.masksToBounds = true
return view
}()
/// 学科年级信息标签
private lazy var subjectLabel: UILabel = {
let label = UILabel(
text: "学科",
fontSize: 14,
textColor: UIColor(named: .WhiteTranslucent9)
)
return label
}()
/// 直播课程图标
private lazy var liveCourseIcon: UIImageView = {
let imageView = UIImageView(imageName: "live_courseIcon")
return imageView
}()
/// 老师姓名图标
private lazy var teacherIcon: UIImageView = {
let imageView = UIImageView(imageName: "live_teacher")
return imageView
}()
/// 老师姓名标签
private lazy var teacherLabel: UILabel = {
let label = UILabel(
text: "老师姓名",
fontSize: 14,
textColor: UIColor(named: .ArticleSubTitle)
)
return label
}()
/// 助教老师姓名
private lazy var assistantLabel: UILabel = {
let label = UILabel(
text: "助教老师姓名",
fontSize: 13,
textColor: UIColor(named: .HeaderTitle)
)
return label
}()
/// 上课时间图标
private lazy var timeSlotIcon: UIImageView = {
let imageView = UIImageView(imageName: "comment_time")
return imageView
}()
/// 上课时间信息
private lazy var timeSlotLabel: UILabel = {
let label = UILabel(
text: "上课时间",
fontSize: 13,
textColor: UIColor(named: .ArticleSubTitle)
)
return label
}()
/// 上课地点图标
private lazy var schoolIcon: UIImageView = {
let imageView = UIImageView(imageName: "comment_location")
return imageView
}()
/// 上课地点
private lazy var schoolLabel: UILabel = {
let label = UILabel(
text: "上课地点",
fontSize: 13,
textColor: UIColor(named: .ArticleSubTitle)
)
label.numberOfLines = 0
return label
}()
/// 评论按钮
private lazy var commentButton: UIButton = {
let button = UIButton()
button.layer.borderWidth = 1
button.layer.cornerRadius = 4
button.layer.masksToBounds = true
button.contentEdgeInsets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
button.isHidden = true
return button
}()
// MARK: - Instance Method
override init(frame: CGRect) {
super.init(frame: frame)
setupUserInterface()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Private
private func setupUserInterface() {
backgroundColor = UIColor.white
// SubView
addSubview(headerBackground)
headerBackground.addSubview(subjectLabel)
headerBackground.addSubview(liveCourseIcon)
addSubview(teacherIcon)
addSubview(teacherLabel)
addSubview(assistantLabel)
addSubview(timeSlotIcon)
addSubview(timeSlotLabel)
addSubview(schoolIcon)
addSubview(schoolLabel)
addSubview(commentButton)
// AutoLayout
headerBackground.snp.makeConstraints { (maker) in
maker.top.equalTo(self)
maker.height.equalTo(32)
maker.left.equalTo(self)
maker.right.equalTo(self)
}
subjectLabel.snp.makeConstraints { (maker) in
maker.height.equalTo(14)
maker.left.equalTo(headerBackground).offset(10)
maker.centerY.equalTo(headerBackground)
}
liveCourseIcon.snp.makeConstraints { (maker) in
maker.height.equalTo(21)
maker.right.equalTo(headerBackground).offset(-10)
maker.centerY.equalTo(headerBackground)
}
teacherIcon.snp.makeConstraints { (maker) in
maker.top.equalTo(headerBackground.snp.bottom).offset(10)
maker.left.equalTo(headerBackground)
maker.width.equalTo(13)
maker.height.equalTo(13)
}
teacherLabel.snp.makeConstraints { (maker) in
maker.top.equalTo(teacherIcon)
maker.left.equalTo(teacherIcon.snp.right).offset(5)
maker.height.equalTo(13)
}
assistantLabel.snp.makeConstraints { (maker) in
maker.top.equalTo(teacherIcon)
maker.left.equalTo(teacherLabel.snp.right).offset(27.5)
maker.height.equalTo(13)
}
timeSlotIcon.snp.makeConstraints { (maker) in
maker.top.equalTo(teacherIcon.snp.bottom).offset(10)
maker.left.equalTo(headerBackground)
maker.width.equalTo(13)
maker.height.equalTo(13)
}
timeSlotLabel.snp.makeConstraints { (maker) in
maker.top.equalTo(timeSlotIcon)
maker.left.equalTo(timeSlotIcon.snp.right).offset(5)
maker.height.equalTo(13)
}
schoolIcon.snp.makeConstraints { (maker) in
maker.top.equalTo(timeSlotIcon.snp.bottom).offset(10)
maker.left.equalTo(headerBackground)
maker.width.equalTo(13)
maker.height.equalTo(15)
}
schoolLabel.snp.makeConstraints { (maker) in
maker.top.equalTo(schoolIcon)
maker.left.equalTo(schoolIcon.snp.right).offset(5)
maker.right.equalTo(self)
maker.bottom.equalTo(self).offset(-20)
}
commentButton.snp.makeConstraints { (maker) in
maker.top.equalTo(teacherLabel)
maker.right.equalTo(headerBackground)
maker.height.equalTo(24)
}
}
/// 加载课程数据
private func setupCourseInfo() {
guard let course = model else { return }
// 课程类型
if course.isLiveCourse == true {
liveCourseIcon.isHidden = false
assistantLabel.isHidden = false
teacherLabel.text = course.lecturer?.name
assistantLabel.text = String(format: "助教:%@", course.teacher?.name ?? "")
}else {
liveCourseIcon.isHidden = true
assistantLabel.isHidden = true
teacherLabel.text = course.teacher?.name
}
// 课程信息
subjectLabel.text = String(format: "%@%@", course.grade, course.subject)
timeSlotLabel.text = String(format: "%@-%@", getDateString(course.start, format: "HH:mm"), getDateString(course.end, format: "HH:mm"))
schoolLabel.attributedText = model?.attrAddressString
// 课程状态
switch course.status {
case .Past:
headerBackground.backgroundColor = UIColor(named: .Disabled)
commentButton.isHidden = false
break
case .Today:
headerBackground.backgroundColor = UIColor(named: .ThemeDeepBlue)
commentButton.isHidden = true
break
case .Future:
headerBackground.backgroundColor = UIColor(named: .ThemeDeepBlue)
commentButton.isHidden = true
break
}
}
/// 根据当前课程评价状态,渲染对应UI样式
private func changeDisplayMode() {
// 课程评价状态
if model?.comment != nil {
setStyleCommented()
}else if model?.isExpired == true {
setStyleExpired()
}else {
setStyleNoComments()
}
}
/// 设置过期样式
private func setStyleExpired() {
commentButton.layer.borderColor = UIColor(named: .HeaderTitle).cgColor
commentButton.setTitle("评价已过期", for: .normal)
commentButton.setTitleColor(UIColor(named: .HeaderTitle), for: .normal)
commentButton.setBackgroundImage(UIImage.withColor(UIColor.white), for: .normal)
commentButton.setBackgroundImage(UIImage.withColor(UIColor(named: .HeaderTitle)), for: .highlighted)
commentButton.titleLabel?.font = FontFamily.PingFangSC.Regular.font(12)
commentButton.isEnabled = false
}
/// 设置待评论样式
private func setStyleNoComments() {
commentButton.layer.borderColor = UIColor(named: .ThemeRed).cgColor
commentButton.setTitle("去评价", for: .normal)
commentButton.setTitleColor(UIColor(named: .ThemeRed), for: .normal)
commentButton.setBackgroundImage(UIImage.withColor(UIColor.white), for: .normal)
commentButton.setBackgroundImage(UIImage.withColor(UIColor(named: .ThemeRedHighlight)), for: .highlighted)
commentButton.titleLabel?.font = FontFamily.PingFangSC.Regular.font(12)
commentButton.addTarget(self, action: #selector(SingleCourseView.toComment), for: .touchUpInside)
}
/// 设置已评论样式
private func setStyleCommented() {
commentButton.layer.borderColor = UIColor(named: .commentBlue).cgColor
commentButton.setTitle("查看评价", for: .normal)
commentButton.setTitleColor(UIColor(named: .commentBlue), for: .normal)
commentButton.setBackgroundImage(UIImage.withColor(UIColor.white), for: .normal)
commentButton.setBackgroundImage(UIImage.withColor(UIColor(named: .CommitHighlightBlue)), for: .highlighted)
commentButton.titleLabel?.font = FontFamily.PingFangSC.Regular.font(12)
commentButton.addTarget(self, action: #selector(SingleCourseView.showComment), for: .touchUpInside)
}
// MARK: - Event Response
/// 去评价
@objc private func toComment() {
let commentWindow = CommentViewWindow(contentView: UIView())
commentWindow.finishedAction = { [weak self] in
self?.commentButton.removeTarget(self, action: #selector(SingleCourseView.toComment), for: .touchUpInside)
self?.setStyleCommented()
}
commentWindow.model = self.model ?? StudentCourseModel()
commentWindow.isJustShow = false
commentWindow.show()
}
/// 查看评价
@objc private func showComment() {
let commentWindow = CommentViewWindow(contentView: UIView())
commentWindow.model = self.model ?? StudentCourseModel()
commentWindow.isJustShow = true
commentWindow.show()
}
}
|
edccf4c0cdf171fd7a3d3d42f2053502
| 33.483974 | 142 | 0.603588 | false | false | false | false |
Shivol/Swift-CS333
|
refs/heads/master
|
examples/uiKit/uiKitCatalog/UIKitCatalog/CustomToolbarViewController.swift
|
mit
|
3
|
/*
Copyright (C) 2016 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
A view controller that demonstrates how to customize a UIToolbar.
*/
import UIKit
class CustomToolbarViewController: UIViewController {
// MARK: - Properties
@IBOutlet weak var toolbar: UIToolbar!
// MARK: - View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
configureToolbar()
}
// MARK: - Configuration
func configureToolbar() {
let toolbarBackgroundImage = UIImage(named: "toolbar_background")
toolbar.setBackgroundImage(toolbarBackgroundImage, forToolbarPosition: .bottom, barMetrics: .default)
let toolbarButtonItems = [
customImageBarButtonItem,
flexibleSpaceBarButtonItem,
customBarButtonItem
]
toolbar.setItems(toolbarButtonItems, animated: true)
}
// MARK: - UIBarButtonItem Creation and Configuration
var customImageBarButtonItem: UIBarButtonItem {
let customBarButtonItemImage = UIImage(named: "tools_icon")
let customImageBarButtonItem = UIBarButtonItem(image: customBarButtonItemImage, style: .plain, target: self, action: #selector(CustomToolbarViewController.barButtonItemClicked(_:)))
customImageBarButtonItem.tintColor = UIColor.applicationPurpleColor
return customImageBarButtonItem
}
var flexibleSpaceBarButtonItem: UIBarButtonItem {
// Note that there's no target/action since this represents empty space.
return UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
}
var customBarButtonItem: UIBarButtonItem {
let barButtonItem = UIBarButtonItem(title: NSLocalizedString("Button", comment: ""), style: .plain, target: self, action: #selector(CustomToolbarViewController.barButtonItemClicked(_:)))
let backgroundImage = UIImage(named: "WhiteButton")
barButtonItem.setBackgroundImage(backgroundImage, for: UIControlState(), barMetrics: .default)
let attributes = [
NSForegroundColorAttributeName: UIColor.applicationPurpleColor
]
barButtonItem.setTitleTextAttributes(attributes, for: UIControlState())
return barButtonItem
}
// MARK: - Actions
func barButtonItemClicked(_ barButtonItem: UIBarButtonItem) {
NSLog("A bar button item on the custom toolbar was clicked: \(barButtonItem).")
}
}
|
81aa8a88e23b688f19abb92810eccb3d
| 32.506667 | 194 | 0.70394 | false | true | false | false |
mortorqrobotics/morscout-ios
|
refs/heads/master
|
MorScout/Models/Dropdown.swift
|
mit
|
1
|
//
// Dropdown.swift
// MorScout
//
// Created by Farbod Rafezy on 3/1/16.
// Copyright © 2016 MorTorq. All rights reserved.
//
import Foundation
import SwiftyJSON
class Dropdown: DataPoint {
let name: String
var options: [String]
init(json: JSON) {
name = json["name"].stringValue
options = []
for (_, subJson):(String, JSON) in json["options"] {
options.append(subJson.stringValue)
}
}
init(name: String, options: [String]){
self.name = name
self.options = options
}
required convenience init(coder aDecoder: NSCoder) {
let name = aDecoder.decodeObject(forKey: "name") as! String
let options = aDecoder.decodeObject(forKey: "options") as! [String]
self.init(name: name, options: options)
}
func encodeWithCoder(_ aCoder: NSCoder) {
aCoder.encode(name, forKey: "name")
aCoder.encode(options, forKey: "options")
}
}
|
32d1a9f57c352a28b3373a17e0e3d3a0
| 24.605263 | 75 | 0.606372 | false | false | false | false |
TeamDeverse/BC-Agora
|
refs/heads/master
|
BC-Agora/background.swift
|
mit
|
1
|
//
// background.swift
// BC-Agora
//
// Created by William Bowditch on 11/16/15.
// Copyright © 2015 William Bowditch. All rights reserved.
//
import Foundation
//import UIView
extension UIViewController {
func addBackground() {
// screen width and height:
let width = UIScreen.mainScreen().bounds.size.width
let height = UIScreen.mainScreen().bounds.size.height
let imageViewBackground = UIImageView(frame: CGRectMake(0, 0, width, height))
imageViewBackground.image = UIImage(named: "YOUR IMAGE NAME GOES HERE")
// you can change the content mode:
imageViewBackground.contentMode = UIViewContentMode.ScaleAspectFill
self.addSubview(imageViewBackground)
self.sendSubviewToBack(imageViewBackground)
}}
|
71e92d7b52fff29ff236389d4f64daa9
| 29.222222 | 85 | 0.676471 | false | false | false | false |
armadsen/CocoaHeads-SLC-Presentations
|
refs/heads/master
|
IntroToConcurrentProgramming/GCD.playground/Pages/Untitled Page 4.xcplaygroundpage/Contents.swift
|
mit
|
1
|
//: [Previous](@previous)
import Foundation
let queue = OperationQueue()
queue.name = "MySerialOperationQueue"
queue.maxConcurrentOperationCount = 1
let op1 = BlockOperation {
print("Do this first")
}
let op2 = BlockOperation {
print("Do this second")
}
let op3 = BlockOperation {
print("Do this third")
}
queue.waitUntilAllOperationsAreFinished()
print("Done!")
//: [Next](@next)
|
89a2d82ace1fab647a78995454fa4f43
| 15.04 | 41 | 0.703242 | false | false | false | false |
northwoodspd/FluentConstraints
|
refs/heads/master
|
FluentConstraints/FluentConstraintSet.swift
|
mit
|
1
|
//
// FluentConstraintSet.swift
// FluentConstraints
//
// Created by Steve Madsen on 6/26/15.
// Copyright (c) 2015 Northwoods Consulting Partners. All rights reserved.
//
import Foundation
open class FluentConstraintSet {
var firstView: UIView
var constraints: [FluentConstraint] = []
public init(_ view: UIView) {
self.firstView = view
}
open func build() -> [NSLayoutConstraint] {
return constraints.map { $0.build() }
}
open func activate() -> [NSLayoutConstraint] {
let constraints = build()
NSLayoutConstraint.activate(constraints)
return constraints
}
// MARK: relationship to view
open var inSuperview: FluentConstraintSet {
precondition(self.firstView.superview != nil, "View does not have a superview")
self.constraints.forEach { $0.secondView = self.firstView.superview! }
return self
}
open func onView(_ view: UIView) -> FluentConstraintSet {
self.constraints.forEach { $0.secondView = view }
return self
}
open func asView(_ view: UIView) -> FluentConstraintSet {
return onView(view)
}
// MARK: internal helpers
func fluentConstraintForView(_ view: UIView, attribute: NSLayoutConstraint.Attribute, constant: CGFloat = 0, relation: NSLayoutConstraint.Relation = .equal) -> FluentConstraint {
let constraint = FluentConstraint(view)
constraint.firstAttribute = attribute
constraint.relation = relation
constraint.secondAttribute = attribute
constraint.constant = constant
return constraint
}
// MARK: builds collections of fluent constraints
open var centered: FluentConstraintSet {
constraints.append(fluentConstraintForView(self.firstView, attribute: .centerX))
constraints.append(fluentConstraintForView(self.firstView, attribute: .centerY))
return self
}
open var sameSize: FluentConstraintSet {
constraints.append(fluentConstraintForView(self.firstView, attribute: .width))
constraints.append(fluentConstraintForView(self.firstView, attribute: .height))
return self
}
open func inset(_ insets: UIEdgeInsets) -> FluentConstraintSet {
constraints.append(fluentConstraintForView(self.firstView, attribute: .left, constant: insets.left))
constraints.append(fluentConstraintForView(self.firstView, attribute: .right, constant: -insets.right))
constraints.append(fluentConstraintForView(self.firstView, attribute: .top, constant: insets.top))
constraints.append(fluentConstraintForView(self.firstView, attribute: .bottom, constant: -insets.bottom))
return self
}
open func inset(_ constant: CGFloat) -> FluentConstraintSet {
return inset(UIEdgeInsets(top: constant, left: constant, bottom: constant, right: constant))
}
open func insetAtLeast(_ insets: UIEdgeInsets) -> FluentConstraintSet {
constraints.append(fluentConstraintForView(self.firstView, attribute: .left, constant: insets.left, relation: .greaterThanOrEqual))
constraints.append(fluentConstraintForView(self.firstView, attribute: .right, constant: -insets.right, relation: .lessThanOrEqual))
constraints.append(fluentConstraintForView(self.firstView, attribute: .top, constant: insets.top, relation: .greaterThanOrEqual))
constraints.append(fluentConstraintForView(self.firstView, attribute: .bottom, constant: -insets.bottom, relation: .lessThanOrEqual))
return self
}
open func insetAtLeast(_ constant: CGFloat) -> FluentConstraintSet {
return insetAtLeast(UIEdgeInsets(top: constant, left: constant, bottom: constant, right: constant))
}
}
|
4e57659e8d9902e1b044430721e7e063
| 37.639175 | 182 | 0.705977 | false | false | false | false |
CodaFi/swift
|
refs/heads/main
|
test/Constraints/gather_all_adjacencies.swift
|
apache-2.0
|
47
|
// RUN: %target-swift-frontend -typecheck %s
// SR-5120 / rdar://problem/32618740
protocol InitCollection: Collection {
init(_ array: [Iterator.Element])
}
protocol InitAny {
init()
}
extension Array: InitCollection {
init(_ array: [Iterator.Element]) {
self = array
}
}
extension String: InitAny {
init() {
self = "bar"
}
}
class Foo {
func foo<T: InitCollection, U: InitAny>(of type: U.Type) -> T
where T.Iterator.Element == U
{
return T.init([U.init()])
}
func foo<T: InitCollection, U: InitAny>(of type: U.Type) -> T?
where T.Iterator.Element == U
{
return T.init([U.init()])
}
}
let _: [String] = Foo().foo(of: String.self)
|
236f0564cdbbfa9d67aee1f58262f325
| 16.894737 | 64 | 0.619118 | false | false | false | false |
Rochester-Ting/DouyuTVDemo
|
refs/heads/master
|
RRDouyuTV/RRDouyuTV/Classes/Tools(工具)/Common.swift
|
mit
|
1
|
//
// Common.swift
// RRDouyuTV
//
// Created by 丁瑞瑞 on 11/10/16.
// Copyright © 2016年 Rochester. All rights reserved.
//
import Foundation
import UIKit
let kStatusBarH : CGFloat = 20
let kNavigationH : CGFloat = 44
let kTitleViewH : CGFloat = 40
let kTabBarH : CGFloat = 44
let kScreenW : CGFloat = UIScreen.main.bounds.size.width
let kScreenH : CGFloat = UIScreen.main.bounds.size.height
let kClycleH : CGFloat = 150
let kGameViewH : CGFloat = 80
|
f2575afe6db437e8fac255d6f0a6a675
| 21.8 | 57 | 0.725877 | false | false | false | false |
daaavid/TIY-Assignments
|
refs/heads/master
|
37--Venue-Menu/Venue-Menu/Venue-Menu/SearchTableViewController.swift
|
cc0-1.0
|
1
|
//
// SearchTableViewController.swift
// Venue-Menu
//
// Created by david on 11/26/15.
// Copyright © 2015 The Iron Yard. All rights reserved.
//
import UIKit
import QuartzCore
import CoreData
protocol APIControllerProtocol
{
func venuesWereFound(venues: [NSDictionary])
}
class SearchTableViewController: UITableViewController, APIControllerProtocol, UISearchBarDelegate
{
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var segmentedControl: UISegmentedControl!
var searchResults = [NSManagedObject]()
var location: Location!
let locationManager = LocationManager()
var apiController: APIController!
override func viewDidLoad()
{
super.viewDidLoad()
segmentedControl.hidden = true
searchBar.delegate = self
location = USER_LOCATION
// locationManager.delegate = self
// locationManager.configureLocationManager()
apiController = APIController(delegate: self)
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return searchResults.count
}
func locationWasFound(location: Location)
{
self.location = location
}
@IBAction func segmentedControlValueChanged(sender: UISegmentedControl)
{
search()
}
func searchBarSearchButtonClicked(searchBar: UISearchBar)
{
search()
}
func searchBarCancelButtonClicked(searchBar: UISearchBar)
{
searchBar.resignFirstResponder()
}
func search()
{
if let _ = location
{
print("searching")
print(location)
if let term = searchBar.text
{
switch segmentedControl.selectedSegmentIndex
{
case 0: apiController.search(term, location: location, searchOption: "explore")
case 1: apiController.search(term, location: location, searchOption: "search")
default: print("segmentedControl unknown segmentIndex")
}
}
searchBar.resignFirstResponder()
}
}
func venuesWereFound(venues: [NSDictionary])
{
print(venues.count)
dispatch_async(dispatch_get_main_queue(), {
for eachVenueDict in venues
{
if let venue = Venue.venueWithJSON(eachVenueDict)
{
self.searchResults.append(venue)
}
}
self.apiController.cancelSearch()
self.tableView.reloadData()
})
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("SearchCell", forIndexPath: indexPath) as! VenueCell
let venue = searchResults[indexPath.row]
cell.venueLabel.text = venue.valueForKey("name") as? String
cell.typeLabel.text = venue.valueForKey("type") as? String
cell.addressLabel.text = venue.valueForKey("address") as? String
if let imageURL = venue.valueForKey("icon") as? String
{
let imageView = makeCellImage(imageURL)
cell.addSubview(imageView)
}
return cell
}
func makeCellImage(iconURL: String) -> UIImageView
{
let imageView = UIImageView()
imageView.frame = CGRect(x: 8, y: 8, width: 64, height: 64)
imageView.downloadedFrom(iconURL, contentMode: .ScaleToFill)
imageView.round()
imageView.backgroundColor = UIColor(hue:0.625, saturation:0.8, brightness:0.886, alpha:1)
return imageView
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
let mainVC = navigationController?.viewControllers[0] as! MainViewController
let detailVC = storyboard?.instantiateViewControllerWithIdentifier("detailVC") as! DetailViewController
let chosenVenue = searchResults[indexPath.row]
detailVC.venue = chosenVenue
detailVC.location = USER_LOCATION
detailVC.delegate = mainVC
navigationController?.pushViewController(detailVC, animated: true)
}
// override func viewDidDisappear(animated: Bool)
// {
// let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
// for venue in searchResults
// {
// managedObjectContext.deleteObject(venue)
// }
// }
}
|
a10c267a2025bf3645e8ff34411f2aaa
| 29.402516 | 118 | 0.628051 | false | false | false | false |
AdaptiveMe/adaptive-arp-api-lib-darwin
|
refs/heads/master
|
Pod/Classes/Sources.Api/AppResourceData.swift
|
apache-2.0
|
1
|
/**
--| 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:carlos@adaptive.me>
Contributors:
* Ferran Vila Conesa
<http://github.com/fnva>
<http://twitter.com/ferran_vila>
<mailto:ferran.vila.conesa@gmail.com>
* See source code files for contributors.
Release:
* @version v2.2.15
-------------------------------------------| aut inveniam viam aut faciam |--------------------------------------------
*/
import Foundation
/**
This class represents a resource provided by the platform from the application's secure payload.
@author Carlos Lozano Diez
@since v2.1.3
@version 1.0
*/
public class AppResourceData {
/**
Marker to indicate whether the resource is cooked in some way (compressed, encrypted, etc.) If true, the
implementation must uncompress/unencrypt following the cookedType recipe specified by the payload.
*/
var cooked : Bool?
/**
This is the length of the payload after cooking. In general, this length indicates the amount
of space saved with regard to the rawLength of the payload.
*/
var cookedLength : Int64?
/**
If the data is cooked, this field should contain the recipe to return the cooked data to its original
uncompressed/unencrypted/etc format.
*/
var cookedType : String?
/**
The payload data of the resource in ready to consume format.
*/
var data : [UInt8]?
/**
The id or path identifier of the resource.
*/
var id : String?
/**
The raw length of the payload before any cooking occurred. This is equivalent to the size of the resource
after uncompressing and unencrypting.
*/
var rawLength : Int64?
/**
The raw type of the payload - this is equivalent to the mimetype of the content.
*/
var rawType : String?
/**
Default constructor.
@since v2.1.3
*/
public init() {
}
/**
Convenience constructor.
@param id The id or path of the resource retrieved.
@param data The payload data of the resource (uncooked).
@param rawType The raw type/mimetype of the resource.
@param rawLength The raw length/original length in bytes of the resource.
@param cooked True if the resource is cooked.
@param cookedType Type of recipe used for cooking.
@param cookedLength The cooked length in bytes of the resource.
@since v2.1.3
*/
public init(id: String, data: [UInt8], rawType: String, rawLength: Int64, cooked: Bool, cookedType: String, cookedLength: Int64) {
self.id = id
self.data = data
self.rawType = rawType
self.rawLength = rawLength
self.cooked = cooked
self.cookedType = cookedType
self.cookedLength = cookedLength
}
/**
Attribute to denote whether the payload of the resource is cooked.
@return True if the resource is cooked, false otherwise.
@since v2.1.3
*/
public func getCooked() -> Bool? {
return self.cooked
}
/**
Attribute to denote whether the payload of the resource is cooked.
@param cooked True if the resource is cooked, false otherwise.
@since v2.1.3
*/
public func setCooked(cooked: Bool) {
self.cooked = cooked
}
/**
The length in bytes of the payload after cooking.
@return Length in bytes of cooked payload.
@since v2.1.3
*/
public func getCookedLength() -> Int64? {
return self.cookedLength
}
/**
The length in bytes of the payload after cooking.
@param cookedLength Length in bytes of cooked payload.
@since v2.1.3
*/
public func setCookedLength(cookedLength: Int64) {
self.cookedLength = cookedLength
}
/**
If the resource is cooked, this will return the recipe used during cooking.
@return The cooking recipe to reverse the cooking process.
@since v2.1.3
*/
public func getCookedType() -> String? {
return self.cookedType
}
/**
If the resource is cooked, the type of recipe used during cooking.
@param cookedType The cooking recipe used during cooking.
@since v2.1.3
*/
public func setCookedType(cookedType: String) {
self.cookedType = cookedType
}
/**
Returns the payload of the resource.
@return Binary payload of the resource.
@since v2.1.3
*/
public func getData() -> [UInt8]? {
return self.data
}
/**
Sets the payload of the resource.
@param data Binary payload of the resource.
@since v2.1.3
*/
public func setData(data: [UInt8]) {
self.data = data
}
/**
Gets The id or path identifier of the resource.
@return id The id or path identifier of the resource.
*/
public func getId() -> String? {
return self.id
}
/**
Sets the id or path of the resource.
@param id The id or path of the resource.
@since v2.1.3
*/
public func setId(id: String) {
self.id = id
}
/**
Gets the resource payload's original length.
@return Original length of the resource in bytes before cooking.
@since v2.1.3
*/
public func getRawLength() -> Int64? {
return self.rawLength
}
/**
Sets the resource payload's original length.
@param rawLength Original length of the resource in bytes before cooking.
@since v2.1.3
*/
public func setRawLength(rawLength: Int64) {
self.rawLength = rawLength
}
/**
Gets the resource's raw type or mimetype.
@return Resource's type or mimetype.
@since v2.1.3
*/
public func getRawType() -> String? {
return self.rawType
}
/**
Sets the resource's raw type or mimetype.
@param rawType Resource's type or mimetype.
@since v2.1.3
*/
public func setRawType(rawType: String) {
self.rawType = rawType
}
/**
JSON Serialization and deserialization support.
*/
public struct Serializer {
public static func fromJSON(json : String) -> AppResourceData {
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) -> AppResourceData {
let resultObject : AppResourceData = AppResourceData()
if let value : AnyObject = dict.objectForKey("cooked") {
if "\(value)" as NSString != "<null>" {
resultObject.cooked = (value as! Bool)
}
}
if let value : AnyObject = dict.objectForKey("cookedLength") {
if "\(value)" as NSString != "<null>" {
let numValue = value as? NSNumber
resultObject.cookedLength = numValue?.longLongValue
}
}
if let value : AnyObject = dict.objectForKey("cookedType") {
if "\(value)" as NSString != "<null>" {
resultObject.cookedType = (value as! String)
}
}
if let value : AnyObject = dict.objectForKey("data") {
if "\(value)" as NSString != "<null>" {
var data : [UInt8] = [UInt8](count: (value as! NSArray).count, repeatedValue: 0)
let dataData : NSData = (value as! NSData)
dataData.getBytes(&data, length: (value as! NSArray).count * sizeof(UInt8))
resultObject.data = data
}
}
if let value : AnyObject = dict.objectForKey("id") {
if "\(value)" as NSString != "<null>" {
resultObject.id = (value as! String)
}
}
if let value : AnyObject = dict.objectForKey("rawLength") {
if "\(value)" as NSString != "<null>" {
let numValue = value as? NSNumber
resultObject.rawLength = numValue?.longLongValue
}
}
if let value : AnyObject = dict.objectForKey("rawType") {
if "\(value)" as NSString != "<null>" {
resultObject.rawType = (value as! String)
}
}
return resultObject
}
public static func toJSON(object: AppResourceData) -> String {
let jsonString : NSMutableString = NSMutableString()
// Start Object to JSON
jsonString.appendString("{ ")
// Fields.
object.cooked != nil ? jsonString.appendString("\"cooked\": \(object.cooked!), ") : jsonString.appendString("\"cooked\": null, ")
object.cookedLength != nil ? jsonString.appendString("\"cookedLength\": \(object.cookedLength!), ") : jsonString.appendString("\"cookedLength\": null, ")
object.cookedType != nil ? jsonString.appendString("\"cookedType\": \"\(JSONUtil.escapeString(object.cookedType!))\", ") : jsonString.appendString("\"cookedType\": null, ")
if (object.data != nil) {
// Start array of objects.
jsonString.appendString("\"data\": [")
for var i = 0; i < object.data!.count; i++ {
jsonString.appendString("\(object.data![i])")
if (i < object.data!.count-1) {
jsonString.appendString(", ");
}
}
// End array of objects.
jsonString.appendString("], ");
} else {
jsonString.appendString("\"data\": null, ")
}
object.id != nil ? jsonString.appendString("\"id\": \"\(JSONUtil.escapeString(object.id!))\", ") : jsonString.appendString("\"id\": null, ")
object.rawLength != nil ? jsonString.appendString("\"rawLength\": \(object.rawLength!), ") : jsonString.appendString("\"rawLength\": null, ")
object.rawType != nil ? jsonString.appendString("\"rawType\": \"\(JSONUtil.escapeString(object.rawType!))\"") : jsonString.appendString("\"rawType\": null")
// End Object to JSON
jsonString.appendString(" }")
return jsonString as String
}
}
}
/**
------------------------------------| Engineered with ♥ in Barcelona, Catalonia |--------------------------------------
*/
|
cb454e8c6f7d6a5ad9241430020e2982
| 31.988571 | 184 | 0.573705 | false | false | false | false |
yeziahehe/Gank
|
refs/heads/master
|
Pods/LeanCloud/Sources/Storage/DataType/Number.swift
|
gpl-3.0
|
1
|
//
// LCNumber.swift
// LeanCloud
//
// Created by Tang Tianyong on 2/27/16.
// Copyright © 2016 LeanCloud. All rights reserved.
//
import Foundation
/**
LeanCloud number type.
It is a wrapper of `Swift.Double` type, used to store a number value.
*/
public final class LCNumber: NSObject, LCValue, LCValueExtension, ExpressibleByFloatLiteral, ExpressibleByIntegerLiteral {
public private(set) var value: Double = 0
public override init() {
super.init()
}
public convenience init(_ value: Double) {
self.init()
self.value = value
}
public convenience required init(floatLiteral value: FloatLiteralType) {
self.init(value)
}
public convenience required init(integerLiteral value: IntegerLiteralType) {
self.init(Double(value))
}
public required init?(coder aDecoder: NSCoder) {
value = aDecoder.decodeDouble(forKey: "value")
}
public func encode(with aCoder: NSCoder) {
aCoder.encode(value, forKey: "value")
}
public func copy(with zone: NSZone?) -> Any {
return LCNumber(value)
}
public override func isEqual(_ object: Any?) -> Bool {
if let object = object as? LCNumber {
return object === self || object.value == value
} else {
return false
}
}
public var jsonValue: Any {
return value
}
func formattedJSONString(indentLevel: Int, numberOfSpacesForOneIndentLevel: Int = 4) -> String {
return String(format: "%g", value)
}
public var jsonString: String {
return formattedJSONString(indentLevel: 0)
}
public var rawValue: LCValueConvertible {
return value
}
var lconValue: Any? {
return jsonValue
}
static func instance() -> LCValue {
return LCNumber()
}
func forEachChild(_ body: (_ child: LCValue) throws -> Void) rethrows {
/* Nothing to do. */
}
func add(_ other: LCValue) throws -> LCValue {
let result = LCNumber(value)
result.addInPlace((other as! LCNumber).value)
return result
}
func addInPlace(_ amount: Double) {
value += amount
}
func concatenate(_ other: LCValue, unique: Bool) throws -> LCValue {
throw LCError(code: .invalidType, reason: "Object cannot be concatenated.")
}
func differ(_ other: LCValue) throws -> LCValue {
throw LCError(code: .invalidType, reason: "Object cannot be differed.")
}
}
|
e99121ed4a6681909962fcdc39de1fee
| 23.436893 | 122 | 0.62058 | false | false | false | false |
shahmishal/swift
|
refs/heads/master
|
test/Constraints/function_builder.swift
|
apache-2.0
|
1
|
// RUN: %target-run-simple-swift | %FileCheck %s
// REQUIRES: executable_test
enum Either<T,U> {
case first(T)
case second(U)
}
@_functionBuilder
struct TupleBuilder {
static func buildBlock<T1, T2>(_ t1: T1, _ t2: T2) -> (T1, T2) {
return (t1, t2)
}
static func buildBlock<T1, T2, T3>(_ t1: T1, _ t2: T2, _ t3: T3)
-> (T1, T2, T3) {
return (t1, t2, t3)
}
static func buildBlock<T1, T2, T3, T4>(_ t1: T1, _ t2: T2, _ t3: T3, _ t4: T4)
-> (T1, T2, T3, T4) {
return (t1, t2, t3, t4)
}
static func buildBlock<T1, T2, T3, T4, T5>(
_ t1: T1, _ t2: T2, _ t3: T3, _ t4: T4, _ t5: T5
) -> (T1, T2, T3, T4, T5) {
return (t1, t2, t3, t4, t5)
}
static func buildDo<T>(_ value: T) -> T { return value }
static func buildIf<T>(_ value: T?) -> T? { return value }
static func buildEither<T,U>(first value: T) -> Either<T,U> {
return .first(value)
}
static func buildEither<T,U>(second value: U) -> Either<T,U> {
return .second(value)
}
}
func tuplify<T>(_ cond: Bool, @TupleBuilder body: (Bool) -> T) {
print(body(cond))
}
// CHECK: (17, 3.14159, "Hello, DSL", (["nested", "do"], 6), Optional((2.71828, ["if", "stmt"])))
let name = "dsl"
tuplify(true) {
17
3.14159
"Hello, \(name.map { $0.uppercased() }.joined())"
do {
["nested", "do"]
1 + 2 + 3
}
if $0 {
2.71828
["if", "stmt"]
}
}
// CHECK: ("Empty optional", nil)
tuplify(false) {
"Empty optional"
if $0 {
2.71828
["if", "stmt"]
}
}
// CHECK: ("chain0", main.Either<(Swift.String, Swift.Double), (Swift.Double, Swift.String)>.second(2.8, "capable"))
tuplify(false) {
"chain0"
if $0 {
"marginal"
2.9
} else {
2.8
"capable"
}
}
// CHECK: ("chain1", nil)
tuplify(false) {
"chain1"
if $0 {
"marginal"
2.9
} else if $0 {
2.8
"capable"
}
}
// CHECK: ("chain2", Optional(main.Either<(Swift.String, Swift.Double), (Swift.Double, Swift.String)>.first("marginal", 2.9)))
tuplify(true) {
"chain2"
if $0 {
"marginal"
2.9
} else if $0 {
2.8
"capable"
}
}
// CHECK: ("chain3", main.Either<main.Either<(Swift.String, Swift.Double), (Swift.Double, Swift.String)>, main.Either<(Swift.Double, Swift.Double), (Swift.String, Swift.String)>>.first(main.Either<(Swift.String, Swift.Double), (Swift.Double, Swift.String)>.first("marginal", 2.9)))
tuplify(true) {
"chain3"
if $0 {
"marginal"
2.9
} else if $0 {
2.8
"capable"
} else if $0 {
2.8
1.0
} else {
"wild"
"broken"
}
}
// CHECK: ("chain4", main.Either<main.Either<main.Either<(Swift.String, Swift.Int), (Swift.String, Swift.Int)>, main.Either<(Swift.String, Swift.Int), (Swift.String, Swift.Int)>>, main.Either<main.Either<(Swift.String, Swift.Int), (Swift.String, Swift.Int)>, (Swift.String, Swift.Int)>>.first
tuplify(true) {
"chain4"
if $0 {
"0"
0
} else if $0 {
"1"
1
} else if $0 {
"2"
2
} else if $0 {
"3"
3
} else if $0 {
"4"
4
} else if $0 {
"5"
5
} else {
"6"
6
}
}
// rdar://50710698
// CHECK: ("chain5", 8, 9)
tuplify(true) {
"chain5"
#if false
6
$0
#else
8
9
#endif
}
// CHECK: ("getterBuilder", 0, 4, 12)
@TupleBuilder
var globalBuilder: (String, Int, Int, Int) {
"getterBuilder"
0
4
12
}
print(globalBuilder)
// CHECK: ("funcBuilder", 13, 45.0)
@TupleBuilder
func funcBuilder(d: Double) -> (String, Int, Double) {
"funcBuilder"
13
d
}
print(funcBuilder(d: 45))
struct MemberBuilders {
@TupleBuilder
func methodBuilder(_ i: Int) -> (String, Int) {
"methodBuilder"
i
}
@TupleBuilder
static func staticMethodBuilder(_ i: Int) -> (String, Int) {
"staticMethodBuilder"
i + 14
}
@TupleBuilder
var propertyBuilder: (String, Int) {
"propertyBuilder"
12
}
}
// CHECK: ("staticMethodBuilder", 27)
print(MemberBuilders.staticMethodBuilder(13))
let mbuilders = MemberBuilders()
// CHECK: ("methodBuilder", 13)
print(mbuilders.methodBuilder(13))
// CHECK: ("propertyBuilder", 12)
print(mbuilders.propertyBuilder)
struct Tagged<Tag, Entity> {
let tag: Tag
let entity: Entity
}
protocol Taggable {
}
extension Taggable {
func tag<Tag>(_ tag: Tag) -> Tagged<Tag, Self> {
return Tagged(tag: tag, entity: self)
}
}
extension Int: Taggable { }
extension String: Taggable { }
extension Double: Taggable { }
@_functionBuilder
struct TaggedBuilder<Tag> {
static func buildBlock() -> () { }
static func buildBlock<T1>(_ t1: Tagged<Tag, T1>) -> Tagged<Tag, T1> {
return t1
}
static func buildBlock<T1, T2>(_ t1: Tagged<Tag, T1>, _ t2: Tagged<Tag, T2>) -> (Tagged<Tag, T1>, Tagged<Tag, T2>) {
return (t1, t2)
}
static func buildBlock<T1, T2, T3>(_ t1: Tagged<Tag, T1>, _ t2: Tagged<Tag, T2>, _ t3: Tagged<Tag, T3>)
-> (Tagged<Tag, T1>, Tagged<Tag, T2>, Tagged<Tag, T3>) {
return (t1, t2, t3)
}
static func buildBlock<T1, T2, T3, T4>(_ t1: Tagged<Tag, T1>, _ t2: Tagged<Tag, T2>, _ t3: Tagged<Tag, T3>, _ t4: Tagged<Tag, T4>)
-> (Tagged<Tag, T1>, Tagged<Tag, T2>, Tagged<Tag, T3>, Tagged<Tag, T4>) {
return (t1, t2, t3, t4)
}
static func buildBlock<T1, T2, T3, T4, T5>(
_ t1: Tagged<Tag, T1>, _ t2: Tagged<Tag, T2>, _ t3: Tagged<Tag, T3>, _ t4: Tagged<Tag, T4>, _ t5: Tagged<Tag, T5>
) -> (Tagged<Tag, T1>, Tagged<Tag, T2>, Tagged<Tag, T3>, Tagged<Tag, T4>, Tagged<Tag, T5>) {
return (t1, t2, t3, t4, t5)
}
static func buildIf<T>(_ value: Tagged<Tag, T>?) -> Tagged<Tag, T>? { return value }
}
enum Color {
case red, green, blue
}
func acceptColorTagged<Result>(@TaggedBuilder<Color> body: () -> Result) {
print(body())
}
struct TagAccepter<Tag> {
static func acceptTagged<Result>(@TaggedBuilder<Tag> body: () -> Result) {
print(body())
}
}
func testAcceptColorTagged(b: Bool, i: Int, s: String, d: Double) {
// CHECK: Tagged<
acceptColorTagged {
i.tag(.red)
s.tag(.green)
d.tag(.blue)
}
// CHECK: Tagged<
TagAccepter<Color>.acceptTagged {
i.tag(.red)
s.tag(.green)
d.tag(.blue)
}
// CHECK: Tagged<
TagAccepter<Color>.acceptTagged { () -> Tagged<Color, Int> in
if b {
return i.tag(Color.green)
} else {
return i.tag(Color.blue)
}
}
}
testAcceptColorTagged(b: true, i: 17, s: "Hello", d: 3.14159)
// rdar://53325810
// Test that we don't have problems with expression pre-checking when
// type-checking an overloaded function-builder call. In particular,
// we need to make sure that expressions in the closure are pre-checked
// before we build constraints for them. Note that top-level expressions
// that need to be rewritten by expression prechecking (such as the operator
// sequences in the boolean conditions and statements below) won't be
// rewritten in the original closure body if we just precheck the
// expressions produced by the function-builder transformation.
struct ForEach1<Data : RandomAccessCollection, Content> {
var data: Data
var content: (Data.Element) -> Content
func show() {
print(content(data.first!))
print(content(data.last!))
}
}
extension ForEach1 where Data.Element: StringProtocol {
// Checking this overload shouldn't trigger inappropriate caching that
// affects checking the next overload.
init(_ data: Data,
@TupleBuilder content: @escaping (Data.Element) -> Content) {
self.init(data: data, content: content)
}
}
extension ForEach1 where Data == Range<Int> {
// This is the overload we actually want.
init(_ data: Data,
@TupleBuilder content: @escaping (Int) -> Content) {
self.init(data: data, content: content)
}
}
let testForEach1 = ForEach1(-10 ..< 10) { i in
"testForEach1"
if i < 0 {
"begin"
i < -5
} else {
i > 5
"end"
}
}
testForEach1.show()
// CHECK: ("testForEach1", main.Either<(Swift.String, Swift.Bool), (Swift.Bool, Swift.String)>.first("begin", true))
// CHECK: ("testForEach1", main.Either<(Swift.String, Swift.Bool), (Swift.Bool, Swift.String)>.second(true, "end"))
|
aedae8ea9a6bf005fbe181a7cf655a04
| 21.880682 | 292 | 0.606407 | false | false | false | false |
halo/LinkLiar
|
refs/heads/master
|
LinkLiar/Classes/MACPrefixQuestion.swift
|
mit
|
1
|
/*
* Copyright (C) 2012-2021 halo https://io.github.com/halo/LinkLiar
*
* 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 Cocoa
class MACPrefixQuestion {
let title: String
let description: String
let alert = NSAlert()
let textField: CopyPastableNSTextField = {
let field = CopyPastableNSTextField(frame: NSMakeRect(0, 0, 150, 24))
field.formatter = MACPrefixFormatter()
field.stringValue = "aa:bb:cc"
field.placeholderString = "aa:bb:cc"
return field
}()
init(title: String, description: String) {
self.title = title
self.description = description
alert.messageText = title
alert.informativeText = description
alert.addButton(withTitle: "OK")
alert.addButton(withTitle: "Cancel")
alert.accessoryView = textField
}
func ask() -> String? {
let button = alert.runModal()
if (button == NSApplication.ModalResponse.alertFirstButtonReturn) {
textField.validateEditing()
return textField.stringValue
} else {
return nil
}
}
}
|
9e1c71542e1f04e3fc8a73d75042bea0
| 35.535714 | 133 | 0.73216 | false | false | false | false |
codepgq/WeiBoDemo
|
refs/heads/master
|
PQWeiboDemo/PQWeiboDemo/classes/Index 首页/model/PQUserInfoModel.swift
|
mit
|
1
|
//
// PQUserInfoModel.swift
// PQWeiboDemo
//
// Created by ios on 16/10/8.
// Copyright © 2016年 ios. All rights reserved.
//
import UIKit
class PQUserInfoModel: NSObject {
/// 用户ID
var id: Int = 0
/// 用户昵称
var name :String?
/// 用户头像地址
var profile_image_url : String?
{
didSet{
if let urlStr = profile_image_url
{
imageURL = NSURL(string: urlStr)
}
}
}
/// 用户头像地址
var imageURL : NSURL?
/// 用户是否认证
var verified :Bool = false
/// 用户认证类型, -1 没有认证 0,认证用户 2 3 5企业认证 220 达人
var verified_type : Int = -1{
didSet{
switch verified_type {
case 0:
verified_image = UIImage(named: "avatar_vip")
case 2,3,5:
verified_image = UIImage(named: "avatar_enterprise_vip")
case 220:
verified_image = UIImage(named: "avatar_grassroot")
default:
verified_image = nil
}
}
}
/// 认证头像
var verified_image : UIImage?
/// 有没有钻石💎
var followers_count : Int = 0{
didSet{
if followers_count >= 1000000{
isHiddenDiamond = false
}
}
}
var isHiddenDiamond :Bool = true
var mbrank : Int = 0{
didSet{
if mbrank > 0 && mbrank < 7 {
mbrankImage = UIImage(named: "common_icon_membership_level\(mbrank)")
}
}
}
var mbrankImage :UIImage?
init(dict : [String : AnyObject]) {
super.init()
setValuesForKeys(dict)
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {
}
}
|
33062cd39cf1d7c03fe924f89976244d
| 20.876543 | 85 | 0.485892 | false | false | false | false |
eurofurence/ef-app_ios
|
refs/heads/release/4.0.0
|
Packages/EurofurenceKit/Sources/XCTAsyncAssertions/XCTAssertEventuallyThrowsSpecificError.swift
|
mit
|
1
|
import XCTest
public func XCTAssertThrowsSpecificError<E, T>(
_ expected: E,
_ block: @autoclosure () throws -> T,
file: StaticString = #file,
line: UInt = #line
) where E: Error & Equatable {
do {
_ = try block()
XCTFail("Expected to throw an error.", file: file, line: line)
} catch let error as E {
XCTAssertEqual(expected, error, file: file, line: line)
} catch {
XCTFail("Unexpected error thrown: \(error)", file: file, line: line)
}
}
public func XCTAssertEventuallyThrowsSpecificError<E>(
_ expected: E,
_ block: () async throws -> Void,
file: StaticString = #file,
line: UInt = #line
) async where E: Error & Equatable {
do {
try await block()
XCTFail("Expected to throw an error.", file: file, line: line)
} catch let error as E {
XCTAssertEqual(expected, error, file: file, line: line)
} catch {
XCTFail("Unexpected error thrown: \(error)", file: file, line: line)
}
}
public func XCTAssertEventuallyThrowsError(
_ block: () async throws -> Void,
file: StaticString = #file,
line: UInt = #line
) async {
do {
try await block()
XCTFail("Expected to throw an error.", file: file, line: line)
} catch {
// 👍
}
}
public func XCTAssertEventuallyNoThrows(
_ block: () async throws -> Void,
file: StaticString = #file,
line: UInt = #line
) async {
do {
try await block()
// 👍
} catch {
XCTFail("Unexpected error raised: \(error)", file: file, line: line)
}
}
|
4c02a8816021d18cd45936688b1e4218
| 25.949153 | 76 | 0.589308 | false | false | false | false |
chrislzm/TimeAnalytics
|
refs/heads/master
|
Time Analytics/TAActivityTableViewController.swift
|
mit
|
1
|
//
// TAActivityTableViewController.swift
// Time Analytics
//
// Displays all Time Analytics Activity data (TAActivitySegment managed objects) and allows user to tap into a detail view for each one.
//
// Created by Chris Leung on 5/23/17.
// Copyright © 2017 Chris Leung. All rights reserved.
//
import CoreData
import UIKit
class TAActivityTableViewController: TATableViewController {
@IBOutlet weak var activityTableView: UITableView!
let viewTitle = "Activities"
// MARK: Lifecycle
override func viewDidLoad() {
// Set tableview for superclass before calling super method so that it can setup the table's properties (style, etc.)
super.tableView = activityTableView
super.viewDidLoad()
navigationItem.title = viewTitle
// Get the context
let delegate = UIApplication.shared.delegate as! AppDelegate
let context = delegate.stack.context
// Create a fetchrequest
let fr = NSFetchRequest<NSFetchRequestResult>(entityName: "TAActivitySegment")
fr.sortDescriptors = [NSSortDescriptor(key: "startTime", ascending: false)]
// Create the FetchedResultsController
fetchedResultsController = NSFetchedResultsController(fetchRequest: fr, managedObjectContext: context, sectionNameKeyPath: "daySectionIdentifier", cacheName: nil)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// If no data, let the user know
if fetchedResultsController?.sections?.count == 0 {
createTableEmptyMessageIn(tableView, "No activities recorded yet.\n\nPlease ensure that your sleep and\nworkout activities are being written\nto Apple Health data and that\nTime Analytics is authorized to\nread your Health data.")
} else {
removeTableEmptyMessageFrom(tableView)
// Deselect row if we selected one that caused a segue
if let selectedRowIndexPath = activityTableView.indexPathForSelectedRow {
activityTableView.deselectRow(at: selectedRowIndexPath, animated: true)
}
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let activity = fetchedResultsController!.object(at: indexPath) as! TAActivitySegment
let cell = tableView.dequeueReusableCell(withIdentifier: "TAActivityTableViewCell", for: indexPath) as! TAActivityTableViewCell
// Get label values
let start = activity.startTime! as Date
let end = activity.endTime! as Date
// Set label values
cell.timeLabel.text = generateTimeInOutStringWithDate(start, end)
cell.lengthLabel.text = generateLengthString(start, end)
cell.nameLabel.text = "\(activity.type!): \(activity.name!)"
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let activity = fetchedResultsController!.object(at: indexPath) as! TAActivitySegment
showActivityDetailViewController(activity)
}
}
|
126f4f9d2137176374fa707e02c64847
| 39.858974 | 242 | 0.68748 | false | false | false | false |
Pacific3/PFoundation
|
refs/heads/master
|
PFoundation/Operations/Conditions/ExclusivityController.swift
|
mit
|
1
|
//
// RBExclusivityController.swift
// reserbus-ios
//
// Created by Swanros on 8/14/15.
// Copyright © 2015 Reserbus S. de R.L. de C.V. All rights reserved.
//
private let ExclusivityControllerSerialQueueLabel = "Operations.ExclusivityController"
class RBExclusivityController {
static let sharedInstance = RBExclusivityController()
private let serialQueue = dispatch_queue_create(ExclusivityControllerSerialQueueLabel, DISPATCH_QUEUE_SERIAL)
private var operations: [String: [Operation]] = [:]
private init() {}
func addOperation(operation: Operation, categories: [String]) {
dispatch_sync(serialQueue) {
for category in categories {
self.noqueue_addOperation(operation, category: category)
}
}
}
func removeOperation(operation: Operation, categories: [String]) {
dispatch_async(serialQueue) {
for category in categories {
self.noqueue_removeOperation(operation, category: category)
}
}
}
private func noqueue_addOperation(operation: Operation, category: String) {
var operationsWithThisCategory = operations[category] ?? []
if let last = operationsWithThisCategory.last {
operation.addDependency(last)
}
operationsWithThisCategory.append(operation)
operations[category] = operationsWithThisCategory
}
private func noqueue_removeOperation(operation: Operation, category: String) {
let matchingOperations = operations[category]
if var operationsWithThisCategory = matchingOperations,
let index = operationsWithThisCategory.indexOf(operation) {
operationsWithThisCategory.removeAtIndex(index)
operations[category] = operationsWithThisCategory
}
}
}
|
4dd7d3e041225e1a31d07cefd6cb5b52
| 33.4 | 113 | 0.659619 | false | false | false | false |
yellowChao/beverly
|
refs/heads/master
|
DTMaster/Pods/Alamofire/Source/MultipartFormData.swift
|
mit
|
1
|
//
// MultipartFormData.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
#if os(iOS) || os(watchOS) || os(tvOS)
import MobileCoreServices
#elseif os(OSX)
import CoreServices
#endif
/**
Constructs `multipart/form-data` for uploads within an HTTP or HTTPS body. There are currently two ways to encode
multipart form data. The first way is to encode the data directly in memory. This is very efficient, but can lead
to memory issues if the dataset is too large. The second way is designed for larger datasets and will write all the
data to a single file on disk with all the proper boundary segmentation. The second approach MUST be used for
larger datasets such as video content, otherwise your app may run out of memory when trying to encode the dataset.
For more information on `multipart/form-data` in general, please refer to the RFC-2388 and RFC-2045 specs as well
and the w3 form documentation.
- https://www.ietf.org/rfc/rfc2388.txt
- https://www.ietf.org/rfc/rfc2045.txt
- https://www.w3.org/TR/html401/interact/forms.html#h-17.13
*/
public class MultipartFormData {
// MARK: - Helper Types
struct EncodingCharacters {
static let CRLF = "\r\n"
}
struct BoundaryGenerator {
enum BoundaryType {
case Initial, Encapsulated, Final
}
static func randomBoundary() -> String {
return String(format: "alamofire.boundary.%08x%08x", arc4random(), arc4random())
}
static func boundaryData(boundaryType boundaryType: BoundaryType, boundary: String) -> NSData {
let boundaryText: String
switch boundaryType {
case .Initial:
boundaryText = "--\(boundary)\(EncodingCharacters.CRLF)"
case .Encapsulated:
boundaryText = "\(EncodingCharacters.CRLF)--\(boundary)\(EncodingCharacters.CRLF)"
case .Final:
boundaryText = "\(EncodingCharacters.CRLF)--\(boundary)--\(EncodingCharacters.CRLF)"
}
return boundaryText.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
}
}
class BodyPart {
let headers: [String: String]
let bodyStream: NSInputStream
let bodyContentLength: UInt64
var hasInitialBoundary = false
var hasFinalBoundary = false
init(headers: [String: String], bodyStream: NSInputStream, bodyContentLength: UInt64) {
self.headers = headers
self.bodyStream = bodyStream
self.bodyContentLength = bodyContentLength
}
}
// MARK: - Properties
/// The `Content-Type` header value containing the boundary used to generate the `multipart/form-data`.
public var contentType: String { return "multipart/form-data; boundary=\(boundary)" }
/// The content length of all body parts used to generate the `multipart/form-data` not including the boundaries.
public var contentLength: UInt64 { return bodyParts.reduce(0) { $0 + $1.bodyContentLength } }
/// The boundary used to separate the body parts in the encoded form data.
public let boundary: String
private var bodyParts: [BodyPart]
private var bodyPartError: NSError?
private let streamBufferSize: Int
// MARK: - Lifecycle
/**
Creates a multipart form data object.
- returns: The multipart form data object.
*/
public init() {
self.boundary = BoundaryGenerator.randomBoundary()
self.bodyParts = []
/**
* The optimal read/write buffer size in bytes for input and output streams is 1024 (1KB). For more
* information, please refer to the following article:
* - https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Streams/Articles/ReadingInputStreams.html
*/
self.streamBufferSize = 1024
}
// MARK: - Body Parts
/**
Creates a body part from the data and appends it to the multipart form data object.
The body part data will be encoded using the following format:
- `Content-Disposition: form-data; name=#{name}` (HTTP Header)
- Encoded data
- Multipart form boundary
- parameter data: The data to encode into the multipart form data.
- parameter name: The name to associate with the data in the `Content-Disposition` HTTP header.
*/
public func appendBodyPart(data data: NSData, name: String) {
let headers = contentHeaders(name: name)
let stream = NSInputStream(data: data)
let length = UInt64(data.length)
appendBodyPart(stream: stream, length: length, headers: headers)
}
/**
Creates a body part from the data and appends it to the multipart form data object.
The body part data will be encoded using the following format:
- `Content-Disposition: form-data; name=#{name}` (HTTP Header)
- `Content-Type: #{generated mimeType}` (HTTP Header)
- Encoded data
- Multipart form boundary
- parameter data: The data to encode into the multipart form data.
- parameter name: The name to associate with the data in the `Content-Disposition` HTTP header.
- parameter mimeType: The MIME type to associate with the data content type in the `Content-Type` HTTP header.
*/
public func appendBodyPart(data data: NSData, name: String, mimeType: String) {
let headers = contentHeaders(name: name, mimeType: mimeType)
let stream = NSInputStream(data: data)
let length = UInt64(data.length)
appendBodyPart(stream: stream, length: length, headers: headers)
}
/**
Creates a body part from the data and appends it to the multipart form data object.
The body part data will be encoded using the following format:
- `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header)
- `Content-Type: #{mimeType}` (HTTP Header)
- Encoded file data
- Multipart form boundary
- parameter data: The data to encode into the multipart form data.
- parameter name: The name to associate with the data in the `Content-Disposition` HTTP header.
- parameter fileName: The filename to associate with the data in the `Content-Disposition` HTTP header.
- parameter mimeType: The MIME type to associate with the data in the `Content-Type` HTTP header.
*/
public func appendBodyPart(data data: NSData, name: String, fileName: String, mimeType: String) {
let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType)
let stream = NSInputStream(data: data)
let length = UInt64(data.length)
appendBodyPart(stream: stream, length: length, headers: headers)
}
/**
Creates a body part from the file and appends it to the multipart form data object.
The body part data will be encoded using the following format:
- `Content-Disposition: form-data; name=#{name}; filename=#{generated filename}` (HTTP Header)
- `Content-Type: #{generated mimeType}` (HTTP Header)
- Encoded file data
- Multipart form boundary
The filename in the `Content-Disposition` HTTP header is generated from the last path component of the
`fileURL`. The `Content-Type` HTTP header MIME type is generated by mapping the `fileURL` extension to the
system associated MIME type.
- parameter fileURL: The URL of the file whose content will be encoded into the multipart form data.
- parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header.
*/
public func appendBodyPart(fileURL fileURL: NSURL, name: String) {
if let
fileName = fileURL.lastPathComponent,
pathExtension = fileURL.pathExtension {
let mimeType = mimeTypeForPathExtension(pathExtension)
appendBodyPart(fileURL: fileURL, name: name, fileName: fileName, mimeType: mimeType)
} else {
let failureReason = "Failed to extract the fileName of the provided URL: \(fileURL)"
setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason)
}
}
/**
Creates a body part from the file and appends it to the multipart form data object.
The body part data will be encoded using the following format:
- Content-Disposition: form-data; name=#{name}; filename=#{filename} (HTTP Header)
- Content-Type: #{mimeType} (HTTP Header)
- Encoded file data
- Multipart form boundary
- parameter fileURL: The URL of the file whose content will be encoded into the multipart form data.
- parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header.
- parameter fileName: The filename to associate with the file content in the `Content-Disposition` HTTP header.
- parameter mimeType: The MIME type to associate with the file content in the `Content-Type` HTTP header.
*/
public func appendBodyPart(fileURL fileURL: NSURL, name: String, fileName: String, mimeType: String) {
let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType)
//============================================================
// Check 1 - is file URL?
//============================================================
guard fileURL.fileURL else {
let failureReason = "The file URL does not point to a file URL: \(fileURL)"
setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason)
return
}
//============================================================
// Check 2 - is file URL reachable?
//============================================================
var isReachable = true
if #available(OSX 10.10, *) {
isReachable = fileURL.checkPromisedItemIsReachableAndReturnError(nil)
}
guard isReachable else {
setBodyPartError(code: NSURLErrorBadURL, failureReason: "The file URL is not reachable: \(fileURL)")
return
}
//============================================================
// Check 3 - is file URL a directory?
//============================================================
var isDirectory: ObjCBool = false
guard let
path = fileURL.path
where NSFileManager.defaultManager().fileExistsAtPath(path, isDirectory: &isDirectory) && !isDirectory else {
let failureReason = "The file URL is a directory, not a file: \(fileURL)"
setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason)
return
}
//============================================================
// Check 4 - can the file size be extracted?
//============================================================
var bodyContentLength: UInt64?
do {
if let
path = fileURL.path,
fileSize = try NSFileManager.defaultManager().attributesOfItemAtPath(path)[NSFileSize] as? NSNumber {
bodyContentLength = fileSize.unsignedLongLongValue
}
} catch {
// No-op
}
guard let length = bodyContentLength else {
let failureReason = "Could not fetch attributes from the file URL: \(fileURL)"
setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason)
return
}
//============================================================
// Check 5 - can a stream be created from file URL?
//============================================================
guard let stream = NSInputStream(URL: fileURL) else {
let failureReason = "Failed to create an input stream from the file URL: \(fileURL)"
setBodyPartError(code: NSURLErrorCannotOpenFile, failureReason: failureReason)
return
}
appendBodyPart(stream: stream, length: length, headers: headers)
}
/**
Creates a body part from the stream and appends it to the multipart form data object.
The body part data will be encoded using the following format:
- `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header)
- `Content-Type: #{mimeType}` (HTTP Header)
- Encoded stream data
- Multipart form boundary
- parameter stream: The input stream to encode in the multipart form data.
- parameter length: The content length of the stream.
- parameter name: The name to associate with the stream content in the `Content-Disposition` HTTP header.
- parameter fileName: The filename to associate with the stream content in the `Content-Disposition` HTTP header.
- parameter mimeType: The MIME type to associate with the stream content in the `Content-Type` HTTP header.
*/
public func appendBodyPart(
stream stream: NSInputStream,
length: UInt64,
name: String,
fileName: String,
mimeType: String) {
let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType)
appendBodyPart(stream: stream, length: length, headers: headers)
}
/**
Creates a body part with the headers, stream and length and appends it to the multipart form data object.
The body part data will be encoded using the following format:
- HTTP headers
- Encoded stream data
- Multipart form boundary
- parameter stream: The input stream to encode in the multipart form data.
- parameter length: The content length of the stream.
- parameter headers: The HTTP headers for the body part.
*/
public func appendBodyPart(stream stream: NSInputStream, length: UInt64, headers: [String: String]) {
let bodyPart = BodyPart(headers: headers, bodyStream: stream, bodyContentLength: length)
bodyParts.append(bodyPart)
}
// MARK: - Data Encoding
/**
Encodes all the appended body parts into a single `NSData` object.
It is important to note that this method will load all the appended body parts into memory all at the same
time. This method should only be used when the encoded data will have a small memory footprint. For large data
cases, please use the `writeEncodedDataToDisk(fileURL:completionHandler:)` method.
- throws: An `NSError` if encoding encounters an error.
- returns: The encoded `NSData` if encoding is successful.
*/
public func encode() throws -> NSData {
if let bodyPartError = bodyPartError {
throw bodyPartError
}
let encoded = NSMutableData()
bodyParts.first?.hasInitialBoundary = true
bodyParts.last?.hasFinalBoundary = true
for bodyPart in bodyParts {
let encodedData = try encodeBodyPart(bodyPart)
encoded.appendData(encodedData)
}
return encoded
}
/**
Writes the appended body parts into the given file URL.
This process is facilitated by reading and writing with input and output streams, respectively. Thus,
this approach is very memory efficient and should be used for large body part data.
- parameter fileURL: The file URL to write the multipart form data into.
- throws: An `NSError` if encoding encounters an error.
*/
public func writeEncodedDataToDisk(fileURL: NSURL) throws {
if let bodyPartError = bodyPartError {
throw bodyPartError
}
if let path = fileURL.path where NSFileManager.defaultManager().fileExistsAtPath(path) {
let failureReason = "A file already exists at the given file URL: \(fileURL)"
throw Error.error(domain: NSURLErrorDomain, code: NSURLErrorBadURL, failureReason: failureReason)
} else if !fileURL.fileURL {
let failureReason = "The URL does not point to a valid file: \(fileURL)"
throw Error.error(domain: NSURLErrorDomain, code: NSURLErrorBadURL, failureReason: failureReason)
}
let outputStream: NSOutputStream
if let possibleOutputStream = NSOutputStream(URL: fileURL, append: false) {
outputStream = possibleOutputStream
} else {
let failureReason = "Failed to create an output stream with the given URL: \(fileURL)"
throw Error.error(domain: NSURLErrorDomain, code: NSURLErrorCannotOpenFile, failureReason: failureReason)
}
outputStream.open()
self.bodyParts.first?.hasInitialBoundary = true
self.bodyParts.last?.hasFinalBoundary = true
for bodyPart in self.bodyParts {
try writeBodyPart(bodyPart, toOutputStream: outputStream)
}
outputStream.close()
}
// MARK: - Private - Body Part Encoding
private func encodeBodyPart(bodyPart: BodyPart) throws -> NSData {
let encoded = NSMutableData()
let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData()
encoded.appendData(initialData)
let headerData = encodeHeaderDataForBodyPart(bodyPart)
encoded.appendData(headerData)
let bodyStreamData = try encodeBodyStreamDataForBodyPart(bodyPart)
encoded.appendData(bodyStreamData)
if bodyPart.hasFinalBoundary {
encoded.appendData(finalBoundaryData())
}
return encoded
}
private func encodeHeaderDataForBodyPart(bodyPart: BodyPart) -> NSData {
var headerText = ""
for (key, value) in bodyPart.headers {
headerText += "\(key): \(value)\(EncodingCharacters.CRLF)"
}
headerText += EncodingCharacters.CRLF
return headerText.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
}
private func encodeBodyStreamDataForBodyPart(bodyPart: BodyPart) throws -> NSData {
let inputStream = bodyPart.bodyStream
inputStream.open()
var error: NSError?
let encoded = NSMutableData()
while inputStream.hasBytesAvailable {
var buffer = [UInt8](count: streamBufferSize, repeatedValue: 0)
let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize)
if inputStream.streamError != nil {
error = inputStream.streamError
break
}
if bytesRead > 0 {
encoded.appendBytes(buffer, length: bytesRead)
} else if bytesRead < 0 {
let failureReason = "Failed to read from input stream: \(inputStream)"
error = Error.error(domain: NSURLErrorDomain, code: .InputStreamReadFailed, failureReason: failureReason)
break
} else {
break
}
}
inputStream.close()
if let error = error {
throw error
}
return encoded
}
// MARK: - Private - Writing Body Part to Output Stream
private func writeBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws {
try writeInitialBoundaryDataForBodyPart(bodyPart, toOutputStream: outputStream)
try writeHeaderDataForBodyPart(bodyPart, toOutputStream: outputStream)
try writeBodyStreamForBodyPart(bodyPart, toOutputStream: outputStream)
try writeFinalBoundaryDataForBodyPart(bodyPart, toOutputStream: outputStream)
}
private func writeInitialBoundaryDataForBodyPart(
bodyPart: BodyPart,
toOutputStream outputStream: NSOutputStream)
throws {
let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData()
return try writeData(initialData, toOutputStream: outputStream)
}
private func writeHeaderDataForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws {
let headerData = encodeHeaderDataForBodyPart(bodyPart)
return try writeData(headerData, toOutputStream: outputStream)
}
private func writeBodyStreamForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws {
let inputStream = bodyPart.bodyStream
inputStream.open()
while inputStream.hasBytesAvailable {
var buffer = [UInt8](count: streamBufferSize, repeatedValue: 0)
let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize)
if let streamError = inputStream.streamError {
throw streamError
}
if bytesRead > 0 {
if buffer.count != bytesRead {
buffer = Array(buffer[0..<bytesRead])
}
try writeBuffer(&buffer, toOutputStream: outputStream)
} else if bytesRead < 0 {
let failureReason = "Failed to read from input stream: \(inputStream)"
throw Error.error(domain: NSURLErrorDomain, code: .InputStreamReadFailed, failureReason: failureReason)
} else {
break
}
}
inputStream.close()
}
private func writeFinalBoundaryDataForBodyPart(
bodyPart: BodyPart,
toOutputStream outputStream: NSOutputStream)
throws {
if bodyPart.hasFinalBoundary {
return try writeData(finalBoundaryData(), toOutputStream: outputStream)
}
}
// MARK: - Private - Writing Buffered Data to Output Stream
private func writeData(data: NSData, toOutputStream outputStream: NSOutputStream) throws {
var buffer = [UInt8](count: data.length, repeatedValue: 0)
data.getBytes(&buffer, length: data.length)
return try writeBuffer(&buffer, toOutputStream: outputStream)
}
private func writeBuffer(inout buffer: [UInt8], toOutputStream outputStream: NSOutputStream) throws {
var bytesToWrite = buffer.count
while bytesToWrite > 0 {
if outputStream.hasSpaceAvailable {
let bytesWritten = outputStream.write(buffer, maxLength: bytesToWrite)
if let streamError = outputStream.streamError {
throw streamError
}
if bytesWritten < 0 {
let failureReason = "Failed to write to output stream: \(outputStream)"
throw Error.error(domain: NSURLErrorDomain, code: .OutputStreamWriteFailed, failureReason: failureReason)
}
bytesToWrite -= bytesWritten
if bytesToWrite > 0 {
buffer = Array(buffer[bytesWritten..<buffer.count])
}
} else if let streamError = outputStream.streamError {
throw streamError
}
}
}
// MARK: - Private - Mime Type
private func mimeTypeForPathExtension(pathExtension: String) -> String {
if let
id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension, nil)?.takeRetainedValue(),
contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue() {
return contentType as String
}
return "application/octet-stream"
}
// MARK: - Private - Content Headers
private func contentHeaders(name name: String) -> [String: String] {
return ["Content-Disposition": "form-data; name=\"\(name)\""]
}
private func contentHeaders(name name: String, mimeType: String) -> [String: String] {
return [
"Content-Disposition": "form-data; name=\"\(name)\"",
"Content-Type": "\(mimeType)"
]
}
private func contentHeaders(name name: String, fileName: String, mimeType: String) -> [String: String] {
return [
"Content-Disposition": "form-data; name=\"\(name)\"; filename=\"\(fileName)\"",
"Content-Type": "\(mimeType)"
]
}
// MARK: - Private - Boundary Encoding
private func initialBoundaryData() -> NSData {
return BoundaryGenerator.boundaryData(boundaryType: .Initial, boundary: boundary)
}
private func encapsulatedBoundaryData() -> NSData {
return BoundaryGenerator.boundaryData(boundaryType: .Encapsulated, boundary: boundary)
}
private func finalBoundaryData() -> NSData {
return BoundaryGenerator.boundaryData(boundaryType: .Final, boundary: boundary)
}
// MARK: - Private - Errors
private func setBodyPartError(code code: Int, failureReason: String) {
guard bodyPartError == nil else { return }
bodyPartError = Error.error(domain: NSURLErrorDomain, code: code, failureReason: failureReason)
}
}
|
103b710f53d4b55bd7b4d56ce53f5aef
| 39.302147 | 128 | 0.637858 | false | false | false | false |
RubyNative/RubyKit
|
refs/heads/master
|
String.swift
|
mit
|
2
|
//
// String.swift
// SwiftRuby
//
// Created by John Holdsworth on 26/09/2015.
// Copyright © 2015 John Holdsworth. All rights reserved.
//
// $Id: //depot/SwiftRuby/String.swift#13 $
//
// Repo: https://github.com/RubyNative/SwiftRuby
//
// See: http://ruby-doc.org/core-2.2.3/String.html
//
import Foundation
public var STRING_ENCODING = String.Encoding.utf8
public let FALLBACK_INPUT_ENCODING = String.Encoding.isoLatin1
public let FALLBACK_OUTPUT_ENCODING = String.Encoding.utf8
public enum StringIndexDisposition {
case warnAndFail, truncate
}
public var STRING_INDEX_DISPOSITION: StringIndexDisposition = .warnAndFail
public protocol string_like: array_like {
var to_s: String { get }
}
public protocol char_like {
var to_c: [CChar] { get }
}
extension String: string_like, array_like, data_like, char_like {
public subscript (i: Int) -> String {
return slice(i)
}
public subscript (start: Int, len: Int) -> String {
return slice(start, len: len)
}
public subscript (r: Range<Int>) -> String {
return String(self[index(startIndex, offsetBy: r.lowerBound) ..<
index(startIndex, offsetBy: r.upperBound)])
}
public var to_s: String {
return self
}
public var to_a: [String] {
// ??? self.characters.count
return [self]
}
public var to_c: [CChar] {
if let chars = cString(using: STRING_ENCODING) {
return chars
}
SRLog("String.to_c, unable to encode string for output")
return U(cString(using: FALLBACK_OUTPUT_ENCODING))
}
public var to_d: Data {
return Data(array: self.to_c)
}
public var to_i: Int {
if let val = Int(self) {
return val
}
let dummy = -99999999
SRLog("Unable to convert \(self) to Int. Returning \(dummy)")
return dummy
}
public var to_f: Double {
if let val = Double(self) {
return val
}
let dummy = -99999999.0
SRLog("Unable to convert \(self) to Doubleb. Returning \(dummy)")
return dummy
}
public func characterAtIndex(_ i: Int) -> Int {
if let char = self[i].unicodeScalars.first {
return Int(char.value)
}
SRLog("No character available in string '\(self)' returning nul char")
return 0
}
public var downcase: String {
return self.lowercased()
}
public func each_byte(_ block: (UInt8) -> ()) {
for char in utf8 {
block(char)
}
}
public func each_char(_ block: (UInt16) -> ()) {
for char in utf16 {
block(char)
}
}
public func each_codepoint(_ block: (String) -> ()) {
for char in self {
block(String(char ))
}
}
public func each_line(_ block: (String) -> ()) {
StringIO(self).each_line(LINE_SEPARATOR, nil, block)
}
public var length: Int {
return count
}
public var ord: Int {
return characterAtIndex(0)
}
public func slice(_ start: Int, len: Int = 1) -> String {
var vstart = start, vlen = len
let length = self.length
if start < 0 {
vstart = length + start
}
if vstart < 0 {
SRLog("String.str(\(start), \(len)) start before front of string '\(self)', length \(length)")
if STRING_INDEX_DISPOSITION == .truncate {
vstart = 0
}
}
else if vstart > length {
SRLog("String.str(\(start), \(len)) start after end of string '\(self)', length \(length)")
if STRING_INDEX_DISPOSITION == .truncate {
vstart = length
}
}
if len < 0 {
vlen = length + len - vstart
}
else if len == NSNotFound {
vlen = length - vstart
}
if vlen < 0 {
SRLog("String.str(\(start), \(len)) start + len before start of substring '\(self)', length \(length)")
if STRING_INDEX_DISPOSITION == .truncate {
vlen = 0
}
}
else if vstart + vlen > length {
SRLog("String.str(\(start), \(len)) start + len after end of string '\(self)', length \(length)")
if STRING_INDEX_DISPOSITION == .truncate {
vlen = length - vstart
}
}
return self[vstart..<vstart+vlen]
}
public func split(_ delimiter: String) -> [String] {
return components(separatedBy: delimiter)
}
public var upcase: String {
return self.uppercased()
}
}
|
2cf435bdc725ffe007742df6d75e0eba
| 24.192513 | 115 | 0.545532 | false | false | false | false |
pawel-sp/AppFlowController
|
refs/heads/master
|
iOS-Example/AlphaTransition.swift
|
mit
|
1
|
//
// AlphaTransition.swift
// iOS-Example
//
// Created by Paweł Sporysz on 02.10.2016.
// Copyright © 2016 Paweł Sporysz. All rights reserved.
//
import UIKit
import AppFlowController
class AlphaTransition: NSObject, UIViewControllerAnimatedTransitioning, FlowTransition, UINavigationControllerDelegate {
// MARK: - UIViewControllerAnimatedTransitioning
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.5
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard let fromVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) else { return }
guard let toVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) else { return }
let containerView = transitionContext.containerView
guard let toView = toVC.view else { return }
guard let fromView = fromVC.view else { return }
let animationDuration = transitionDuration(using: transitionContext)
toView.alpha = 0
containerView.addSubview(toView)
UIView.animate(withDuration: animationDuration, animations: {
toView.alpha = 1
}) { finished in
if (transitionContext.transitionWasCancelled) {
toView.removeFromSuperview()
} else {
fromView.removeFromSuperview()
}
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
}
// MARK: - FlowTransition
func performForwardTransition(animated: Bool, completion: @escaping () -> ()) -> ForwardTransition.ForwardTransitionAction {
return { navigationController, viewController in
let previousDelegate = navigationController.delegate
navigationController.delegate = self
navigationController.pushViewController(viewController, animated: animated){
navigationController.delegate = previousDelegate
completion()
}
}
}
func performBackwardTransition(animated: Bool, completion: @escaping () -> ()) -> BackwardTransition.BackwardTransitionAction {
return { viewController in
let navigationController = viewController.navigationController
let previousDelegate = navigationController?.delegate
navigationController?.delegate = self
let _ = navigationController?.popViewController(animated: animated) {
navigationController?.delegate = previousDelegate
completion()
}
}
}
// MARK: - UINavigationControllerDelegate
func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return self
}
}
|
31eb536579b48ff6a8b17b3d0c8853f8
| 40.835616 | 246 | 0.69057 | false | false | false | false |
derrickhunt/unsApp
|
refs/heads/master
|
UNS/UNS/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// UNS
//
// Created by Student on 4/30/15.
// Copyright (c) 2015 Derrick Hunt. All rights reserved.
//
import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate {
var webView: WKWebView!
var URLHistory = NSMutableArray()
@IBOutlet weak var myBackBtn: UIBarButtonItem!
@IBOutlet weak var myActionBtn: UIBarButtonItem!
@IBOutlet weak var myToolbar: UIToolbar!
@IBOutlet weak var myActivityIndicator: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
self.title = "University News"
//set up web view
webView = WKWebView()
webView.navigationDelegate = self
resizeWebView()
let url = NSURL(string: "http://www.rit.edu/news/")
let request = NSURLRequest(URL: url!)
webView.loadRequest(request)
view.addSubview(webView)
webView.hidden = true
//handle device rotation
UIDevice.currentDevice().beginGeneratingDeviceOrientationNotifications()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "resizeWebView", name: UIDeviceOrientationDidChangeNotification, object: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func resizeWebView() {
var navBarOffset = self.navigationController!.navigationBar.frame.height + UIApplication.sharedApplication().statusBarFrame.height
var toolBarOffset = myToolbar.frame.height + 1
webView.frame = CGRectMake(0, navBarOffset, view.frame.width, view.frame.height - navBarOffset - toolBarOffset)
}
//MARK: - Nav Bar Actions -
@IBAction func goBack(sender: AnyObject) {
if (URLHistory.count <= 1) {
return
}
//get URL
let request = NSURLRequest(URL: URLHistory[URLHistory.count - 2] as NSURL)
//update array and button
URLHistory.removeLastObject()
URLHistory.removeLastObject()
if (URLHistory.count <= 1) {
myBackBtn.enabled = false
}
//go back
webView.loadRequest(request)
println(URLHistory)
println(request)
}
@IBAction func goShare(sender: AnyObject) {
let urlString = URLHistory[URLHistory.count - 1] as NSURL
//let shareString = "RIT News: " + urlString
let activity = UIActivityViewController(activityItems: [urlString], applicationActivities: nil)
activity.popoverPresentationController?.barButtonItem = sender as UIBarButtonItem //attaches view to btn
presentViewController(activity, animated: true, completion: nil)
}
//MARK: - Toolbar Actions -
@IBAction func goHome(sender: AnyObject) {
let url = NSURL(string: "http://www.rit.edu/news/")
let request = NSURLRequest(URL: url!)
if (request != webView.URL!){
webView.loadRequest(request)
}
}
@IBAction func goMag(sender: AnyObject) {
let url = NSURL(string: "http://www.rit.edu/news/magazine.php")
let request = NSURLRequest(URL: url!)
if (request != webView.URL!){
webView.loadRequest(request)
}
}
@IBAction func goAth(sender: AnyObject) {
let url = NSURL(string: "http://www.rit.edu/news/athenaeum.php")
let request = NSURLRequest(URL: url!)
if (request != webView.URL!){
webView.loadRequest(request)
}
}
@IBAction func goSports(sender: AnyObject) {
let url = NSURL(string: "http://www.ritathletics.com/")
let request = NSURLRequest(URL: url!)
if (request != webView.URL!){
webView.loadRequest(request)
}
}
//MARK: - WKNavigation Methods -
func webView(webView: WKWebView, didCommitNavigation navigation: WKNavigation!) {
webView.hidden = true
myActivityIndicator.hidden = false
myActivityIndicator.startAnimating()
//update URL list and button
URLHistory.addObject(webView.URL!)
if (URLHistory.count > 1) {
myBackBtn.enabled = true
}
println(URLHistory)
}
func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
myActivityIndicator.stopAnimating()
//update nav title
if (webView.URL! == NSURL(string: "http://www.rit.edu/news/")) {
self.title = "University News"
}
if (webView.URL! == NSURL(string: "http://www.rit.edu/news/magazine.php")) {
self.title = "University Magazine"
}
if (webView.URL! == NSURL(string: "http://www.rit.edu/news/athenaeum.php")) {
self.title = "Athenaeum"
}
if (webView.URL! == NSURL(string: "http://www.ritathletics.com/")) {
self.title = "Athletics"
}
webView.hidden = false
}
func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) {
myActivityIndicator.stopAnimating()
//display error message
let errorMsg = UIAlertView(title: "Error", message: "An error occurred while processing your request. \n\nPlease make sure you are connected to the Internet and try again.", delegate: self, cancelButtonTitle: "Okay")
errorMsg.show()
//log error to console
println("Failed to load: \(error)")
}
func webView(webView: WKWebView, didFailNavigation navigation: WKNavigation!, withError error: NSError) {
myActivityIndicator.stopAnimating()
//display error message
let errorMsg = UIAlertView(title: "Error", message: "An error occurred while processing your request. \n\nPlease make sure you are connected to the Internet and try again.", delegate: self, cancelButtonTitle: "Okay")
errorMsg.show()
//log error to console
println("Failed to load: \(error)")
}
}
|
c06a13749353f0b18b3e8401c7224b0e
| 32.879781 | 224 | 0.616774 | false | false | false | false |
dedeexe/tmdb_example
|
refs/heads/master
|
tmdb/Classes/Common/Rest/FuckingRequest.swift
|
mit
|
1
|
//
// FuckingRequest.swift
// FuckTheRest
//
// Created by Fabrício Santos on 1/24/17.
// Copyright © 2017 dede.exe. All rights reserved.
//
import Foundation
open class FuckingRequest {
let url:URL
let method : String
var parameters : [String:String] = [:]
var headers : [String:String] = [:]
fileprivate var request : URLRequest
{
var fieldParams:[String] = []
var urlRequest = URLRequest(url: self.url)
urlRequest.httpMethod = method
for (key,value) in headers {
urlRequest.addValue(value, forHTTPHeaderField: key)
}
for (key,value) in parameters {
let paramValue = "\(key)=\(value)"
fieldParams.append(paramValue)
}
let paramsString = fieldParams.joined(separator: "&")
if method == FuckingMethod.get.rawValue && fieldParams.count > 0 {
let urlString = url.absoluteString + "?" + paramsString
let getURL = URL(string: urlString)
urlRequest.url = getURL
return urlRequest
}
urlRequest.httpBody = paramsString.data(using:.utf8)
return urlRequest
}
public init(url:String, methodName:String) {
self.url = URL(string:url)!
self.method = methodName
}
convenience public init(url:String, method:FuckingMethod) {
self.init(url:url, methodName:method.rawValue)
}
open func header(_ fields:[String:String]) {
self.headers = fields
}
open func addHeader(_ key:String, value:String) -> FuckingRequest {
self.headers[key] = value
return self
}
open func parameters(_ fields:[String:String]) {
self.headers = fields
}
open func addParameter(_ key:String, value:String) -> FuckingRequest {
self.parameters[key] = value
return self
}
}
extension FuckingRequest
{
open func response(completion:@escaping (FuckingResult<Data>) -> Void) {
let requestEntity = self.request
let responseEntity = FuckingResponse(request: requestEntity)
responseEntity.getData(completion: completion)
}
open func responseString(completion:@escaping (FuckingResult<String>) -> Void) {
let requestEntity = self.request
let responseEntity = FuckingResponse(request: requestEntity)
responseEntity.getData { (resultData) in
let stringResult = resultData.map(extractStringFromData)
completion(stringResult)
}
}
}
|
546f1e32cc3e7ad9d24f8a2855b5209e
| 27.648352 | 84 | 0.60491 | false | false | false | false |
breadwallet/breadwallet-ios
|
refs/heads/master
|
breadwalletWidget/Services/WidgetService.swift
|
mit
|
1
|
//
// WidgetService.swift
// breadwalletIntentHandler
//
// Created by stringcode on 11/02/2021.
// Copyright © 2021 Breadwinner AG. All rights reserved.
//
// See the LICENSE file at the project root for license information.
//
import Foundation
import CoinGecko
typealias CurrencyHandler = (Result<[Currency], Error>) -> Void
typealias AssetOptionHandler = (Result<[AssetOption], Error>) -> Void
typealias ColorOptionHandler = (Result<[ColorOption], Error>) -> Void
typealias CurrencyInfoHandler = (CurrencyInfoResult) -> Void
typealias CurrencyInfoResult = Result<([Currency], [CurrencyId: MarketInfo]), Error>
protocol WidgetService {
func fetchCurrenciesAndMarketInfo(for assetOptions: [AssetOption],
quote: String,
interval: IntervalOption,
handler: @escaping CurrencyInfoHandler)
func fetchCurrencies(handler: @escaping CurrencyHandler)
func fetchAssetOptions(handler: @escaping AssetOptionHandler)
func fetchBackgroundColorOptions(handler: ColorOptionHandler)
func fetchTextColorOptions(handler: ColorOptionHandler)
func fetchChartUpColorOptions(handler: ColorOptionHandler)
func fetchChartDownColorOptions(handler: ColorOptionHandler)
func defaultBackgroundColor() -> ColorOption
func defaultTextColor() -> ColorOption
func defaultChartUpOptions() -> ColorOption
func defaultChartDownOptions() -> ColorOption
func defaultAssetOptions() -> [AssetOption]
func defaultCurrencies() throws -> [Currency]
func quoteCurrencyCode() -> String
}
enum WidgetServiceError: Error {
case failedToLoadCurrenciesFile
}
// MARK: - DefaultAssetsOptionsService
class DefaultWidgetService: WidgetService {
let widgetDataShareService: WidgetDataShareService?
let coinGeckoClient = CoinGeckoClient()
private(set) var currenciesCache: [Currency] = []
init(widgetDataShareService: WidgetDataShareService?,
imageStoreService: ImageStoreService?) {
self.widgetDataShareService = widgetDataShareService
imageStoreService?.loadImagesIfNeeded()
}
func fetchCurrenciesAndMarketInfo(for assetOptions: [AssetOption],
quote: String,
interval: IntervalOption,
handler: @escaping CurrencyInfoHandler) {
let uids = assetOptions.map { $0.identifier }
fetchCurrencies { [weak self] result in
switch result {
case let .success(currencies):
let selected = currencies.filter { uids.contains($0.uid.rawValue) }
self?.fetchPriceListAndChart(for: selected,
quote: quote,
interval: interval,
handler: handler)
case let .failure(error):
handler(.failure(error))
}
}
}
func fetchCurrencies(handler: @escaping CurrencyHandler) {
if !currenciesCache.isEmpty {
handler(.success(currenciesCache))
return
}
do {
let currencies = try defaultCurrencies()
handler(.success(currencies))
} catch {
handler(.failure(error))
}
}
func fetchAssetOptions(handler: @escaping AssetOptionHandler) {
fetchCurrencies { result in
switch result {
case let .success(currencies):
handler(.success(currencies.map { $0.assetOption() }))
case let .failure(error):
handler(.failure(error))
}
}
}
func defaultAssetOptions() -> [AssetOption] {
return ((try? defaultCurrencies()) ?? [])
.filter { Constant.defaultCurrencyCodes.contains($0.code.uppercased()) }
.map { $0.assetOption() }
}
func fetchBackgroundColorOptions(handler: ColorOptionHandler) {
let currenciesColors = ((try? defaultCurrencies()) ?? []).map {
ColorOption(currency: $0)
}
let colorOptions = [ColorOption.autoBackground]
+ ColorOption.backgroundColors()
+ ColorOption.basicColors()
+ currenciesColors
handler(.success(colorOptions))
}
func defaultBackgroundColor() -> ColorOption {
return ColorOption.autoBackground
}
func fetchTextColorOptions(handler: ColorOptionHandler) {
let colorOptions = [ColorOption.autoTextColor]
+ ColorOption.textColors()
+ ColorOption.basicColors()
+ ColorOption.backgroundColors()
handler(.success(colorOptions))
}
func defaultTextColor() -> ColorOption {
return ColorOption.autoTextColor
}
func fetchChartUpColorOptions(handler: ColorOptionHandler) {
let options = ColorOption.basicColors()
+ ColorOption.textColors()
+ ColorOption.backgroundColors()
handler(.success(options))
}
func defaultChartUpOptions() -> ColorOption {
return ColorOption.green
}
func fetchChartDownColorOptions(handler: ColorOptionHandler) {
let options = ColorOption.basicColors()
+ ColorOption.textColors()
+ ColorOption.backgroundColors()
handler(.success(options))
}
func defaultChartDownOptions() -> ColorOption {
return ColorOption.red
}
func defaultCurrencies() throws -> [Currency] {
guard currenciesCache.isEmpty else {
return currenciesCache
}
guard let url = Constant.currenciesURL else {
throw WidgetServiceError.failedToLoadCurrenciesFile
}
do {
let data = try Data(contentsOf: url)
let decoder = JSONDecoder()
let meta = try decoder.decode([CurrencyMetaData].self, from: data)
let currencies = meta
.map { Currency(metaData: $0)}
.filter { $0.isSupported }
.sorted { $0.metaData.isPreferred && !$1.metaData.isPreferred }
.sorted { $0.isEthereum && !$1.isEthereum }
.sorted { $0.isBitcoin && !$1.isBitcoin }
currenciesCache = currencies
return currencies
}
}
func quoteCurrencyCode() -> String {
return widgetDataShareService?.quoteCurrencyCode ?? "USD"
}
}
// MARK: - Loading chart and simple price
private extension DefaultWidgetService {
typealias MarketChartResult = Result<MarketChart, CoinGeckoError>
typealias PriceListResult = Result<PriceList, CoinGeckoError>
func fetchPriceListAndChart(for currencies: [Currency],
quote: String,
interval: IntervalOption,
handler: @escaping (CurrencyInfoResult) -> Void) {
let group = DispatchGroup()
var priceList: PriceList = []
var charts: [CurrencyId: MarketChart] = [:]
var error: Error?
let codes = currencies.compactMap { $0.coinGeckoId }
group.enter()
self.priceList(codes: codes, base: quote) { result in
switch result {
case let .success(list):
priceList = list
case let .failure(err):
error = err
}
group.leave()
}
for currency in currencies {
guard let code = currency.coinGeckoId else {
continue
}
group.enter()
chart(code: code, quote: quote, interval: interval.resources) { result in
switch result {
case let .success(chartData):
charts[currency.uid] = chartData
case let .failure(error):
print(error)
}
group.leave()
}
}
group.notify(queue: DispatchQueue.global()) {
if let error = error {
handler(.failure(error))
return
}
let info = self.marketInfo(currencies, priceList: priceList, charts: charts)
handler(.success((currencies, info)))
}
}
func priceList(codes: [String], base: String, handler: @escaping (PriceListResult) -> Void) {
let prices = Resources.simplePrice(ids: codes,
vsCurrency: base,
options: SimplePriceOptions.allCases,
handler)
coinGeckoClient.load(prices)
}
func chart(code: String,
quote: String,
interval: Resources.Interval,
handler: @escaping (MarketChartResult) -> Void) {
let chart = Resources.chart(base: code,
quote: quote,
interval: interval,
callback: handler)
coinGeckoClient.load(chart)
}
func marketInfo(_ currencies: [Currency],
priceList: PriceList,
charts: [CurrencyId: MarketChart]) -> [CurrencyId: MarketInfo] {
var result = [CurrencyId: MarketInfo]()
for currency in currencies {
let coinGeckoId = currency.coinGeckoId ?? "error"
let simplePrice = priceList.first(where: { $0.id == coinGeckoId})
let amount = widgetDataShareService?.amount(for: currency.uid)
if let price = simplePrice {
result[currency.uid] = MarketInfo(id: currency.uid,
amount: amount,
simplePrice: price,
chart: charts[currency.uid])
}
}
return result
}
}
// MARK: - Utilities
private extension DefaultWidgetService {
enum Constant {
static let defaultCurrencyCodes = ["BTC", "ETH", "BRD"]
static let currenciesURL = Bundle.main.url(forResource: "currencies",
withExtension: "json")
}
}
|
4e4adeed3f94e60e5a002642951309fa
| 34.037162 | 97 | 0.569376 | false | false | false | false |
machelix/Lightbox
|
refs/heads/master
|
Source/LightboxViewCell.swift
|
mit
|
1
|
import UIKit
public class LightboxViewCell: UICollectionViewCell {
public static let reuseIdentifier: String = "LightboxViewCell"
var constraintsAdded = false
weak var parentViewController: LightboxController?
public lazy var lightboxView: LightboxView = { [unowned self] in
let lightboxView = LightboxView(frame: self.bounds)
lightboxView.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(lightboxView)
return lightboxView
}()
public override func layoutSubviews() {
super.layoutSubviews()
setupConstraints()
lightboxView.updateViewLayout()
}
public func setupTransitionManager() {
guard let controller = parentViewController else { return }
controller.transitionManager.sourceViewCell = self
controller.transitionManager.animator = UIDynamicAnimator(referenceView: lightboxView)
}
private func setupConstraints() {
if !constraintsAdded {
let layoutAttributes: [NSLayoutAttribute] = [.Leading, .Trailing, .Top, .Bottom]
for layoutAttribute in layoutAttributes {
addConstraint(NSLayoutConstraint(item: lightboxView, attribute: layoutAttribute,
relatedBy: .Equal, toItem: contentView, attribute: layoutAttribute,
multiplier: 1, constant: 0))
}
constraintsAdded = true
}
}
}
|
12a2aa9c43e45a8e423ea747e5f598ee
| 30.046512 | 90 | 0.740075 | false | false | false | false |
somegeekintn/SimDirs
|
refs/heads/main
|
SimDirs/Views/DescriptiveToggle.swift
|
mit
|
1
|
//
// DescriptiveToggle.swift
// SimDirs
//
// Created by Casey Fleser on 8/7/22.
//
import SwiftUI
protocol ToggleDescriptor {
var isOn : Bool { get }
var titleKey : LocalizedStringKey { get }
var text : String { get }
var image : Image { get }
}
extension ToggleDescriptor {
var circleColor : Color { isOn ? .accentColor : Color("CircleSymbolBkgOff") }
}
struct DescriptiveToggle<T: ToggleDescriptor>: View {
@Binding var isOn : Bool
var descriptor : T
var subtitled : Bool
init(_ descriptor: T, isOn: Binding<Bool>, subtitled: Bool = true) {
self._isOn = isOn
self.descriptor = descriptor
self.subtitled = subtitled
}
var body: some View {
Toggle(descriptor.titleKey, isOn: _isOn)
.toggleStyle(DescriptiveToggleStyle(descriptor, subtitled: subtitled))
}
}
struct DescriptiveToggle_Previews: PreviewProvider {
struct DarkMode: ToggleDescriptor {
var isOn : Bool = true
var titleKey : LocalizedStringKey { "Dark Mode" }
var text : String { isOn ? "On" : "Off" }
var image : Image { Image(systemName: "circle.circle") }
}
@State static var toggle = DarkMode()
static var previews: some View {
DescriptiveToggle(DarkMode(), isOn: $toggle.isOn)
.disabled(true)
}
}
|
02dc3bd4203e48d6eaef9a59436f51ec
| 26.134615 | 82 | 0.603118 | false | false | false | false |
taji-taji/TJExtensions
|
refs/heads/master
|
TJExtensions/Sources/UIViewExtensions.swift
|
mit
|
1
|
//
// UIViewExtensions.swift
// TJExtension
//
// Created by tajika on 2015/12/08.
// Copyright © 2015年 Tajika. All rights reserved.
//
import UIKit
public enum TJViewBorderPosition {
case top
case right
case bottom
case left
}
public extension UIView {
/**
Extended by TJExtensions
*/
public func border(borderWidth: CGFloat, borderColor: UIColor?, borderRadius: CGFloat?) {
self.layer.borderWidth = borderWidth
self.layer.borderColor = borderColor?.cgColor
if let _ = borderRadius {
self.layer.cornerRadius = borderRadius!
}
self.layer.masksToBounds = true
}
/**
Extended by TJExtensions
*/
public func border(_ positions: Set<TJViewBorderPosition>, borderWidth: CGFloat, borderColor: UIColor?) {
self.layer.sublayers = nil
if positions.contains(.top) {
borderTop(borderWidth, borderColor: borderColor)
}
if positions.contains(.left) {
borderLeft(borderWidth, borderColor: borderColor)
}
if positions.contains(.bottom) {
borderBottom(borderWidth, borderColor: borderColor)
}
if positions.contains(.right) {
borderRight(borderWidth, borderColor: borderColor)
}
}
fileprivate func borderTop(_ borderWidth: CGFloat, borderColor: UIColor?) {
let rect = CGRect(x: 0.0, y: 0.0, width: self.frame.width, height: borderWidth)
addBorderWithRect(borderWidth, borderColor: borderColor, rect: rect)
}
fileprivate func borderBottom(_ borderWidth: CGFloat, borderColor: UIColor?) {
let rect = CGRect(x: 0.0, y: self.frame.height - borderWidth, width: self.frame.width, height: borderWidth)
addBorderWithRect(borderWidth, borderColor: borderColor, rect: rect)
}
fileprivate func borderLeft(_ borderWidth: CGFloat, borderColor: UIColor?) {
let rect = CGRect(x: 0.0, y: 0.0, width: borderWidth, height: self.frame.height)
addBorderWithRect(borderWidth, borderColor: borderColor, rect: rect)
}
fileprivate func borderRight(_ borderWidth: CGFloat, borderColor: UIColor?) {
let rect = CGRect(x: self.frame.width - borderWidth, y: 0.0, width: borderWidth, height: self.frame.height)
addBorderWithRect(borderWidth, borderColor: borderColor, rect: rect)
}
fileprivate func addBorderWithRect(_ borderWidth: CGFloat, borderColor: UIColor?, rect: CGRect) {
let line = CALayer()
let defaultBorderColor = UIColor.white
var CGBorderColor: CGColor
self.layer.masksToBounds = true
if let _ = borderColor {
CGBorderColor = borderColor!.cgColor
} else {
CGBorderColor = defaultBorderColor.cgColor
}
line.frame = rect
line.backgroundColor = CGBorderColor
self.layer.addSublayer(line)
self.setNeedsDisplay()
}
/**
Extended by TJExtensions
*/
@IBInspectable
var borderWidth: CGFloat {
get {
return self.layer.borderWidth
}
set {
self.layer.borderWidth = newValue
}
}
/**
Extended by TJExtensions
*/
@IBInspectable
var borderColor: UIColor? {
get {
if let _ = self.layer.borderColor {
return UIColor(cgColor: self.layer.borderColor!)
}
return nil
}
set {
self.layer.borderColor = newValue?.cgColor
}
}
/**
Extended by TJExtensions
*/
@IBInspectable
var cornerRadius: CGFloat {
get {
return self.layer.cornerRadius
}
set {
self.layer.cornerRadius = newValue
}
}
}
|
908abf675c760f21d9c27de4c6747bc6
| 28.389313 | 115 | 0.604416 | false | false | false | false |
JohnSundell/Wrap
|
refs/heads/master
|
Tests/WrapTests/WrapTests.swift
|
mit
|
1
|
/**
* Wrap
*
* Copyright (c) 2015 - 2017 John Sundell. Licensed under the MIT license, as follows:
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import Foundation
import XCTest
import Wrap
// MARK: - Tests
class WrapTests: XCTestCase {
func testBasicStruct() {
struct Model {
let string = "A string"
let int = 15
let double = 7.6
}
do {
try verify(dictionary: wrap(Model()), againstDictionary: [
"string" : "A string",
"int" : 15,
"double" : 7.6
])
} catch {
XCTFail(error.toString())
}
}
func testOptionalProperties() {
struct Model {
let string: String? = "A string"
let int: Int? = 5
let missing: String? = nil
let missingNestedOptional: Optional<Optional<String>> = .some(.none)
}
do {
try verify(dictionary: wrap(Model()), againstDictionary: [
"string" : "A string",
"int" : 5
])
} catch {
XCTFail(error.toString())
}
}
func testSpecificNonOptionalProperties() {
struct Model {
let some: String = "value"
let Some: Int = 1
}
do {
try verify(dictionary: wrap(Model()), againstDictionary: [
"some" : "value",
"Some" : 1
])
} catch {
XCTFail(error.toString())
}
}
func testSpecificNonOptionalValues() {
struct Model {
let string: String = "nil"
}
do {
try verify(dictionary: wrap(Model()), againstDictionary: [
"string" : "nil"
])
} catch {
XCTFail(error.toString())
}
}
func testProtocolProperties() {
struct NestedModel: MockProtocol {
let constantString = "Another string"
var mutableInt = 27
}
struct Model: MockProtocol {
let constantString = "A string"
var mutableInt = 15
let nested: MockProtocol = NestedModel()
}
do {
try verify(dictionary: wrap(Model()), againstDictionary: [
"constantString" : "A string",
"mutableInt" : 15,
"nested": [
"constantString" : "Another string",
"mutableInt" : 27
]
])
} catch {
XCTFail(error.toString())
}
}
func testRootEnum() {
enum Enum {
case first
case second(String)
}
do {
try verify(dictionary: wrap(Enum.first), againstDictionary: [:])
try verify(dictionary: wrap(Enum.second("Hello")), againstDictionary: [
"second" : "Hello"
])
} catch {
XCTFail(error.toString())
}
}
func testEnumProperties() {
enum Enum {
case first
case second(String)
case third(intValue: Int)
}
enum IntEnum: Int, WrappableEnum {
case first
case second = 17
}
enum StringEnum: String, WrappableEnum {
case first = "First string"
case second = "Second string"
}
struct Model {
let first = Enum.first
let second = Enum.second("Hello")
let third = Enum.third(intValue: 15)
let firstInt = IntEnum.first
let secondInt = IntEnum.second
let firstString = StringEnum.first
let secondString = StringEnum.second
}
do {
try verify(dictionary: wrap(Model()), againstDictionary: [
"first" : "first",
"second" : [
"second" : "Hello"
],
"third" : [
"third" : 15
],
"firstInt" : 0,
"secondInt" : 17,
"firstString" : "First string",
"secondString" : "Second string"
])
} catch {
XCTFail(error.toString())
}
}
func testDateProperty() {
let date = Date()
struct Model {
let date: Date
}
let dateFormatter = DateFormatter()
do {
let model = Model(date: date)
try verify(dictionary: wrap(model, dateFormatter: dateFormatter), againstDictionary: [
"date" : dateFormatter.string(from: date)
])
} catch {
XCTFail("\(try! wrap(Model(date: date), dateFormatter: dateFormatter) as WrappedDictionary)")
XCTFail(error.toString())
}
}
#if !os(Linux)
func testNSDateProperty() {
let date = NSDate()
struct Model {
let date: NSDate
}
let dateFormatter = DateFormatter()
do {
let model = Model(date: date)
try verify(dictionary: wrap(model, dateFormatter: dateFormatter), againstDictionary: [
"date" : dateFormatter.string(from: date as Date)
])
} catch {
XCTFail("\(try! wrap(Model(date: date), dateFormatter: dateFormatter) as WrappedDictionary)")
XCTFail(error.toString())
}
}
#endif
func testDatePropertyWithCustomizableStruct() {
let date = Date()
struct Model: WrapCustomizable {
let date: Date
}
let dateFormatter = DateFormatter()
do {
let model = Model(date: date)
try verify(dictionary: wrap(model, dateFormatter: dateFormatter), againstDictionary: [
"date" : dateFormatter.string(from: date)
])
} catch {
XCTFail(error.toString())
}
}
func testEmptyStruct() {
struct Empty {}
do {
try verify(dictionary: wrap(Empty()), againstDictionary: [:])
} catch {
XCTFail(error.toString())
}
}
func testNestedEmptyStruct() {
struct Empty {}
struct EmptyWithOptional {
let optional: String? = nil
}
struct Model {
let empty = Empty()
let emptyWithOptional = EmptyWithOptional()
}
do {
try verify(dictionary: wrap(Model()), againstDictionary: [
"empty" : [:],
"emptyWithOptional" : [:]
])
} catch {
XCTFail(error.toString())
}
}
func testArrayProperties() {
struct Model {
let homogeneous = ["Wrap", "Tests"]
let mixed = ["Wrap", 15, 8.3] as [Any]
}
do {
try verify(dictionary: wrap(Model()), againstDictionary: [
"homogeneous" : ["Wrap", "Tests"],
"mixed" : ["Wrap", 15, 8.3]
])
} catch {
XCTFail(error.toString())
}
}
func testDictionaryProperties() {
struct Model {
let homogeneous = [
"Key1" : "Value1",
"Key2" : "Value2"
]
let mixed: WrappedDictionary = [
"Key1" : 15,
"Key2" : 19.2,
"Key3" : "Value",
"Key4" : ["Wrap", "Tests"],
"Key5" : [
"NestedKey" : "NestedValue"
]
]
}
do {
try verify(dictionary: wrap(Model()), againstDictionary: [
"homogeneous" : [
"Key1" : "Value1",
"Key2" : "Value2"
],
"mixed" : [
"Key1" : 15,
"Key2" : 19.2,
"Key3" : "Value",
"Key4" : ["Wrap", "Tests"],
"Key5" : [
"NestedKey" : "NestedValue"
]
]
])
} catch {
XCTFail(error.toString())
}
}
func testHomogeneousSetProperty() {
struct Model {
let set: Set<String> = ["Wrap", "Tests"]
}
do {
let dictionary: WrappedDictionary = try wrap(Model())
XCTAssertEqual(dictionary.count, 1)
guard let array = dictionary["set"] as? [String] else {
return XCTFail("Expected array for key \"set\"")
}
XCTAssertEqual(Set(array), ["Wrap", "Tests"])
} catch {
XCTFail(error.toString())
}
}
#if !os(Linux)
func testMixedNSObjectSetProperty() {
struct Model {
let set: Set<NSObject> = ["Wrap" as NSObject, 15 as NSObject, 8.3 as NSObject]
}
do {
try verify(dictionary: wrap(Model()), againstDictionary: [
"set" : ["Wrap", 15, 8.3]
])
} catch {
XCTFail(error.toString())
}
}
#endif
func testNSURLProperty() {
struct Model {
let optionalURL = NSURL(string: "http://github.com")
let URL = NSURL(string: "http://google.com")!
}
do {
try verify(dictionary: wrap(Model()), againstDictionary: [
"optionalURL" : "http://github.com",
"URL" : "http://google.com"
])
} catch {
XCTFail(error.toString())
}
}
func testURLProperty() {
struct Model {
let optionalUrl = URL(string: "http://github.com")
let url = URL(string: "http://google.com")!
}
do {
try verify(dictionary: wrap(Model()), againstDictionary: [
"optionalUrl" : "http://github.com",
"url" : "http://google.com"
])
} catch {
XCTFail(error.toString())
}
}
func test64BitIntegerProperties() {
struct Model {
let int = Int64.max
let uint = UInt64.max
}
do {
let dictionary = try JSONSerialization.jsonObject(with: wrap(Model()), options: []) as! WrappedDictionary
try verify(dictionary: dictionary, againstDictionary: [
"int" : Int64.max,
"uint" : UInt64.max
])
} catch {
XCTFail(error.toString())
}
}
func testRootSubclass() {
class Superclass {
let string1 = "String1"
let int1 = 1
}
class Subclass: Superclass {
let string2 = "String2"
let int2 = 2
}
do {
try verify(dictionary: wrap(Subclass()), againstDictionary: [
"string1" : "String1",
"string2" : "String2",
"int1" : 1,
"int2" : 2
])
} catch {
XCTFail(error.toString())
}
}
func testRootNSObjectSubclass() {
class Model: NSObject {
let string = "String"
let double = 7.14
}
do {
try verify(dictionary: wrap(Model()), againstDictionary: [
"string" : "String",
"double" : 7.14
])
} catch {
XCTFail(error.toString())
}
}
func testRootDictionary() {
struct Model {
var string: String
}
let dictionary = [
"model1" : Model(string: "First"),
"model2" : Model(string: "Second")
]
do {
try verify(dictionary: wrap(dictionary), againstDictionary: [
"model1" : [
"string" : "First"
],
"model2" : [
"string" : "Second"
]
])
} catch {
XCTFail(error.toString())
}
}
func testNestedStruct() {
struct NestedModel {
let string = "Nested model"
}
struct Model {
let nested = NestedModel()
}
do {
try verify(dictionary: wrap(Model()), againstDictionary: [
"nested" : [
"string" : "Nested model"
]
])
} catch {
XCTFail(error.toString())
}
}
func testNestedArrayOfStructs() {
struct NestedModel1 {
let string1: String
}
struct NestedModel2 {
let string2: String
}
struct Model {
let nested: [Any] = [
NestedModel1(string1: "String1"),
NestedModel2(string2: "String2"),
]
}
do {
let wrapped: WrappedDictionary = try wrap(Model())
if let nested = wrapped["nested"] as? [WrappedDictionary] {
XCTAssertEqual(nested.count, 2)
if let firstDictionary = nested.first, let secondDictionary = nested.last {
try verify(dictionary: firstDictionary, againstDictionary: [
"string1" : "String1"
])
try verify(dictionary: secondDictionary, againstDictionary: [
"string2" : "String2"
])
} else {
XCTFail("Missing dictionaries")
}
} else {
XCTFail("Unexpected type")
}
} catch {
XCTFail(error.toString())
}
}
func testNestedDictionariesOfStructs() {
struct NestedModel {
let string = "Hello"
}
struct Model {
let nested = [
"model" : NestedModel()
]
}
do {
try verify(dictionary: wrap(Model()), againstDictionary: [
"nested" : [
"model" : [
"string" : "Hello"
]
]
])
} catch {
XCTFail(error.toString())
}
}
func testNestedSubclass() {
class Superclass {
let string1 = "String1"
}
class Subclass: Superclass {
let string2 = "String2"
}
struct Model {
let superclass = Superclass()
let subclass = Subclass()
}
do {
try verify(dictionary: wrap(Model()), againstDictionary: [
"superclass" : [
"string1" : "String1"
],
"subclass" : [
"string1" : "String1",
"string2" : "String2"
]
])
} catch {
XCTFail(error.toString())
}
}
func testDeepNesting() {
struct ThirdModel {
let string = "Third String"
}
struct SecondModel {
let string = "Second String"
let nestedArray = [ThirdModel()]
}
struct FirstModel {
let string = "First String"
let nestedDictionary = [ "nestedDictionary" : SecondModel()]
}
do {
let wrappedDictionary :WrappedDictionary = try wrap(FirstModel())
try verify(dictionary: wrappedDictionary, againstDictionary: [
"string" : "First String",
"nestedDictionary" : [
"nestedDictionary" : [
"string" : "Second String",
"nestedArray" : [
["string" : "Third String"]
]
]
]
])
} catch {
XCTFail(error.toString())
}
}
#if !os(Linux)
func testObjectiveCObjectProperties() {
struct Model {
let string = NSString(string: "Hello")
let number = NSNumber(value: 17)
let array = NSArray(object: NSString(string: "Unwrap"))
}
do {
try verify(dictionary: wrap(Model()), againstDictionary: [
"string" : "Hello",
"number" : 17,
"array" : ["Unwrap"]
])
} catch {
XCTFail(error.toString())
}
}
#endif
func testWrappableKey() {
enum Key: Int, WrappableKey {
case first = 15
case second = 19
func toWrappedKey() -> String {
return String(self.rawValue)
}
}
struct Model {
let dictionary = [
Key.first : "First value",
Key.second : "Second value"
]
}
do {
try verify(dictionary: wrap(Model()), againstDictionary: [
"dictionary" : [
"15" : "First value",
"19" : "Second value"
]
])
} catch {
XCTFail(error.toString())
}
}
func testKeyCustomization() {
struct Model: WrapCustomizable {
let string = "Default"
let customized = "I'm customized"
let skipThis = 15
fileprivate func keyForWrapping(propertyNamed propertyName: String) -> String? {
if propertyName == "customized" {
return "totallyCustomized"
}
if propertyName == "skipThis" {
return nil
}
return propertyName
}
}
do {
try verify(dictionary: wrap(Model()), againstDictionary: [
"string" : "Default",
"totallyCustomized" : "I'm customized"
])
} catch {
XCTFail(error.toString())
}
}
func testCustomWrapping() {
struct Model: WrapCustomizable {
let string = "A string"
func wrap(context: Any?, dateFormatter: DateFormatter?) -> Any? {
return [
"custom" : "A value"
]
}
}
do {
try verify(dictionary: wrap(Model()), againstDictionary: [
"custom" : "A value"
])
} catch {
XCTFail(error.toString())
}
}
func testCustomWrappingCallingWrapFunction() {
struct Model: WrapCustomizable {
let int = 27
func wrap(context: Any?, dateFormatter: DateFormatter?) -> Any? {
do {
var wrapped = try Wrapper().wrap(object: self)
wrapped["custom"] = "A value"
return wrapped
} catch {
return nil
}
}
}
do {
try verify(dictionary: wrap(Model()), againstDictionary: [
"int" : 27,
"custom" : "A value"
])
} catch {
XCTFail(error.toString())
}
}
func testCustomWrappingForSingleProperty() {
struct Model: WrapCustomizable {
let string = "Hello"
let int = 16
func wrap(propertyNamed propertyName: String, originalValue: Any, context: Any?, dateFormatter: DateFormatter?) throws -> Any? {
if propertyName == "int" {
XCTAssertEqual((originalValue as? Int) ?? 0, self.int)
return 27
}
return nil
}
}
do {
try verify(dictionary: wrap(Model()), againstDictionary: [
"string" : "Hello",
"int" : 27
])
} catch {
XCTFail(error.toString())
}
}
func testCustomWrappingFailureThrows() {
struct Model: WrapCustomizable {
func wrap(context: Any?, dateFormatter: DateFormatter?) -> Any? {
return nil
}
}
do {
_ = try wrap(Model()) as WrappedDictionary
XCTFail("Should have thrown")
} catch WrapError.wrappingFailedForObject(let object) {
XCTAssertTrue(object is Model)
} catch {
XCTFail("Invalid error type: " + error.toString())
}
}
func testCustomWrappingForSinglePropertyFailureThrows() {
struct Model: WrapCustomizable {
let string = "A string"
func wrap(propertyNamed propertyName: String, originalValue: Any, context: Any?, dateFormatter: DateFormatter?) throws -> Any? {
throw NSError(domain: "ERROR", code: 0, userInfo: nil)
}
}
do {
_ = try wrap(Model()) as WrappedDictionary
XCTFail("Should have thrown")
} catch WrapError.wrappingFailedForObject(let object) {
XCTAssertTrue(object is Model)
} catch {
XCTFail("Invalid error type: " + error.toString())
}
}
func testInvalidRootObjectThrows() {
do {
_ = try wrap("A string") as WrappedDictionary
} catch WrapError.invalidTopLevelObject(let object) {
XCTAssertEqual((object as? String) ?? "", "A string")
} catch {
XCTFail("Invalid error type: " + error.toString())
}
}
func testDataWrapping() {
struct Model {
let string = "A string"
let int = 42
let array = [4, 1, 9]
}
do {
let data: Data = try wrap(Model())
let object = try JSONSerialization.jsonObject(with: data, options: [])
guard let dictionary = object as? WrappedDictionary else {
return XCTFail("Invalid encoded type")
}
try verify(dictionary: dictionary, againstDictionary: [
"string" : "A string",
"int" : 42,
"array" : [4, 1, 9]
])
} catch {
XCTFail(error.toString())
}
}
func testWrappingArray() {
struct Model {
let string: String
}
do {
let models = [Model(string: "A"), Model(string: "B"), Model(string: "C")]
let wrapped: [WrappedDictionary] = try wrap(models)
XCTAssertEqual(wrapped.count, 3)
try verify(dictionary: wrapped[0], againstDictionary: ["string" : "A"])
try verify(dictionary: wrapped[1], againstDictionary: ["string" : "B"])
try verify(dictionary: wrapped[2], againstDictionary: ["string" : "C"])
} catch {
XCTFail(error.toString())
}
}
func testSnakeCasedKeyWrapping() {
struct Model: WrapCustomizable {
var wrapKeyStyle: WrapKeyStyle { return .convertToSnakeCase }
let simple = "simple name"
let camelCased = "camel cased name"
let CAPITALIZED = "capitalized name"
let _underscored = "underscored name"
let center_underscored = "center underscored name"
let double__underscored = "double underscored name"
}
do {
try verify(dictionary: wrap(Model()), againstDictionary: [
"simple" : "simple name",
"camel_cased" : "camel cased name",
"capitalized" : "capitalized name",
"_underscored" : "underscored name",
"center_underscored" : "center underscored name",
"double__underscored" : "double underscored name"
])
} catch {
XCTFail(error.toString())
}
}
func testContext() {
struct NestedModel: WrapCustomizable {
let string = "String"
func wrap(context: Any?, dateFormatter: DateFormatter?) -> Any? {
XCTAssertEqual(context as! String, "Context")
return try? Wrapper(context: context, dateFormatter: dateFormatter).wrap(object: self)
}
func wrap(propertyNamed propertyName: String, originalValue: Any, context: Any?, dateFormatter: DateFormatter?) throws -> Any? {
XCTAssertEqual(context as! String, "Context")
return context
}
}
class Model: WrapCustomizable {
let string = "String"
let nestedArray = [NestedModel()]
let nestedDictionary = ["nested" : NestedModel()]
func wrap(context: Any?, dateFormatter: DateFormatter?) -> Any? {
XCTAssertEqual(context as! String, "Context")
return try? Wrapper(context: context, dateFormatter: dateFormatter).wrap(object: self)
}
func wrap(propertyNamed propertyName: String, originalValue: Any, context: Any?, dateFormatter: DateFormatter?) throws -> Any? {
XCTAssertEqual(context as! String, "Context")
return nil
}
}
do {
try verify(dictionary: wrap(Model(), context: "Context"), againstDictionary: [
"string" : "String",
"nestedArray" : [["string" : "Context"]],
"nestedDictionary" : ["nested" : ["string" : "Context"]]
])
} catch {
XCTFail(error.toString())
}
}
func testInheritance() {
class Superclass {
let string = "String"
}
class Subclass: Superclass {
let int = 22
}
do {
try verify(dictionary: wrap(Subclass()), againstDictionary: [
"string" : "String",
"int" : 22
])
} catch {
XCTFail(error.toString())
}
}
func testIgnoringClosureProperties() {
struct StringConvertible: CustomStringConvertible {
var description: String { return "(Function)" }
}
struct Model {
let closure = {}
let string = "(Function)"
let stringConvertible = StringConvertible()
}
do {
try verify(dictionary: wrap(Model()), againstDictionary: [
"string" : "(Function)",
"stringConvertible" : [:]
])
} catch {
XCTFail(error.toString())
}
}
}
// MARK: - Mocks
private protocol MockProtocol {
var constantString: String { get }
var mutableInt: Int { get set }
}
// MARK: - Utilities
private enum VerificationError: Error {
case arrayCountMismatch(Int, Int)
case dictionaryKeyMismatch([String], [String])
case cannotVerifyValue(Any)
case missingValueForKey(String)
case valueMismatchBetween(Any, Any)
}
extension VerificationError: CustomStringConvertible {
var description: String {
switch self {
case .arrayCountMismatch(let countA, let countB):
return "Array count mismatch: \(countA) vs \(countB)"
case .dictionaryKeyMismatch(let keysA, let keysB):
return "Dictionary key count mismatch: \(keysA) vs \(keysB)"
case .cannotVerifyValue(let value):
return "Cannot verify value: \(value)"
case .missingValueForKey(let key):
return "Missing expected value for key: \(key)"
case .valueMismatchBetween(let valueA, let valueB):
return "Values don't match: \(valueA) vs \(valueB)"
}
}
}
private protocol Verifiable {
static func convert(objectiveCObject: NSObject) -> Self?
var hashValue: Int { get }
}
extension Int: Verifiable {
fileprivate static func convert(objectiveCObject object: NSObject) -> Int? {
guard let number = object as? NSNumber else {
return nil
}
return number.intValue
}
}
extension Int64: Verifiable {
fileprivate static func convert(objectiveCObject object: NSObject) -> Int64? {
guard let number = object as? NSNumber else {
return nil
}
return number.int64Value
}
}
extension UInt64: Verifiable {
fileprivate static func convert(objectiveCObject object: NSObject) -> UInt64? {
guard let number = object as? NSNumber else {
return nil
}
return number.uint64Value
}
}
extension Double: Verifiable {
fileprivate static func convert(objectiveCObject object: NSObject) -> Double? {
guard let number = object as? NSNumber else {
return nil
}
return number.doubleValue
}
}
extension String: Verifiable {
fileprivate static func convert(objectiveCObject object: NSObject) -> String? {
guard let string = object as? NSString else {
return nil
}
#if os(Linux)
return nil
#else
return String(string)
#endif
}
}
extension Date: Verifiable {
fileprivate static func convert(objectiveCObject object: NSObject) -> Date? {
guard let date = object as? NSDate else {
return nil
}
return Date(timeIntervalSinceReferenceDate: date.timeIntervalSinceReferenceDate)
}
}
extension NSNumber: Verifiable {
fileprivate static func convert(objectiveCObject object: NSObject) -> Self? {
return nil
}
}
extension NSString: Verifiable {
fileprivate static func convert(objectiveCObject object: NSObject) -> Self? {
return nil
}
}
extension NSDate: Verifiable {
fileprivate static func convert(objectiveCObject object: NSObject) -> Self? {
return nil
}
}
private func verify(dictionary: WrappedDictionary, againstDictionary expectedDictionary: WrappedDictionary) throws {
if dictionary.count != expectedDictionary.count {
throw VerificationError.dictionaryKeyMismatch(Array(dictionary.keys), Array(expectedDictionary.keys))
}
for (key, expectedValue) in expectedDictionary {
guard let actualValue = dictionary[key] else {
throw VerificationError.missingValueForKey(key)
}
if let expectedNestedDictionary = expectedValue as? WrappedDictionary {
if let actualNestedDictionary = actualValue as? WrappedDictionary {
try verify(dictionary: actualNestedDictionary, againstDictionary: expectedNestedDictionary)
continue
} else {
throw VerificationError.valueMismatchBetween(actualValue, expectedValue)
}
}
if let expectedNestedArray = expectedValue as? [Any] {
if let actualNestedArray = actualValue as? [Any] {
try verify(array: actualNestedArray, againstArray: expectedNestedArray)
continue
} else {
throw VerificationError.valueMismatchBetween(actualValue, expectedValue)
}
}
try verify(value: actualValue, againstValue: expectedValue)
}
}
private func verify(array: [Any], againstArray expectedArray: [Any]) throws {
if array.count != expectedArray.count {
throw VerificationError.arrayCountMismatch(array.count, expectedArray.count)
}
for (index, expectedValue) in expectedArray.enumerated() {
let actualValue = array[index]
if let expectedNestedDictionary = expectedValue as? WrappedDictionary {
if let actualNestedDictionary = actualValue as? WrappedDictionary {
try verify(dictionary: actualNestedDictionary, againstDictionary: expectedNestedDictionary)
continue
} else {
throw VerificationError.valueMismatchBetween(actualValue, expectedValue)
}
}
if let expectedNestedArray = expectedValue as? [Any] {
if let actualNestedArray = actualValue as? [Any] {
try verify(array: actualNestedArray, againstArray: expectedNestedArray)
continue
} else {
throw VerificationError.valueMismatchBetween(actualValue, expectedValue)
}
}
try verify(value: actualValue, againstValue: expectedValue)
}
}
private func verify(value: Any, againstValue expectedValue: Any, convertToObjectiveCObjectIfNeeded: Bool = true) throws {
guard let expectedVerifiableValue = expectedValue as? Verifiable else {
throw VerificationError.cannotVerifyValue(expectedValue)
}
guard let actualVerifiableValue = value as? Verifiable else {
throw VerificationError.cannotVerifyValue(value)
}
if actualVerifiableValue.hashValue != expectedVerifiableValue.hashValue {
if convertToObjectiveCObjectIfNeeded {
if let objectiveCObject = value as? NSObject {
let expectedValueType = type(of: expectedVerifiableValue)
guard let convertedObject = expectedValueType.convert(objectiveCObject: objectiveCObject) else {
throw VerificationError.cannotVerifyValue(value)
}
return try verify(value: convertedObject, againstValue: expectedVerifiableValue, convertToObjectiveCObjectIfNeeded: false)
}
}
throw VerificationError.valueMismatchBetween(value, expectedValue)
}
}
private extension Error {
func toString() -> String {
return "\(self)"
}
}
|
1800214289e2187dfd8c4d6c19f51f69
| 28.00922 | 140 | 0.511269 | false | false | false | false |
Irvel/Actionable-Screenshots
|
refs/heads/master
|
ActionableScreenshots/ActionableScreenshots/DetailViewController.swift
|
gpl-3.0
|
1
|
//
// DetailViewController.swift
// ActionableScreenshots
//
// Created by Chuy Galvan on 10/21/17.
// Copyright © 2017 Jesus Galvan. All rights reserved.
//
import UIKit
import Photos
import RealmSwift
protocol UIWithCollection {
func reloadCollection()
}
class DetailViewController: UIViewController {
@IBOutlet weak var viewTextButton: UIButton!
@IBOutlet weak var imgView: UIImageView!
var screenshot: Screenshot?
var screenshotId: String!
var previousView: UIWithCollection!
override func viewDidLoad() {
super.viewDidLoad()
UIApplication.shared.statusBarStyle = UIStatusBarStyle.lightContent
if !screenshot!.hasText {
viewTextButton.isEnabled = false
viewTextButton.alpha = 0.45
}
let fetchOptions = PHImageRequestOptions()
fetchOptions.isSynchronous = true
self.imgView.image = screenshot?.getImage(width: imgView.superview!.frame.size.width, height: imgView.superview!.frame.size.height, contentMode: .aspectFit, fetchOptions: fetchOptions)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if(segue.identifier == "showTags") {
let destinationView = segue.destination as! TagsViewController
destinationView.screenshot = screenshot
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
UIApplication.shared.statusBarStyle = UIStatusBarStyle.default
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillDisappear(animated)
UIApplication.shared.statusBarStyle = UIStatusBarStyle.lightContent
}
@IBAction func unwindTagsView(segueUnwind: UIStoryboardSegue) {
}
// MARK: - Button actions
@IBAction func shareButtonTapped(_ sender: Any) {
let act = UIActivityViewController(activityItems: [self.imgView.image!], applicationActivities: nil)
act.popoverPresentationController?.sourceView = self.view
self.present(act, animated: true, completion: nil)
}
@IBAction func viewTextButtonTapped(_ sender: Any) {
if screenshot!.hasText {
let alertController = UIAlertController(title: "Recognized Text", message: screenshot!.text, preferredStyle: .alert)
let OKAction = UIAlertAction(title: "OK", style: .default) { action in }
alertController.addAction(OKAction)
self.present(alertController, animated: true) { }
}
}
@IBAction func deleteButtonTapped(_ sender: Any) {
self.screenshot?.deleteImageFromDevice()
dismiss(animated: true, completion: {
let realm = try! Realm()
try! realm.write {
realm.delete(self.screenshot!)
}
self.previousView.reloadCollection()
})
}
@IBAction func backButtonTapped(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
}
|
227438728cefbe37255c4688b2015eca
| 30.442308 | 192 | 0.6737 | false | false | false | false |
jangxyz/springy
|
refs/heads/master
|
springy-swift/springy_runner/main.swift
|
mit
|
1
|
#!/usr/bin/env xcrun swift -i
//
// main.swift
// springy_runner
//
// Created by 김장환 on 1/17/15.
// Copyright (c) 2015 김장환. All rights reserved.
//
import Foundation
func createTestGraph(#nodesNum:Int, #edgesNum:Int) -> Graph {
var graph = Graph()
// add 100 nodes
var edgeCandidate:[String] = []
for var i = 0; i < nodesNum; i++ {
let node = graph.newNode(["label": String(i)])
edgeCandidate.append(node.id);
}
func nodeName(node:Node) -> String {
return node.data["label"] ?? node.id
}
// add 1000 edges
for var i = 0; i < edgesNum; i++ {
// select source
//var randid:UInt32 = arc4random_uniform(edgeCandidate.count)
let rand1:Int = random() % edgeCandidate.count
var node1:Node = graph.nodeSet[edgeCandidate[rand1]]!
// println("node1: \(rand1) \(node1.description())")
// select target
var rand2:Int
do {
rand2 = random() % edgeCandidate.count
} while (rand2 == rand1)
var node2:Node = graph.nodeSet[edgeCandidate[rand2]]!
// println("node2: \(rand2) \(node2.description())")
var edge = graph.newEdge(source:node1, target:node2,
data:["label": "\(nodeName(node1)) --> \(nodeName(node2))"]
)
// hub
edgeCandidate.append(node1.id)
edgeCandidate.append(node2.id)
}
return graph
}
func importGraph(filename:String) -> Graph {
let fileContent = NSString(contentsOfFile: filename, encoding: NSUTF8StringEncoding, error: nil)
// parse JSON
var parseError: NSError?
let parsedObject: AnyObject? = NSJSONSerialization.JSONObjectWithData(
fileContent!.dataUsingEncoding(NSUTF8StringEncoding)!,
options: NSJSONReadingOptions.AllowFragments,
error: &parseError)
let data:JSON = JSON(parsedObject!)
//
var graph = Graph()
// add nodes
if data["nodes"] != nil {
var nodeNames = [String]()
for nodeData in data["nodes"].arrayValue {
var id = ""
if let _id1 = nodeData["id"].string {
id = _id1
} else if let _id2 = nodeData["id"].number {
id = "\(_id2)"
} else {
// let error = nodeData["id"].error
// println("error: \(error)")
}
nodeNames.append(id)
}
graph.addNodes(nodeNames)
}
// add edges
if data["edges"] != nil {
let edgeTuples = map(data["edges"].arrayValue) { (e) -> (String,String,[String:String]) in
var edgeData = [String:String]()
for (key:String,value:JSON) in e["data"] {
edgeData[key] = value.stringValue
}
return (e["source"]["id"].stringValue, e["target"]["id"].stringValue, edgeData)
}
graph.addEdges(edgeTuples)
}
return graph
}
func JSONStringify(value: AnyObject, prettyPrinted: Bool = false) -> String {
var options = prettyPrinted ? NSJSONWritingOptions.PrettyPrinted : nil
if NSJSONSerialization.isValidJSONObject(value) {
if let data = NSJSONSerialization.dataWithJSONObject(value, options: options, error: nil) {
if let string = NSString(data: data, encoding: NSUTF8StringEncoding) {
return string
}
}
}
return ""
}
func exportGraph(graph:Graph,
write:(JSON) -> () = {println($0)}) {
func buildNode(node:Node) -> [String:AnyObject] {
return [
"id": node.id,
"data": node.data
]
}
var data:[String:[AnyObject]] = [
"nodes": graph.nodes.map { buildNode($0) },
"edges": graph.edges.map { (edge) in
[
"id": edge.id,
"source": buildNode(edge.source),
"target": buildNode(edge.target),
"data": edge.data
]
}
]
let json:JSON = JSON(data)
write(json)
}
func importLayout(filename:String, graph:Graph) -> ForceDirectedLayout {
let fileContent = NSString(contentsOfFile: filename, encoding: NSUTF8StringEncoding, error: nil)
// parse JSON
var parseError: NSError?
let parsedObject: AnyObject? = NSJSONSerialization.JSONObjectWithData(
fileContent!.dataUsingEncoding(NSUTF8StringEncoding)!, options: NSJSONReadingOptions.AllowFragments, error: &parseError)
let data:JSON = JSON(parsedObject!)
let stiffness = data["stiffness"].doubleValue
let repulsion = data["repulsion"].doubleValue
let damping = data["damping"].doubleValue
let unitTime = data["unitTime"].doubleValue
let minEnergyThreshold = 0.01
var layout = ForceDirectedLayout(graph:graph,
stiffness:stiffness, repulsion:repulsion, damping:damping, energyThreshold:minEnergyThreshold, unitTime:unitTime)
func pointKey(point:Point) -> String {
return "[\(point.p.x), \(point.p.y), \(point.v.x), \(point.v.y)]"
}
// set node points
var nodePoints = [String:Point]()
var nodePointsIndexByPM = [String:Point]()
func buildPoint(_pointData:JSON) -> Point {
let pointData = _pointData.dictionaryValue
let p = pointData["p"]!.dictionaryValue
let position = Vector(x:p["x"]!.doubleValue, y:p["y"]!.doubleValue)
let v = pointData["v"]!.dictionaryValue
let velocity = Vector(x:v["x"]!.doubleValue, y:v["y"]!.doubleValue)
let mass = pointData["m"]!.doubleValue
let point = Point(p:position, m:mass)
point.v = velocity
return point
}
for (pointId:String, _pointData:JSON) in data["nodePoints"] {
let point = buildPoint(_pointData)
nodePoints[pointId] = point
nodePointsIndexByPM[pointKey(point)] = point
}
layout.nodePoints = nodePoints
// set edge springs
var edgeSprings = [String:Spring]()
for (edgeId:String, _springData:JSON) in data["edgeSprings"] {
let length = _springData["length"].doubleValue
let k = _springData["k"].doubleValue
let point1Key = pointKey(buildPoint(_springData["point1"]))
let point2Key = pointKey(buildPoint(_springData["point2"]))
let point1 = nodePointsIndexByPM[point1Key]!
let point2 = nodePointsIndexByPM[point2Key]!
edgeSprings[edgeId] = Spring(point1:point1, point2:point2, length:length, k:k)
}
layout.edgeSprings = edgeSprings
return layout
}
func exportLayout(layout:ForceDirectedLayout, write:(JSON -> ()) = {println($0)}) {
var data:[String:AnyObject] = [
"stiffness": layout.stiffness,
"repulsion": layout.repulsion,
"damping": layout.damping,
"unitTime": layout.unitTime,
"energy": layout.totalEnergy(),
"nodePoints": [String:AnyObject](),
"edgeSprings": [String:AnyObject]()
]
func buildPointData(point:Point) -> [String:AnyObject] {
return [
"p": [ "x": point.p.x, "y": point.p.y ],
"v": [ "x": point.v.x, "y": point.v.y ],
"m": point.m,
"a": [ "x": point.a.x, "y": point.a.y ]
]
}
func buildSpringData(spring:Spring) -> [String:AnyObject] {
return [
"point1": buildPointData(spring.point1),
"point2": buildPointData(spring.point2),
"length": spring.length,
"k": spring.k
]
}
func a2d<K,V>(tuples:[(K,V)]) -> [K:V] {
var dict = [K:V]()
for (key,value) in tuples {
dict[key] = value
}
return dict
}
func toDict<K,V,E>(array:[E], transform:E->(K,V)) -> [K:V] {
var dict = [K:V]()
for entity in array {
let (key,value) = transform(entity)
dict[key] = value
}
return dict
}
data["nodePoints"] = toDict(layout.eachNode) { ($0.id, buildPointData($1)) }
var edgeSprings = [String:AnyObject]()
for (i,spring) in enumerate(layout.eachSpring) {
edgeSprings[String(i)] = buildSpringData(spring)
}
data["edgeSprings"] = edgeSprings
write(JSON(data))
}
// create graph and layout
var graph:Graph
var layout:ForceDirectedLayout
// args
let args = NSProcessInfo.processInfo().arguments as NSArray
let args1 = /*"/Users/jangxyz/play/springy-swift/springy/data/20150101-123899_2_1/graph.json"*/args.count >= 2 ? args[1] as String : ""
let args2 = /*"/Users/jangxyz/play/springy-swift/springy/data/20150101-123899_2_1/layout_300.json"*/args.count >= 3 ? args[2] as String : ""
let fileManager = NSFileManager.defaultManager()
let files2 = fileManager.contentsOfDirectoryAtPath("./data/20150123-085804_10_20_400_400_0.3_0.01", error:nil)
if fileManager.fileExistsAtPath(args1) && fileManager.fileExistsAtPath(args2) {
let graphFilename = args1
let layoutFilename = args2
print("reading graph from \(graphFilename) ...")
graph = importGraph(graphFilename)
println(" done: \(graph.nodes.count), \(graph.edges.count)")
print("reading layout from \(layoutFilename) ...")
layout = importLayout(layoutFilename, graph)
println(" done.")
} else {
let nodesNum = args.count >= 2 ? args1.toInt()! : 100//10
let edgesNum = args.count >= 3 ? args2.toInt()! : 50//nodesNum * 2
//graph = createTestGraph(nodesNum:1000, edgesNum:2000)
graph = createTestGraph(nodesNum:nodesNum, edgesNum:edgesNum)
layout = ForceDirectedLayout(graph:graph,
stiffness: 400.0,
repulsion: 400,
damping: 0.5,
energyThreshold: 0.01,
unitTime: 0.01
)
}
let nodesNum = graph.nodes.count
let edgesNum = graph.edges.count
// E1 = 154285510.127098
//
// layout summary
println("---")
println("points: \(layout.eachNode.count)")
println("springs: \(layout.eachSpring.count)")
//println("Points")
//for (i,(node,point)) in enumerate(layout.eachNode) {
// println("- \(i+1): \(point)")
//}
//println("Springs")
//for (i,spring) in enumerate(layout.eachSpring) {
// println("- \(i+1): \(spring)")
//}
func writeToFile(filename:String) -> (JSON -> ()) {
return {(json:JSON) -> () in
json.rawString()!.writeToFile(filename, atomically: false, encoding: NSUTF8StringEncoding, error: nil)
return
}
}
let startDate = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "YYYYMMDD-HHmmSS"
let startDateStr = dateFormatter.stringFromDate(NSDate())
let testResultPath = "data/\(startDateStr)_\(nodesNum)_\(edgesNum)_\(layout.stiffness)_\(layout.repulsion)_\(layout.damping)_\(layout.unitTime)_swift"
var isDir:ObjCBool = true
if !fileManager.fileExistsAtPath(testResultPath, isDirectory:&isDir) {
fileManager.createDirectoryAtPath(testResultPath, withIntermediateDirectories:true, attributes: nil, error: nil)
}
// start
// onRender
var count = 0
var prevRunTime = startDate
func onRenderStart() {
//
exportGraph(graph, writeToFile("\(testResultPath)/graph.json"))
exportLayout(layout, writeToFile("\(testResultPath)/layout_\(count).json"))
}
func render() {
count += 1
func checkPrint(i:Int) -> Bool {
if (i <= 300) { return true } // DEBUG
//return false
if (i == 1) { return true }
if (i <= 100) { return true }
if (i > 30 && i <= 100 && i % 10 == 0) { return true }
if (i > 100 && i <= 1000 && i % 50 == 0) { return true }
if (i % 100 == 0) { return true }
return false
}
func checkSaveAt(i:Int) -> Bool {
if (i <= 300 && i % 10 == 0) { return true } // DEBUG
if (i < 10) { return true }
if (i == 10) { return true }
if (i == 100) { return true }
if (i % 1000 == 0) { return true }
if (i % 1000 == 300) { return true }
if (i % 1000 == 700) { return true }
return false
}
//
if checkPrint(count) {
let thisTime = NSDate()
println("- #\(count) energy: \(layout.totalEnergy()) (\(thisTime.timeIntervalSinceDate(prevRunTime)) s)")
prevRunTime = thisTime
}
if (checkSaveAt(count)) {
exportLayout(layout, writeToFile("\(testResultPath)/layout_\(count).json"))
}
}
func onRenderStop() {
// write layout
// text.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding, error: nil)
exportLayout(layout, writeToFile("\(testResultPath)/layout_\(count).json"))
// time
let end = NSDate()
println("done. took \(end.timeIntervalSinceDate(startDate)) seconds.")
}
//layout.start(render, onRenderStop:onRenderStop, onRenderStart:onRenderStart)
layout.start({}, onRenderStop:onRenderStop, onRenderStart:onRenderStart)
|
9a8d6ca0c5037fe1234278be940e861e
| 31.513924 | 150 | 0.596823 | false | false | false | false |
byu-oit-appdev/ios-byuSuite
|
refs/heads/dev
|
byuSuite/Apps/LockerRental/controller/LockerRentalMyLockersViewController.swift
|
apache-2.0
|
1
|
//
// LockerRentalMyLockersViewController.swift
// byuSuite
//
// Created by Erik Brady on 7/19/17.
// Copyright © 2017 Brigham Young University. All rights reserved.
//
protocol LockerRentalDelegate {
func loadLockers()
}
class LockerRentalMyLockersViewController: ByuViewController2, UITableViewDataSource, LockerRentalDelegate {
//MARK: Outlets
@IBOutlet private weak var tableView: UITableView!
@IBOutlet private weak var spinner: UIActivityIndicatorView!
@IBOutlet private weak var button: UIBarButtonItem!
//MARK: Properties
private var agreements = [LockerRentalAgreement]()
private var loadedLockerCount: Int = 0
override func viewDidLoad() {
super.viewDidLoad()
loadLockers()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.deselectSelectedRow()
}
//MARK: Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "myLockerDetail",
let vc = segue.destination as? LockerRentalMyLockersDetailViewController,
let sender = sender as? UITableViewCell,
let indexPath = tableView.indexPath(for: sender) {
vc.agreement = agreements[indexPath.row]
vc.delegate = self
} else if segue.identifier == "toBrowseLockers", let vc = segue.destination as? LockerRentalBuildingsViewController {
vc.delegate = self
}
}
//MARK: UITableViewDelegate/DataSource Methods
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if loadedLockerCount > 0 {
return "My Lockers"
}
return nil
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return loadedLockerCount
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(for: indexPath)
let agreement = agreements[indexPath.row]
if let building = agreement.locker?.building, let floor = agreement.locker?.floor, let number = agreement.locker?.displayedLockerNumber {
cell.textLabel?.text = "\(building) Floor \(floor) - \(number)"
}
cell.detailTextLabel?.text = "Expires on: \(agreement.expirationDateString())"
return cell
}
//MARK: IBAction Methods
@IBAction func browseAvailableLockersClicked(_ sender: Any) {
if agreements.count >= 3 {
super.displayAlert(error: nil, title: "Unable to Browse Lockers", message: "You have reached the maximum number of lockers you can rent.", alertHandler: nil)
} else {
self.performSegue(withIdentifier: "toBrowseLockers", sender: sender)
}
}
//MARK: LockerRental Delegate Methods
func loadLockers() {
//loadedLockerCount tracks the number of lockers loaded. It must be reset here because this method can be called later in the feature to reload lockers.
loadedLockerCount = 0
//Remove current rows from tableView
tableView.reloadData()
spinner.startAnimating()
LockerRentalClient.getAgreements { (agreements, error) in
if let agreements = agreements {
self.agreements = agreements
if self.agreements.count == 0 {
self.stopSpinnerIfReady()
self.tableView.tableFooterView?.isHidden = false
} else {
//Reset footer in the case that they just rented a first locker
self.tableView.tableFooterView?.isHidden = true
//Sort locker agreements by Expiration Date
self.agreements.sort()
//Load lockers for each agreement
for agreement in self.agreements {
if let lockerId = agreement.lockerId {
LockerRentalClient.getLocker(lockerId: lockerId, callback: { (locker, error) in
if let locker = locker {
agreement.locker = locker
self.loadedLockerCount += 1
self.tableView.reloadData()
self.stopSpinnerIfReady()
} else {
self.spinner.stopAnimating()
super.displayAlert(error: error)
}
})
}
}
}
} else {
super.displayAlert(error: error)
}
}
}
//MARK: Custom Methods
private func stopSpinnerIfReady() {
if agreements.count == loadedLockerCount {
spinner.stopAnimating()
button.isEnabled = true
}
}
}
|
63bc57152d04b7c1f292d8cf1ad16220
| 36.23913 | 169 | 0.578906 | false | false | false | false |
exponent/exponent
|
refs/heads/master
|
packages/expo-dev-menu/ios/DevMenuExpoSessionDelegate.swift
|
bsd-3-clause
|
2
|
// Copyright 2015-present 650 Industries. All rights reserved.
class DevMenuExpoSessionDelegate {
private static let sessionKey = "expo-dev-menu.session"
private static let userLoginEvent = "expo.dev-menu.user-login"
private static let userLogoutEvent = "expo.dev-menu.user-logout"
private let manager: DevMenuManager
init(manager: DevMenuManager) {
self.manager = manager
}
func setSessionAsync(_ session: [String: Any]?) throws {
var sessionSecret: String?
if session != nil {
guard let castedSessionSecret = session!["sessionSecret"] as? String else {
throw NSError(
domain: NSExceptionName.invalidArgumentException.rawValue,
code: 0,
userInfo: [
NSLocalizedDescriptionKey: "'sessionSecret' cannot be null."
]
)
}
sessionSecret = castedSessionSecret
}
setSesssionSecret(sessionSecret)
UserDefaults.standard.set(session, forKey: DevMenuExpoSessionDelegate.sessionKey)
}
@discardableResult
func restoreSession() -> [String: Any]? {
guard let session = UserDefaults.standard.dictionary(forKey: DevMenuExpoSessionDelegate.sessionKey) else {
return nil
}
setSesssionSecret(session["sessionSecret"] as? String)
return session
}
private func setSesssionSecret(_ sessionSecret: String?) {
let wasLoggedIn = manager.expoApiClient.isLoggedIn()
manager.expoApiClient.setSessionSecret(sessionSecret)
let isLoggedIn = manager.expoApiClient.isLoggedIn()
if !wasLoggedIn && isLoggedIn {
manager.sendEventToDelegateBridge(DevMenuExpoSessionDelegate.userLoginEvent, data: nil)
} else if wasLoggedIn && !isLoggedIn {
manager.sendEventToDelegateBridge(DevMenuExpoSessionDelegate.userLogoutEvent, data: nil)
}
}
}
|
db27960c4cd0ff8c0c0d60667494defa
| 31.745455 | 110 | 0.716824 | false | false | false | false |
SoCM/iOS-FastTrack-2014-2015
|
refs/heads/master
|
04-App Architecture/Swift 3/4-4 ResponderChain/Scenario 1/ResponderChainDemo/ResponderChainDemo/ViewController.swift
|
mit
|
4
|
//
// ViewController.swift
// ResponderChainDemo
//
// Created by Nicholas Outram on 15/01/2016.
// Copyright © 2016 Plymouth University. All rights reserved.
//
import UIKit
extension UIResponder {
func switchState(_ t : Int) -> Bool? {
guard let me = self as? UIView else {
return nil
}
for v in me.subviews {
if let sw = v as? UISwitch, v.tag == t {
return sw.isOn
}
}
return false
}
func printNextRepsonderAsString() {
var result : String = "\(type(of: self)) got a touch event."
if let nr = self.next {
result += " The next responder is " + type(of: nr).description()
} else {
result += " This class has no next responder"
}
print(result)
}
}
class ViewController: UIViewController {
@IBOutlet weak var passUpSwitch: UISwitch!
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.
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.printNextRepsonderAsString()
if passUpSwitch.isOn {
//Pass up the responder chain
super.touchesBegan(touches, with: event)
}
}
}
|
eadf7b85245ffb908fd076a188f2ff14
| 23.967213 | 80 | 0.572554 | false | false | false | false |
ckrey/mqttswift
|
refs/heads/master
|
Sources/MqttMessage.swift
|
gpl-3.0
|
1
|
//
// MqttMessage.swift
// mqttswift
//
// Created by Christoph Krey on 18.09.17.
//
//
import Foundation
class MqttMessage {
var topic: String!
var data: Data = Data()
var qos: MqttQoS = MqttQoS.AtMostOnce
var retain: Bool = false
var payloadFormatIndicator: UInt8? = nil
var publicationExpiryInterval : Int? = nil
var publicationExpiryTime : Date? = nil
var responseTopic: String? = nil
var correlationData: Data? = nil
var userProperties: [[String: String]]? = nil
var contentType: String? = nil
var topicAlias:Int? = nil
var subscriptionIdentifiers: [Int]? = nil
var packetIdentifier: Int? = nil
var pubrel: Bool = false
init () {
}
init(topic: String!,
data: Data!,
qos: MqttQoS!,
retain: Bool!) {
self.topic = topic
self.data = data
self.qos = qos
self.retain = retain
}
}
|
5f454e6610ec0f939c5a0ccd72301aa3
| 22.025 | 49 | 0.608035 | false | false | false | false |
wupengnash/WPWebImage
|
refs/heads/master
|
WPWebImage/Lib/WPWebImage/WPWebImage.swift
|
mit
|
1
|
//
// WPWebImage.swift
// ArtCircle
//
// Created by wupeng on 16/1/29.
//
//
import UIKit
import ImageIO
import MobileCoreServices
import AssetsLibrary
public enum CacheType {
case None, Memory, Disk
}
public typealias DownloadProgressBlock = ((receivedSize: Int64, totalSize: Int64) -> ())
public typealias CompletionHandler = ((image: UIImage?, error: NSError?, cacheType: CacheType, imageURL: NSURL?) -> ())
extension String {
func length() -> Int {
return self.characters.count
}
}
extension UIButton {
/**
渐变设置图片第二种方法
- parameter duration:
*/
func addTransition(duration:NSTimeInterval,transionStyle:WPCATransionStyle = .Fade) {
if self.layer.animationForKey(transionStyle.rawValue) == nil && transionStyle != .None {
let transition = CATransition()
transition.type = transionStyle.rawValue
transition.duration = duration
transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
self.layer.addAnimation(transition, forKey: transionStyle.rawValue)
}
}
func removeTransition(transionStyle:WPCATransionStyle = .Fade) {
if self.layer.animationForKey(transionStyle.rawValue) != nil {
self.layer.removeAnimationForKey(transionStyle.rawValue)
}
}
/**
自定义的异步加载图片
- parameter urlString: url
- parameter placeholderImage: 默认图
*/
func wp_setBackgroundImageWithURL(urlString: String,
forState state:UIControlState,
autoSetImage:Bool = true,
withTransformStyle transformStyle:WPCATransionStyle = .Fade,
duration:NSTimeInterval = 1.0,
placeholderImage: UIImage? = UIColor.imageWithColor(UIColor.randomColor()),
completionHandler:((image:UIImage) ->Void)? = nil) {
guard urlString != "" else {
self.setBackgroundImage(placeholderImage, forState: state)
return
}
if self.tag != urlString.hash {
//解决reloaddata的时候imageview 闪烁问题
self.tag = urlString.hash
self.setBackgroundImage(placeholderImage, forState: state)
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in
if WPCache.imageExistWithKey(urlString) {
WPCache.getDiskCacheObjectForKey(urlString, withSuccessHandler: { (image, key, filePath) -> Void in
if self.tag == urlString.hash {
if autoSetImage {
if filePath == "" {
//内存中取出
self.removeTransition()
self.setBackgroundImage(image, forState: state)
} else {
//硬盘中取出
switch transformStyle {
case .None:
self.removeTransition()
case .Fade:
self.addTransition(duration)
default:
self.removeTransition()
}
self.setBackgroundImage(image, forState: state)
}
if completionHandler != nil {
completionHandler!(image: image)
}
} else {
if completionHandler != nil {
completionHandler!(image: image)
}
}
}
})
} else {
if urlString.length() <= 0 {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.setBackgroundImage(placeholderImage, forState: state)
})
} else {
WPWebImage.downloadImage(urlString, withSuccessColsure: { (image, imageData,saveUrl) -> Void in
dispatch_async(dispatch_get_global_queue(0, 0), { () -> Void in
let newImage = WPWebImage.wp_animatedImageWithGIFData(gifData: imageData)
if self.tag == urlString.hash {
if autoSetImage {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
switch transformStyle {
case .Fade:
self.addTransition(duration)
self.setBackgroundImage(newImage, forState: state)
default:
self.removeTransition()
self.setBackgroundImage(newImage, forState: state)
}
})
}
WPCache.setDiskCacheObject(imageData, ForKey: urlString, withSuccessHandler: { (image, key, filePath) -> Void in
if completionHandler != nil {
completionHandler!(image: image)
}
})
}
})
})
}
}
}
}
}
extension UIColor {
static func randomColor() -> UIColor {
return UIColor(red: (CGFloat)(arc4random() % 254 + 1)/255.0, green: (CGFloat)(arc4random() % 254 + 1)/255.0, blue: (CGFloat)(arc4random() % 254 + 1)/255.0, alpha: CGFloat.max)
}
static func imageWithColor(imageColor:UIColor) -> UIImage {
let rect = CGRect(x: CGFloat.min, y: CGFloat.min, width: 1.0, height: 1.0)
UIGraphicsBeginImageContext(rect.size)
let context:CGContextRef = UIGraphicsGetCurrentContext()!
CGContextSetFillColorWithColor(context, imageColor.CGColor)
CGContextFillRect(context, rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
class WPCache: NSObject {
let userDefault = NSUserDefaults.standardUserDefaults()
class func setStickConversation(conversationID:String) {
WPCache.sharedInstance.userDefault.setObject(NSNumber(bool: true), forKey: "STICKY\(conversationID)")
}
class func getStickConversation(conversationID:String) -> Bool {
if let stick = WPCache.sharedInstance.userDefault.objectForKey("STICKY\(conversationID)") as? NSNumber {
return stick.boolValue
} else {
return false
}
}
class func desetStickConversation(conversationID:String) {
WPCache.sharedInstance.userDefault.setObject(NSNumber(bool: false), forKey: "STICKY\(conversationID)")
}
let defaultCache = NSCache()
static let sharedInstance = {
return WPCache()
}()
override init() {
super.init()
self.defaultMemoryCache.countLimit = 100
self.defaultMemoryCache.totalCostLimit = 80
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("terminateCleanDisk"), name: UIApplicationWillTerminateNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("cleanDisk"), name: UIApplicationDidEnterBackgroundNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("clearMemory"), name: UIApplicationDidReceiveMemoryWarningNotification, object: nil)
}
func clearMemory() {
self.defaultMemoryCache.removeAllObjects()
}
/**
清理磁盘缓存方法
- parameter expirCacheAge:
- parameter completionColsure:
*/
static func cleanDiskWithCompeletionColsure(expirCacheAge:NSInteger = WPCache.sharedInstance.maxCacheAge,completionColsure:(()->Void)? = nil) {
dispatch_async(dispatch_get_global_queue(0, 0)) { () -> Void in
let diskCacheurl = NSURL(fileURLWithPath: WPCache.sharedInstance.cacheDir, isDirectory: true)
let resourceKeys = [NSURLIsDirectoryKey,NSURLContentModificationDateKey,NSURLTotalFileAllocatedSizeKey]
let fileManager = NSFileManager.defaultManager()
let fileEnumerator = fileManager.enumeratorAtURL(diskCacheurl, includingPropertiesForKeys: resourceKeys, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles, errorHandler: nil)
var fileUrls = [NSURL]()
while let fileUrl = fileEnumerator?.nextObject() as? NSURL {
fileUrls.append(fileUrl)
}
let expirationDate = NSDate(timeIntervalSinceNow: -NSTimeInterval(expirCacheAge))
var urlsToDelegate = [NSURL]()
for (_,url) in fileUrls.enumerate() {
do {
let resourceValues = try url.resourceValuesForKeys(resourceKeys)
let moditfyDate = resourceValues[NSURLContentModificationDateKey] as! NSDate
if moditfyDate.laterDate(expirationDate) .isEqualToDate(expirationDate) {
urlsToDelegate.append(url)
}
} catch _ {}
}
for (_,deleteUrl) in urlsToDelegate.enumerate() {
do {
try fileManager.removeItemAtURL(deleteUrl)
print("删除照片:\(deleteUrl.absoluteString)")
} catch _ {}
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if completionColsure != nil {
completionColsure!()
}
})
}
}
func terminateCleanDisk() {
WPCache.cleanDiskWithCompeletionColsure(0, completionColsure: nil)
}
func cleanDisk() {
WPCache.cleanDiskWithCompeletionColsure()
}
/// 最大保留秒数7天
let maxCacheAge : NSInteger = 3600 * 7
let defaultMemoryCache = NSCache()
let defaultDiskCache = NSFileManager()
var diskCacheDirName = "" {
didSet {
self.cacheDir = NSTemporaryDirectory().stringByAppendingString("\(self.diskCacheDirName)/")
if !self.defaultDiskCache.fileExistsAtPath(self.diskCacheDirName) {
do {
try self.defaultDiskCache.createDirectoryAtPath(self.cacheDir, withIntermediateDirectories: true, attributes: nil)
} catch _ {}
}
}
}
var cacheDir = "" {
didSet {
}
}
static func imageExistWithKey(key:String) -> Bool {
if WPCache.sharedInstance.diskCacheDirName == "" {
WPCache.sharedInstance.diskCacheDirName = "defaultCache"
}
let filePath = WPCache.sharedInstance.cacheDir.stringByAppendingString("\(key.hashValue)")
return WPCache.sharedInstance.defaultDiskCache.fileExistsAtPath(filePath)
}
static func setDiskCacheObject(imageData:NSData , ForKey key:String ,withSuccessHandler successColsure:((image:UIImage,key:String,filePath:String) -> Void)) {
dispatch_async(dispatch_get_global_queue(0, 0)) { () -> Void in
if WPCache.sharedInstance.diskCacheDirName == "" {
WPCache.sharedInstance.diskCacheDirName = "defaultCache"
}
let filePath = WPCache.sharedInstance.cacheDir.stringByAppendingString("\(key.hashValue)")
let result = WPCache.sharedInstance.defaultDiskCache.createFileAtPath(filePath, contents: imageData, attributes: nil)
// let result = imageData.writeToFile(filePath, atomically: true)
if result {
print("写入成功,\(key),\(filePath)")
let image = WPWebImage.wp_animatedImageWithGIFData(gifData: imageData)
WPCache.sharedInstance.defaultMemoryCache.setObject(image!, forKey: key)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
successColsure(image: UIImage(data: imageData)!,key: key,filePath: filePath)
})
} else {
print("写入失败,\(key),\(filePath)")
}
}
}
static func getDiskCacheObjectForKey(key:String,withSuccessHandler successColsure:((image:UIImage,key:String,filePath:String) -> Void)) {
dispatch_async(dispatch_get_global_queue(0, 0)) { () -> Void in
if WPCache.sharedInstance.diskCacheDirName == "" {
WPCache.sharedInstance.diskCacheDirName = "defaultCache"
}
if WPCache.sharedInstance.defaultMemoryCache.objectForKey(key) != nil {
let image = WPCache.sharedInstance.defaultMemoryCache.objectForKey(key) as! UIImage
dispatch_async(dispatch_get_main_queue(), { () -> Void in
successColsure(image: image,key: key,filePath: "")
})
} else {
let filePath = WPCache.sharedInstance.cacheDir.stringByAppendingString("\(key.hashValue)")
let imageData = WPCache.sharedInstance.defaultDiskCache.contentsAtPath(filePath)
let image = WPWebImage.wp_animatedImageWithGIFData(gifData: imageData!)
WPCache.sharedInstance.defaultMemoryCache.setObject(image!, forKey: key)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
successColsure(image: image!,key: key,filePath: filePath)
})
}
}
}
}
class WPWebImage: NSObject {
/**
下载图片
- parameter urlString: 图片url
- parameter colsure: 回调
*/
class func downloadImage(urlString:String,withSuccessColsure colsure:(image:UIImage,imageData:NSData,url:String) -> Void) {
let url = NSURL(string: urlString)
let request = NSURLRequest(URL: url!)
let queue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request, queue: queue) { (response, data, error ) -> Void in
if data != nil {
let image = WPWebImage.wp_animatedImageWithGIFData(gifData: data!)
if image != nil {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
colsure(image: image!, imageData: data!,url: urlString)
})
}
}
}
}
/**
GIF适配
CG 框架是不会在ARC下被管理,因此此处GIF时会导致内存泄漏 20160401
证明在OC下确实如此 http://stackoverflow.com/questions/1263642/releasing-cgimage-cgimageref
Swift 下面被ARC自动管理释放 http://stackoverflow.com/questions/24900595/swift-cgpathrelease-and-arc
但是在GIF下面内存暴涨很厉害 ,GifU的解决方案:https://github.com/kaishin/Gifu/pull/55
解决方案描述:
Although the deinit block called displayLink.invalidate(), because the CADisplayLink was retaining the AnimatableImageView instance the view was never deallocated, its deinit block never executed, and .invalidate() was never called.
We can fix the retention cycle between AnimatableImageView and CADisplayLink by using another object as the target for the CADisplayLink instance, as described here.
自定义一个CADispaylink 手动管理
它自定义一个类继承自UIImageView,目前方法考虑UIImageView扩展模仿其实现方法重写
- parameter data:
- returns:
*/
class func wp_animatedImageWithGIFData(gifData data: NSData) -> UIImage! {
let options: NSDictionary = [kCGImageSourceShouldCache as String: NSNumber(bool: true), kCGImageSourceTypeIdentifierHint as String: kUTTypeGIF]
guard let imageSource = CGImageSourceCreateWithData(data as CFDataRef, options) else {
return nil
}
let frameCount = CGImageSourceGetCount(imageSource)
var images = [UIImage]()
let duration = 0.1 * Double(frameCount)
for i in 0 ..< frameCount {
guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, i, options) else {
return nil
}
images.append(UIImage(CGImage: imageRef, scale: UIScreen.mainScreen().scale, orientation: .Up))
}
if frameCount <= 1 {
return images.first
} else {
return UIImage.animatedImageWithImages(images, duration: duration)
}
}
}
public enum WPCATransionStyle : String {
case Fade = "kCATransitionFade"
case MoveIn = "kCATransitionMoveIn"
case Push = "kCATransitionPush"
case Reveal = "kCATransitionReveal"
case FromRight = "kCATransitionFromRight"
case FromLeft = "kCATransitionFromLeft"
case FromTop = "kCATransitionFromTop"
case FromBottom = "kCATransitionFromBottom"
case None = "None"
}
extension UIImageView {
/**
渐变设置图片第一种方法,tableview 上面有些卡顿
- parameter newImage:
- parameter duration:
*/
func transitionWithImage(newImage:UIImage,duration:NSTimeInterval) {
UIView.transitionWithView(self, duration: duration, options: UIViewAnimationOptions.TransitionCrossDissolve, animations: { () -> Void in
self.image = newImage
}) { (finish) -> Void in
}
}
/**
渐变设置图片第二种方法
- parameter duration:
*/
func addTransition(duration:NSTimeInterval,transionStyle:WPCATransionStyle = .Fade) {
if self.layer.animationForKey(transionStyle.rawValue) == nil && transionStyle != .None {
let transition = CATransition()
transition.type = transionStyle.rawValue
transition.duration = duration
transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
self.layer.addAnimation(transition, forKey: transionStyle.rawValue)
}
}
func removeTransition(transionStyle:WPCATransionStyle = .Fade) {
if self.layer.animationForKey(transionStyle.rawValue) != nil {
self.layer.removeAnimationForKey(transionStyle.rawValue)
}
}
func wp_setImageWithAsset(urlString: String,placeholderImage: UIImage?) {
self.tag = urlString.hash
self.image = placeholderImage
if WPCache.sharedInstance.defaultCache.objectForKey(urlString) != nil {
self.image = WPCache.sharedInstance.defaultCache.objectForKey(urlString) as? UIImage
} else {
dispatch_async(dispatch_get_global_queue(0, 0), { () -> Void in
let assetLib = ALAssetsLibrary()
assetLib.assetForURL(NSURL(string: urlString), resultBlock: { (asset) -> Void in
let cgImg = asset.defaultRepresentation().fullScreenImage().takeUnretainedValue()
let fullImage = UIImage(CGImage: cgImg)
if self.tag == urlString.hash {
WPCache.sharedInstance.defaultCache.setObject(fullImage, forKey: urlString)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.image = fullImage
})
}
}, failureBlock: { (error) -> Void in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.image = placeholderImage
})
})
})
}
}
func wp_setLoacalOrRemoteImageWith(urlString: String,withIsNotLocalPath remotePath:String,placeholderImage: UIImage?) {
if urlString.hasPrefix("http") {
self.wp_loadImageWithUrlString(NSURL(string: urlString)!, placeholderImage: placeholderImage)
} else if urlString.hasPrefix("/var") {
self.wp_setImageWithLocalPath(urlString, withIsNotLocalPath: remotePath,placeholderImage: placeholderImage)
}
}
func wp_setPreviewImageWithLocalPath(localPath:String, withIsNotLocalPath remotePath:String) {
self.tag = localPath.hashValue
dispatch_async(dispatch_get_global_queue(0, 0), { () -> Void in
if let image = UIImage(contentsOfFile: localPath) {
if self.tag == localPath.hashValue {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.image = image
})
}
} else {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.wp_loadPreviewImageWithUrlString(NSURL(string: remotePath)!, placeholderImage: UIImage(named: "DefaultPortraitIcon"))
})
}
})
}
/**
异步加载本地图片
- parameter localPath:
- parameter remotePath:
*/
func wp_setImageWithLocalPath(localPath:String, withIsNotLocalPath remotePath:String,placeholderImage: UIImage? = nil) {
self.tag = localPath.hashValue
dispatch_async(dispatch_get_global_queue(0, 0), { () -> Void in
if let image = UIImage(contentsOfFile: localPath) {
if self.tag == localPath.hashValue {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.image = image
})
}
} else {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.wp_loadImageWithUrlString(NSURL(string: remotePath)!, placeholderImage: UIImage(named: "DefaultPortraitIcon"))
})
}
})
}
/**
高效加圆角
- parameter urlString: url
- parameter placeholderImage: 默认图
*/
public func wp_roundImageWithURL(urlString:String,
placeholderImage: UIImage?)
{
self.wp_setImageWithURLString(urlString, autoSetImage: false, placeholderImage: placeholderImage) { [weak self] (image) -> Void in
self?.roundedImage(image)
}
}
func roundedImage(downloadImage:UIImage,withRect rect:CGRect = CGRect(x: CGFloat.min, y: CGFloat.min, width: 80, height: 80),withRadius radius:CGFloat = 10.0,completion:((roundedImage:UIImage) -> Void)? = nil) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in
UIGraphicsBeginImageContextWithOptions(rect.size, false, 1.0)
UIBezierPath(roundedRect: rect, cornerRadius: radius).addClip()
downloadImage.drawInRect(rect)
let roundedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.image = roundedImage
if completion != nil {
completion!(roundedImage: roundedImage)
}
})
}
}
}
extension UIImageView {
/**
预览照片的异步加载方法
- parameter url:
- parameter placeholderImage:
- parameter progressBlock:
- parameter completionHandler:
*/
func wp_loadPreviewImageWithUrlString(url: NSURL,
placeholderImage: UIImage?,
progressBlock:DownloadProgressBlock? = nil,
completionHandler: CompletionHandler? = nil) {
self.wp_loadImageWithUrlString(url, placeholderImage: placeholderImage, progressBlock: progressBlock, completionHandler: completionHandler)
}
/**
图片异步加载封装方法
- parameter url: 图片url
- parameter placeholderImage: 默认图
- parameter progressBlock: 进度回调
- parameter completionHandler: 完成时回调
*/
func wp_loadImageWithUrlString(url: NSURL,
placeholderImage: UIImage?,
progressBlock:DownloadProgressBlock? = nil,
completionHandler: CompletionHandler? = nil) {
self.wp_setImageWithURLString(url.absoluteString, autoSetImage: true, placeholderImage: placeholderImage) { (image) -> Void in
}
}
/**
自定义的异步加载图片
- parameter urlString: url
- parameter placeholderImage: 默认图
*/
func wp_setImageWithURLString(urlString: String,
autoSetImage:Bool = true,
withTransformStyle transformStyle:WPCATransionStyle = .Fade,
duration:NSTimeInterval = 1.0,
placeholderImage: UIImage? = UIColor.imageWithColor(UIColor.randomColor()),
completionHandler:((image:UIImage) ->Void)? = nil) {
guard urlString != "" else {
self.image = placeholderImage
return
}
if self.tag != urlString.hash {
//解决reloaddata的时候imageview 闪烁问题
self.tag = urlString.hash
self.image = placeholderImage
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in
if WPCache.imageExistWithKey(urlString) {
WPCache.getDiskCacheObjectForKey(urlString, withSuccessHandler: { (image, key, filePath) -> Void in
if self.tag == urlString.hash {
if autoSetImage {
if filePath == "" {
//内存中取出
self.removeTransition()
self.image = image
} else {
//硬盘中取出
switch transformStyle {
case .None:
self.removeTransition()
self.image = image
case .Fade:
self.addTransition(duration)
self.image = image
default:
self.removeTransition()
self.image = image
}
}
if completionHandler != nil {
completionHandler!(image: image)
}
} else {
if completionHandler != nil {
completionHandler!(image: image)
}
}
}
})
} else {
if urlString.length() <= 0 {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.image = placeholderImage
})
} else {
WPWebImage.downloadImage(urlString, withSuccessColsure: { (image, imageData,saveUrl) -> Void in
dispatch_async(dispatch_get_global_queue(0, 0), { () -> Void in
let newImage = WPWebImage.wp_animatedImageWithGIFData(gifData: imageData)
if self.tag == urlString.hash {
if autoSetImage {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
switch transformStyle {
case .Fade:
self.addTransition(duration)
self.image = newImage
default:
self.removeTransition()
self.image = newImage
}
})
}
WPCache.setDiskCacheObject(imageData, ForKey: urlString, withSuccessHandler: { (image, key, filePath) -> Void in
if completionHandler != nil {
completionHandler!(image: image)
}
})
}
})
})
}
}
}
}
}
|
b1e52afce3de47f622cae7e1014136a2
| 45.541195 | 237 | 0.54714 | false | false | false | false |
bettkd/Securus
|
refs/heads/master
|
Securus/LoginViewController.swift
|
gpl-2.0
|
1
|
//
// TimelineViewController.swift
// Securus
//
// Created by Dominic Bett on 11/16/15.
// Copyright © 2015 DominicBett. All rights reserved.
//
import UIKit
import Parse
class LoginViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var usernameField: UITextField!
@IBOutlet weak var passwordField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
self.usernameField.delegate = self
self.passwordField.delegate = self
// Do any additional setup after loading the view.
}
//Dismiss keyboard when touch outside -> resign first responder when textview is not touched
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?){
view.endEditing(true)
super.touchesBegan(touches, withEvent: event)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
@IBAction func unwindToLogInScreen(segue:UIStoryboardSegue) {
}
@IBAction func loginAction(sender: AnyObject) {
let username = self.usernameField.text?.lowercaseString
let password = self.passwordField.text
// Validate the text fields
if username!.characters.count < 5 {
let alert = UIAlertView(title: "Invalid", message: "Username must be greater than 5 characters", delegate: self, cancelButtonTitle: "OK")
alert.show()
} else if password!.characters.count < 6 {
let alert = UIAlertView(title: "Invalid", message: "Password must be greater than 8 characters", delegate: self, cancelButtonTitle: "OK")
alert.show()
} else {
// Run a spinner to show a task in progress
let spinner: UIActivityIndicatorView = UIActivityIndicatorView(frame: CGRectMake(0, 0, 150, 150)) as UIActivityIndicatorView
spinner.startAnimating()
// Send a request to login
PFUser.logInWithUsernameInBackground(username!, password: password!, block: { (user, error) -> Void in
// Stop the spinner
spinner.stopAnimating()
if ((user) != nil) {
let alert = UIAlertView(title: "Success", message: "Logged In", delegate: self, cancelButtonTitle: "OK")
alert.show()
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let viewController:UIViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("Timeline")
self.presentViewController(viewController, animated: true, completion: nil)
})
} else {
let alert = UIAlertView(title: "Error", message: "\(error)", delegate: self, cancelButtonTitle: "OK")
alert.show()
}
})
}
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
if textField == self.usernameField!{
self.passwordField.becomeFirstResponder()
} else if textField == self.passwordField {
loginAction(self)
}
return true
}
}
|
cfa3f8d5cf696453594a0a96949f2953
| 37.602041 | 153 | 0.604282 | false | false | false | false |
gali8/G8MaterialKitTextField
|
refs/heads/master
|
MKTextField/MKLabel.swift
|
mit
|
1
|
//
// MKLabel.swift
// MaterialKit
//
// Created by Le Van Nghia on 11/29/14.
// Copyright (c) 2014 Le Van Nghia. All rights reserved.
//
import UIKit
class MKLabel: UILabel {
@IBInspectable var maskEnabled: Bool = true {
didSet {
mkLayer.enableMask(maskEnabled)
}
}
@IBInspectable var rippleLocation: MKRippleLocation = .TapLocation {
didSet {
mkLayer.rippleLocation = rippleLocation
}
}
@IBInspectable var aniDuration: Float = 0.65
@IBInspectable var circleAniTimingFunction: MKTimingFunction = .Linear
@IBInspectable var backgroundAniTimingFunction: MKTimingFunction = .Linear
@IBInspectable var backgroundAniEnabled: Bool = true {
didSet {
if !backgroundAniEnabled {
mkLayer.enableOnlyCircleLayer()
}
}
}
@IBInspectable var circleGrowRatioMax: Float = 0.9 {
didSet {
mkLayer.circleGrowRatioMax = circleGrowRatioMax
}
}
@IBInspectable var cornerRadius: CGFloat = 2.5 {
didSet {
layer.cornerRadius = cornerRadius
mkLayer.setMaskLayerCornerRadius(cornerRadius)
}
}
// color
@IBInspectable var circleLayerColor: UIColor = UIColor(white: 0.45, alpha: 0.5) {
didSet {
mkLayer.setCircleLayerColor(circleLayerColor)
}
}
@IBInspectable var backgroundLayerColor: UIColor = UIColor(white: 0.75, alpha: 0.25) {
didSet {
mkLayer.setBackgroundLayerColor(backgroundLayerColor)
}
}
override var bounds: CGRect {
didSet {
mkLayer.superLayerDidResize()
}
}
private lazy var mkLayer: MKLayer = MKLayer(superLayer: self.layer)
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
private func setup() {
mkLayer.setCircleLayerColor(circleLayerColor)
mkLayer.setBackgroundLayerColor(backgroundLayerColor)
mkLayer.setMaskLayerCornerRadius(cornerRadius)
}
func animateRipple(location: CGPoint? = nil) {
if let point = location {
mkLayer.didChangeTapLocation(point)
} else if rippleLocation == .TapLocation {
rippleLocation = .Center
}
mkLayer.animateScaleForCircleLayer(0.65, toScale: 1.0, timingFunction: circleAniTimingFunction, duration: CFTimeInterval(aniDuration))
mkLayer.animateAlphaForBackgroundLayer(backgroundAniTimingFunction, duration: CFTimeInterval(aniDuration))
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesBegan(touches, withEvent: event)
if let firstTouch = touches.first {
let location = firstTouch.locationInView(self)
animateRipple(location)
}
}
}
|
588024032e7cfdb223ca4a55678a743f
| 30.135417 | 142 | 0.632653 | false | false | false | false |
jphacks/KM_03
|
refs/heads/master
|
iOS/LimitedSpace/LimitedSpace/Classes/Model/LimitedSpaceModel.swift
|
mit
|
1
|
//
// LimitedSpaceModel.swift
// LimitedSpace
//
// Copyright © 2015年 Ryunosuke Kirikihira. All rights reserved.
//
import Foundation
class LimitedSpaceModel :NSObject {
let itemId :Int
let title :String
let range :Int
let createDate :NSDate
var time :Int
init(title :String, range :Int, time :Int) {
self.title = title
self.range = range
self.time = time
self.createDate = NSDate()
self.itemId = 0
}
@objc required init(coder aDecoder :NSCoder) {
self.itemId = aDecoder.decodeIntegerForKey("itemId")
self.title = aDecoder.decodeObjectForKey("title") as? String ?? ""
self.range = aDecoder.decodeIntegerForKey("range")
self.createDate = aDecoder.decodeObjectForKey("createDate") as? NSDate ?? NSDate()
self.time = aDecoder.decodeIntegerForKey("time")
}
@objc func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeInteger(self.itemId, forKey: "itemId")
aCoder.encodeObject(self.title, forKey: "title")
aCoder.encodeInteger(self.range, forKey: "range")
aCoder.encodeObject(self.createDate, forKey: "createDate")
aCoder.encodeInteger(self.time, forKey: "time")
}
}
|
ac91a676061ea294f127a2da75bcdd2d
| 29.585366 | 90 | 0.644054 | false | false | false | false |
szehnder/AERecord
|
refs/heads/master
|
AERecordExample/DetailViewController.swift
|
mit
|
1
|
//
// DetailViewController.swift
// AERecordExample
//
// Created by Marko Tadic on 11/3/14.
// Copyright (c) 2014 ae. All rights reserved.
//
import UIKit
import CoreData
import AERecord
let yellow = UIColor(red: 0.969, green: 0.984, blue: 0.745, alpha: 1)
let blue = UIColor(red: 0.918, green: 0.969, blue: 0.984, alpha: 1)
class DetailViewController: CoreDataCollectionViewController {
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// setup UISplitViewController displayMode button
navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem()
navigationItem.leftItemsSupplementBackButton = true
// setup options button
let optionsButton = UIBarButtonItem(title: "Options", style: .Plain, target: self, action: "showOptions:")
self.navigationItem.rightBarButtonItem = optionsButton
// setup fetchedResultsController property
refreshFetchedResultsController()
}
// MARK: - CoreData
func showOptions(sender: AnyObject) {
let optionsAlert = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
optionsAlert.popoverPresentationController?.barButtonItem = self.navigationItem.rightBarButtonItem
let addFewAction = UIAlertAction(title: "Add Few", style: .Default) { (action) -> Void in
// create few objects
for i in 1...5 {
Event.createWithAttributes(["timeStamp" : NSDate()])
}
AERecord.saveContextAndWait()
}
let deleteAllAction = UIAlertAction(title: "Delete All", style: .Destructive) { (action) -> Void in
// delete all objects
Event.deleteAll()
AERecord.saveContextAndWait()
}
let updateAllAction = UIAlertAction(title: "Update All", style: .Default) { (action) -> Void in
if NSProcessInfo.instancesRespondToSelector("isOperatingSystemAtLeastVersion:") {
// >= iOS 8
// batch update all objects (directly in persistent store) then refresh objects in context
Event.batchUpdateAndRefreshObjects(properties: ["timeStamp" : NSDate()])
// note that if using NSFetchedResultsController you have to call performFetch after batch updating
self.performFetch()
} else {
// < iOS 8
println("Batch updating is new in iOS 8.")
// update all objects through context
if let events = Event.all() as? [Event] {
for e in events {
e.timeStamp = NSDate()
}
AERecord.saveContextAndWait()
}
}
}
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) -> Void in
self.dismissViewControllerAnimated(true, completion: nil)
}
optionsAlert.addAction(addFewAction)
optionsAlert.addAction(deleteAllAction)
optionsAlert.addAction(updateAllAction)
optionsAlert.addAction(cancelAction)
presentViewController(optionsAlert, animated: true, completion: nil)
}
func refreshFetchedResultsController() {
let sortDescriptors = [NSSortDescriptor(key: "timeStamp", ascending: true)]
let request = Event.createFetchRequest(sortDescriptors: sortDescriptors)
fetchedResultsController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: AERecord.defaultContext, sectionNameKeyPath: nil, cacheName: nil)
}
// MARK: - Collection View
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as CustomCollectionViewCell
self.configureCell(cell, atIndexPath: indexPath)
return cell
}
func configureCell(cell: CustomCollectionViewCell, atIndexPath indexPath: NSIndexPath) {
if let frc = fetchedResultsController {
if let event = frc.objectAtIndexPath(indexPath) as? Event {
cell.backgroundColor = event.selected ? yellow : blue
cell.textLabel.text = event.timeStamp.description
}
}
}
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
if let cell = collectionView.cellForItemAtIndexPath(indexPath) as? CustomCollectionViewCell {
// update value
if let frc = fetchedResultsController {
if let event = frc.objectAtIndexPath(indexPath) as? Event {
cell.backgroundColor = yellow
// deselect previous
if let previous = Event.firstWithAttribute("selected", value: true) as? Event {
previous.selected = false
AERecord.saveContextAndWait()
}
// select current and refresh timestamp
event.selected = true
event.timeStamp = NSDate()
AERecord.saveContextAndWait()
}
}
}
}
}
|
0fd38c08399a98099ecce2cc9d95ab02
| 40.378788 | 172 | 0.623398 | false | false | false | false |
ashfurrow/pragma-2015-rx-workshop
|
refs/heads/master
|
Session 2/Signup Demo/Signup Demo/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// Signup Demo
//
// Created by Ash Furrow on 2015-10-08.
// Copyright © 2015 Artsy. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import Moya
class ViewController: UIViewController {
@IBOutlet weak var emailAddressTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var submitButton: UIButton!
@IBOutlet weak var imageView: UIImageView!
var disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
let validEmail = emailAddressTextField.rx_text.map(isEmail)
let validPassword = passwordTextField.rx_text.map(isPassword)
combineLatest(validEmail, validPassword, and)
.bindTo(submitButton.rx_enabled)
submitButton.rx_tap.map { _ -> Observable<MoyaResponse> in
return provider.request(.Image)
}.flatMap() { obs in
return obs.filterSuccessfulStatusCodes()
.mapImage()
.catchError(self.presentError)
.filter({ (thing) -> Bool in
return thing != nil
})
}
.take(1)
.bindTo(imageView.rx_image)
.addDisposableTo(disposeBag)
}
}
func isEmail(string: String) -> Bool {
return string.characters.contains("@")
}
func isPassword(string: String) -> Bool {
return string.characters.count >= 6
}
func and(lhs: Bool, rhs: Bool) -> Bool {
return lhs && rhs
}
extension UIViewController {
func presentError(error: ErrorType) -> Observable<UIImage!> {
let alertController = UIAlertController(title: "Network Error", message: (error as NSError).localizedDescription, preferredStyle: .Alert)
alertController.addAction(UIAlertAction(title: "OK", style: .Default) { [weak self] _ -> Void in
self?.dismissViewControllerAnimated(true, completion: nil)
})
self.presentViewController(alertController, animated: true, completion: nil)
return just(nil)
}
}
|
3418a512fd72d5f92949e74d599060ab
| 26.44 | 145 | 0.647716 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.