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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
fredfoc/OpenWit | refs/heads/master | OpenWit/Classes/OpenWitMessageExtension.swift | mit | 1 | //
// OpenWitMessageExtension.swift
// OpenWit
//
// Created by fauquette fred on 24/11/16.
// Copyright © 2016 Fred Fauquette. All rights reserved.
//
import Foundation
import Moya
import ObjectMapper
// MARK: - an extension to handle message analyse
extension OpenWit {
/// get message recognition for WIT
///
/// - Parameters:
/// - message: a String with your message
/// - messageId: optional id of message
/// - threadId: optional thread of the message
/// - context: optional context of the message
/// - completion: completion closure
public func message(_ message: String,
messageId: String? = nil,
threadId: String? = nil,
context: Mappable? = nil,
completion: @escaping (_ result: OpenWitResult<OpenWitMessageModel, OpenWitError>) -> ()) {
guard let serviceManager = try? OpenWitServiceManager(WitToken: WITTokenAcces, serverToken: WITServerTokenAcces, isMocked: isMocked) else {
completion(OpenWitResult(failure: OpenWitError.tokenIsUndefined))
return
}
guard message.isNotTooLong else {
completion(OpenWitResult(failure: OpenWitError.messageTooLong))
return
}
_ = serviceManager.provider.requestObject(OpenWitService.message(apiVersion: apiVersion,
message: message,
messageId: messageId,
threadId: threadId,
context: context),
completion: completion)
}
}
| 1382327e19bcba6644944a3d7071f712 | 39.652174 | 147 | 0.520856 | false | false | false | false |
dnseitz/YAPI | refs/heads/master | YAPI/YAPITests/YelpV2PhoneSearchResponseTests.swift | mit | 1 | //
// YelpPhoneSearchResponseTests.swift
// YAPI
//
// Created by Daniel Seitz on 9/12/16.
// Copyright © 2016 Daniel Seitz. All rights reserved.
//
import XCTest
@testable import YAPI
class YelpPhoneSearchResponseTests: YAPIXCTestCase {
func test_ValidResponse_ParsedFromEncodedJSON() {
do {
let dict = try self.dictFromBase64(ResponseInjections.yelpValidPhoneSearchResponse)
let response = YelpV2SearchResponse(withJSON: dict)
XCTAssertNil(response.region)
XCTAssertNotNil(response.total)
XCTAssert(response.total == 2316)
XCTAssertNotNil(response.businesses)
XCTAssert(response.businesses!.count == 1)
XCTAssert(response.wasSuccessful == true)
XCTAssert(response.error == nil)
}
catch {
XCTFail()
}
}
func test_ErrorResponse_ParsedFromEncodedJSON() {
do {
let dict = try self.dictFromBase64(ResponseInjections.yelpErrorResponse)
let response = YelpV2SearchResponse(withJSON: dict)
XCTAssertNil(response.region)
XCTAssertNil(response.total)
XCTAssertNil(response.businesses)
XCTAssertNotNil(response.error)
guard case .invalidParameter(field: "location") = response.error! else {
return XCTFail("Wrong error type given: \(response.error!)")
}
XCTAssert(response.wasSuccessful == false)
}
catch {
XCTFail()
}
}
}
| dab954bffbd7295141ffde81a0945038 | 27.24 | 89 | 0.684136 | false | true | false | false |
nsafai/tipcalculator | refs/heads/master | calculator/TipViewController.swift | mit | 1 | //
// ViewController.swift
// calculator
//
// Created by Nicolai Safai on 1/23/16.
// Copyright © 2016 Lime. All rights reserved.
//
import UIKit
class TipViewController: UIViewController {
@IBOutlet weak var billAmountField: UITextField!
@IBOutlet weak var tipLabel: UILabel!
@IBOutlet weak var totalLabel: UILabel!
@IBOutlet weak var tipControl: UISegmentedControl!
@IBOutlet weak var whiteView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
billAmountField.becomeFirstResponder()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
let defaults = NSUserDefaults.standardUserDefaults()
tipControl.selectedSegmentIndex = defaults.integerForKey("default_tip_index") // visually change selected index if default has changed in defaults
onEdit(self) // update the tip amount if default tip % has been changed
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onEdit(sender: AnyObject) {
var tipPercentages = [0.1, 0.15, 0.2]
let chosenTip = tipPercentages[tipControl.selectedSegmentIndex]
if let billAmount = Double(billAmountField.text!) {
// print(billAmount)
let tipAmount = billAmount*chosenTip
let totalAmount = billAmount+tipAmount
tipLabel.text = String(format:"$%.2f", tipAmount)
totalLabel.text = String(format:"$%.2f", totalAmount)
// topView.center.x = topView.center.x+100
// billAmountField.center.y = billAmountField.center.y+100
} else {
tipLabel.text = ""
totalLabel.text = ""
}
}
@IBAction func onTap(sender: AnyObject) {
// view.endEditing(true)
}
}
| 0d73115d6d612d53a30d5fbe3ba481a0 | 29.909091 | 154 | 0.636275 | false | false | false | false |
rduan8/Aerial | refs/heads/master | Aerial/Source/Views/AerialView.swift | mit | 1 | //
// AerialView.swift
// Aerial
//
// Created by John Coates on 10/22/15.
// Copyright © 2015 John Coates. All rights reserved.
//
import Foundation
import ScreenSaver
import AVFoundation
import AVKit
@objc(AerialView) class AerialView : ScreenSaverView {
// var playerView: AVPlayerView!
var playerLayer:AVPlayerLayer!
var preferencesController:PreferencesWindowController?
static var players:[AVPlayer] = [AVPlayer]()
static var previewPlayer:AVPlayer?
static var previewView:AerialView?
var player:AVPlayer?
static let defaults:NSUserDefaults = ScreenSaverDefaults(forModuleWithName: "com.JohnCoates.Aerial")! as ScreenSaverDefaults
static var sharingPlayers:Bool {
defaults.synchronize();
return !defaults.boolForKey("differentDisplays");
}
static var sharedViews:[AerialView] = []
// MARK: - Shared Player
static var singlePlayerAlreadySetup:Bool = false;
class var sharedPlayer: AVPlayer {
struct Static {
static let instance: AVPlayer = AVPlayer();
static var _player:AVPlayer?;
static var player:AVPlayer {
if let activePlayer = _player {
return activePlayer;
}
_player = AVPlayer();
return _player!;
}
}
return Static.player;
}
// MARK: - Init / Setup
override init?(frame: NSRect, isPreview: Bool) {
super.init(frame: frame, isPreview: isPreview)
self.animationTimeInterval = 1.0 / 30.0
setup()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setup()
}
deinit {
debugLog("deinit AerialView");
NSNotificationCenter.defaultCenter().removeObserver(self);
// set player item to nil if not preview player
if player != AerialView.previewPlayer {
player?.rate = 0;
player?.replaceCurrentItemWithPlayerItem(nil);
}
guard let player = self.player else {
return;
}
// Remove from player index
let indexMaybe = AerialView.players.indexOf(player)
guard let index = indexMaybe else {
return;
}
AerialView.players.removeAtIndex(index);
}
func setupPlayerLayer(withPlayer player:AVPlayer) {
self.layer = CALayer()
guard let layer = self.layer else {
NSLog("Aerial Errror: Couldn't create CALayer");
return;
}
self.wantsLayer = true
layer.backgroundColor = NSColor.blackColor().CGColor
layer.delegate = self;
layer.needsDisplayOnBoundsChange = true;
layer.frame = self.bounds
// layer.backgroundColor = NSColor.greenColor().CGColor
debugLog("setting up player layer with frame: \(self.bounds) / \(self.frame)");
playerLayer = AVPlayerLayer(player: player);
if #available(OSX 10.10, *) {
playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
};
playerLayer.autoresizingMask = [CAAutoresizingMask.LayerWidthSizable, CAAutoresizingMask.LayerHeightSizable]
playerLayer.frame = layer.bounds;
layer.addSublayer(playerLayer);
}
func setup() {
var localPlayer:AVPlayer?
if (!self.preview) {
// check if we should share preview's player
if (AerialView.players.count == 0) {
if AerialView.previewPlayer != nil {
localPlayer = AerialView.previewPlayer;
}
}
}
else {
AerialView.previewView = self;
}
if AerialView.sharingPlayers {
AerialView.sharedViews.append(self);
}
if localPlayer == nil {
if AerialView.sharingPlayers {
if AerialView.previewPlayer != nil {
localPlayer = AerialView.previewPlayer
}
else {
localPlayer = AerialView.sharedPlayer;
}
}
else {
localPlayer = AVPlayer();
}
}
guard let player = localPlayer else {
NSLog("Aerial Error: Couldn't create AVPlayer!");
return;
}
self.player = player;
if (self.preview) {
AerialView.previewPlayer = player;
}
else if (AerialView.sharingPlayers == false) {
// add to player list
AerialView.players.append(player);
}
setupPlayerLayer(withPlayer: player);
if (AerialView.sharingPlayers == true && AerialView.singlePlayerAlreadySetup) {
self.playerLayer.player = AerialView.sharedViews[0].player
return;
}
AerialView.singlePlayerAlreadySetup = true;
ManifestLoader.instance.addCallback { (videos:[AerialVideo]) -> Void in
self.playNextVideo();
};
}
// MARK: - AVPlayerItem Notifications
func playerItemFailedtoPlayToEnd(aNotification: NSNotification) {
NSLog("AVPlayerItemFailedToPlayToEndTimeNotification \(aNotification)");
playNextVideo();
}
func playerItemNewErrorLogEntryNotification(aNotification: NSNotification) {
NSLog("AVPlayerItemNewErrorLogEntryNotification \(aNotification)");
}
func playerItemPlaybackStalledNotification(aNotification: NSNotification) {
NSLog("AVPlayerItemPlaybackStalledNotification \(aNotification)");
}
func playerItemDidReachEnd(aNotification: NSNotification) {
debugLog("played did reach end");
debugLog("notification: \(aNotification)");
playNextVideo()
debugLog("playing next video for player \(player)");
}
// MARK: - Playing Videos
func playNextVideo() {
let notificationCenter = NSNotificationCenter.defaultCenter()
// remove old entries
notificationCenter.removeObserver(self);
let player = AVPlayer()
// play another video
let oldPlayer = self.player
self.player = player
self.playerLayer.player = self.player
if self.preview {
AerialView.previewPlayer = player
}
debugLog("Setting player for all player layers in \(AerialView.sharedViews)");
for view in AerialView.sharedViews {
view.playerLayer.player = player
}
if (oldPlayer == AerialView.previewPlayer) {
AerialView.previewView?.playerLayer.player = self.player
}
let randomVideo = ManifestLoader.instance.randomVideo();
guard let video = randomVideo else {
NSLog("Aerial: Error grabbing random video!");
return;
}
let videoURL = video.url;
let asset = CachedOrCachingAsset(videoURL)
// let asset = AVAsset(URL: videoURL);
let item = AVPlayerItem(asset: asset);
player.replaceCurrentItemWithPlayerItem(item);
debugLog("playing video: \(video.url)");
if player.rate == 0 {
player.play();
}
guard let currentItem = player.currentItem else {
NSLog("Aerial Error: No current item!");
return;
}
debugLog("observing current item \(currentItem)");
notificationCenter.addObserver(self, selector: "playerItemDidReachEnd:", name: AVPlayerItemDidPlayToEndTimeNotification, object: currentItem);
notificationCenter.addObserver(self, selector: "playerItemNewErrorLogEntryNotification:", name: AVPlayerItemNewErrorLogEntryNotification, object: currentItem);
notificationCenter.addObserver(self, selector: "playerItemFailedtoPlayToEnd:", name: AVPlayerItemFailedToPlayToEndTimeNotification, object: currentItem);
notificationCenter.addObserver(self, selector: "playerItemPlaybackStalledNotification:", name: AVPlayerItemPlaybackStalledNotification, object: currentItem);
player.actionAtItemEnd = AVPlayerActionAtItemEnd.None;
}
// MARK: - Preferences
override func hasConfigureSheet() -> Bool {
return true;
}
override func configureSheet() -> NSWindow? {
if let controller = preferencesController {
return controller.window
}
let controller = PreferencesWindowController(windowNibName: "PreferencesWindow");
preferencesController = controller;
return controller.window;
}
} | 71190ca3c6a70edc2781b7ab0dddab77 | 30.333333 | 167 | 0.592564 | false | false | false | false |
dminones/reddit-ios-client | refs/heads/master | RedditIOSClient/Client/Listing.swift | mit | 1 | //
// Listing.swift
// RedditIOSClient
//
// Created by Dario Miñones on 4/5/17.
// Copyright © 2017 Dario Miñones. All rights reserved.
//
import Foundation
class Listing: NSObject, NSCoding {
var before: String?
var after: String?
var children = [Link]()
override init(){
super.init()
}
//MARK: NSCoding protocol methods
func encode(with aCoder: NSCoder){
aCoder.encode(self.before, forKey: "before")
aCoder.encode(self.after, forKey: "after")
aCoder.encode(self.children, forKey: "children")
}
required init(coder decoder: NSCoder) {
if let before = decoder.decodeObject(forKey: "before") as? String{
self.before = before
}
if let after = decoder.decodeObject(forKey: "after") as? String{
self.after = after
}
if let children = decoder.decodeObject(forKey: "children") as? [Link]{
self.children = children
}
}
init?(json: [String: Any]) {
if let after = json["after"] as? String? {
self.after = after
}
if let before = json["before"] as? String? {
self.before = before
}
if let children : [NSDictionary] = json["children"] as? [NSDictionary] {
var links = [Link]()
for item in children {
if let link = Link(json: item as! [String : Any]) {
links.append(link)
}
}
self.children = links
}
}
func addAfter(_ after: Listing) {
self.after = after.after
self.children.append(contentsOf: after.children)
}
}
| e8a18942b7ee7a056c1e9d010e474442 | 24.865672 | 80 | 0.533756 | false | false | false | false |
saraheolson/TechEmpathy-iOS | refs/heads/master | TechEmpathy/TechEmpathy/Models/Story.swift | apache-2.0 | 1 | //
// Story.swift
// TechEmpathy
//
// Created by Sarah Olson on 4/15/17.
// Copyright © 2017 SarahEOlson. All rights reserved.
//
import Foundation
enum StoryType: String {
case exclusion = "exclusion"
case inclusion = "inclusion"
case all = "all"
}
struct JSONKeys {
static let uuid = "uuid"
static let dateAdded = "dateAdded"
static let storyName = "storyName"
static let user = "user"
static let color = "color"
static let storyType = "storyType"
static let storyText = "storyText"
static let isApproved = "isApproved"
static let audio = "audio"
static let image = "image"
}
struct Story {
let key: String
let uuid: String
var user: String
let dateAdded: Date
var storyName: String
var color: String
var storyType: StoryType
let isApproved: Bool
var audio: String?
var image: String?
var storyText: String?
var isLampLit = false
/// Populating an existing story from JSON
init?(key: String, JSON: [String: Any?]) {
guard let nickname = JSON[JSONKeys.storyName] as? String,
let user = JSON[JSONKeys.user] as? String,
let color = JSON[JSONKeys.color] as? String,
let storyTypeString = JSON[JSONKeys.storyType] as? String,
let storyType = StoryType(rawValue: storyTypeString)
else {
return nil
}
self.key = key
self.storyName = nickname
self.user = user
self.color = color
self.storyType = storyType
if let dateAddedString = JSON[JSONKeys.dateAdded] as? String,
let dateAdded = Date.firebaseDate(fromString: dateAddedString) {
self.dateAdded = dateAdded
} else {
self.dateAdded = Date()
}
if let uuid = JSON[JSONKeys.uuid] as? String {
self.uuid = uuid
} else {
self.uuid = UUID().uuidString
}
if let approved = JSON[JSONKeys.isApproved] as? Bool {
self.isApproved = approved
} else {
self.isApproved = false
}
if let audio = JSON[JSONKeys.audio] as? String {
self.audio = audio
}
if let image = JSON[JSONKeys.image] as? String {
self.image = image
}
if let storyText = JSON[JSONKeys.storyText] as? String {
self.storyText = storyText
}
}
/// Creating a new story
init( key: String,
storyName: String,
user: String,
color: String,
storyType: StoryType,
audio: String?,
image: String?,
storyText: String?) {
self.key = key
self.dateAdded = Date()
self.storyName = storyName
self.user = user
self.color = color
self.storyType = storyType
self.audio = audio
self.image = image
self.storyText = storyText
self.uuid = UUID().uuidString
self.isApproved = false
}
func toJSON() -> [String: [String: Any]] {
return [key :
[JSONKeys.uuid: self.uuid,
JSONKeys.dateAdded: self.dateAdded.firebaseDateString(),
JSONKeys.storyName : self.storyName,
JSONKeys.user: self.user,
JSONKeys.color: self.color,
JSONKeys.storyType: storyType.rawValue,
JSONKeys.isApproved: self.isApproved,
JSONKeys.audio: audio ?? "",
JSONKeys.image: image ?? "",
JSONKeys.storyText: storyText ?? ""]]
}
}
| 339a638a5ce672df469a57036acfce68 | 27.873016 | 75 | 0.561847 | false | false | false | false |
salmojunior/TMDb | refs/heads/master | TMDb/TMDb/Source/Infrastructure/Extensions/ReachabilityExtension.swift | mit | 1 | //
// ReachabilityExtension.swift
// TMDb
//
// Created by SalmoJunior on 13/05/17.
// Copyright © 2017 Salmo Junior. All rights reserved.
//
import Reachability
extension Reachability {
// MARK: - Private Computed Properties
private static let defaultHost = "www.google.com"
private static var reachability = Reachability(hostName: defaultHost)
// MARK: - Public Functions
/// True value if there is a stable network connection
static var isConnected: Bool {
guard let reachability = Reachability.reachability else { return false }
return reachability.currentReachabilityStatus() != .NotReachable
}
/// Current network status based on enum NetworkStatus
static var status: NetworkStatus {
guard let reachability = Reachability.reachability else { return .NotReachable }
return reachability.currentReachabilityStatus()
}
}
| 035a24dca2a60b0e9e5c98ea1fbde5dc | 29.129032 | 88 | 0.690578 | false | false | false | false |
remaerd/Keys | refs/heads/master | Keys/Hash.swift | bsd-3-clause | 1 | //
// Hash.swift
// Keys
//
// Created by Sean Cheng on 8/9/15.
//
//
import Foundation
import CommonCrypto
public extension Data {
var MD2: Data {
var hash = [UInt8](repeating: 0, count: Int(CC_MD2_DIGEST_LENGTH))
var pointer : UnsafeRawPointer? = nil
withUnsafeBytes({ (ptr) in pointer = ptr.baseAddress })
CC_MD2(pointer, CC_LONG(count), &hash)
return Data(bytes: pointer!, count: Int(CC_MD2_DIGEST_LENGTH))
}
var MD4: Data {
var hash = [UInt8](repeating: 0, count: Int(CC_MD4_DIGEST_LENGTH))
var pointer : UnsafeRawPointer? = nil
withUnsafeBytes({ (ptr) in pointer = ptr.baseAddress })
CC_MD4(pointer, CC_LONG(count), &hash)
return Data(bytes: pointer!, count: Int(CC_MD4_DIGEST_LENGTH))
}
var MD5: Data {
var hash = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
var pointer : UnsafeRawPointer? = nil
withUnsafeBytes({ (ptr) in pointer = ptr.baseAddress })
CC_MD5(pointer, CC_LONG(count), &hash)
return Data(bytes: pointer!, count: Int(CC_MD5_DIGEST_LENGTH))
}
var SHA1: Data {
var hash = [UInt8](repeating: 0, count: Int(CC_SHA1_DIGEST_LENGTH))
var pointer : UnsafeRawPointer? = nil
withUnsafeBytes({ (ptr) in pointer = ptr.baseAddress })
CC_SHA1(pointer, CC_LONG(count), &hash)
return Data(bytes: pointer!, count: Int(CC_SHA1_DIGEST_LENGTH))
}
var SHA224: Data {
var hash = [UInt8](repeating: 0, count: Int(CC_SHA224_DIGEST_LENGTH))
var pointer : UnsafeRawPointer? = nil
withUnsafeBytes({ (ptr) in pointer = ptr.baseAddress })
CC_SHA224(pointer, CC_LONG(count), &hash)
return Data(bytes: pointer!, count: Int(CC_SHA224_DIGEST_LENGTH))
}
var SHA256: Data {
var hash = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
var pointer : UnsafeRawPointer? = nil
withUnsafeBytes({ (ptr) in pointer = ptr.baseAddress })
CC_SHA256(pointer, CC_LONG(count), &hash)
return Data(bytes: pointer!, count: Int(CC_SHA256_DIGEST_LENGTH))
}
var SHA384: Data {
var hash = [UInt8](repeating: 0, count: Int(CC_SHA384_DIGEST_LENGTH))
var pointer : UnsafeRawPointer? = nil
withUnsafeBytes({ (ptr) in pointer = ptr.baseAddress })
CC_SHA384(pointer, CC_LONG(count), &hash)
return Data(bytes: pointer!, count: Int(CC_SHA384_DIGEST_LENGTH))
}
var SHA512: Data {
var hash = [UInt8](repeating: 0, count: Int(CC_SHA512_DIGEST_LENGTH))
var pointer : UnsafeRawPointer? = nil
withUnsafeBytes({ (ptr) in pointer = ptr.baseAddress })
CC_SHA512(pointer, CC_LONG(count), &hash)
return Data(bytes: pointer!, count: Int(CC_SHA512_DIGEST_LENGTH))
}
}
public extension String {
var MD2: String? {
return String(digestData: hashData?.MD2, length: CC_MD2_DIGEST_LENGTH)
}
var MD4: String? {
return String(digestData: hashData?.MD4, length: CC_MD4_DIGEST_LENGTH)
}
var MD5: String? {
return String(digestData: hashData?.MD5, length: CC_MD5_DIGEST_LENGTH)
}
var SHA1: String? {
return String(digestData: hashData?.SHA1, length: CC_SHA1_DIGEST_LENGTH)
}
var SHA224: String? {
return String(digestData: hashData?.SHA224, length: CC_SHA224_DIGEST_LENGTH)
}
var SHA256: String? {
return String(digestData: hashData?.SHA256, length: CC_SHA256_DIGEST_LENGTH)
}
var SHA384: String? {
return String(digestData: hashData?.SHA384, length: CC_SHA384_DIGEST_LENGTH)
}
var SHA512: String? {
return String(digestData: hashData?.SHA512, length: CC_SHA512_DIGEST_LENGTH)
}
fileprivate var hashData: Data?
{
return data(using: String.Encoding.utf8, allowLossyConversion: false)
}
fileprivate init?(digestData: Data?, length: Int32) {
guard let digestData = digestData else { return nil }
var digest = [UInt8](repeating: 0, count: Int(length))
(digestData as NSData).getBytes(&digest, length: Int(length) * MemoryLayout<UInt8>.size)
var string = ""
for i in 0..<length {
string += String(format: "%02x", digest[Int(i)])
}
self.init(string)
}
}
| 61be190ba750ab86d4f546bf81620cc3 | 26.598639 | 92 | 0.663544 | false | false | false | false |
luowei/Swift-Samples | refs/heads/master | LWPickerLabel/ViewController.swift | apache-2.0 | 1 | //
// ViewController.swift
// LWPickerLabel
//
// Created by luowei on 16/8/5.
// Copyright © 2016年 wodedata. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet var textLabel: LWAddressLabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//let text = NSMutableAttributedString(string: "aaabbbb")
var main_string = "Hello World aaaaaaaaa aaaaaaaaa aaaaaaaaa aaaaaaaaa aaaaaaaaa aaaaaaaaa aaaaaaaaa bbbb aaaaaaaaa aaaaaaaaa"
var string_to_color = "bbbb"
var range = (main_string as NSString).rangeOfString(string_to_color)
var attributedString = NSMutableAttributedString(string:main_string)
// attributedString.addAttribute(
// NSForegroundColorAttributeName, value: UIColor.redColor() , range: NSRange(location: 0,length: 5))
attributedString.addAttributes([
NSForegroundColorAttributeName : UIColor.redColor(),
NSFontAttributeName : UIFont.systemFontOfSize(21)
], range: NSRange(location: 0,length: 5))
attributedString.addAttributes([
NSForegroundColorAttributeName : UIColor.redColor(),
NSFontAttributeName : UIFont.systemFontOfSize(30)
], range: range)
textLabel.attributedText = attributedString
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| a673d3f66a486754b52428650ef305e8 | 33.673913 | 134 | 0.672727 | false | false | false | false |
flodolo/firefox-ios | refs/heads/main | CredentialProvider/CredentialWelcomeViewController.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 UIKit
import Shared
protocol CredentialWelcomeViewControllerDelegate: AnyObject {
func credentialWelcomeViewControllerDidCancel()
func credentialWelcomeViewControllerDidProceed()
}
class CredentialWelcomeViewController: UIViewController {
var delegate: CredentialWelcomeViewControllerDelegate?
lazy private var logoImageView: UIImageView = {
let image = UIImageView(image: UIImage(named: "logo-glyph"))
image.translatesAutoresizingMaskIntoConstraints = false
return image
}()
lazy private var titleLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = .LoginsWelcomeViewTitle2
label.font = UIFont.systemFont(ofSize: 32, weight: .bold)
label.numberOfLines = 0
label.textAlignment = .center
return label
}()
lazy private var taglineLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = .LoginsWelcomeViewTagline
label.font = UIFont.systemFont(ofSize: 20)
label.numberOfLines = 0
label.textAlignment = .center
return label
}()
lazy private var cancelButton: UIButton = {
let button = UIButton(type: .system)
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle(.CancelString, for: .normal)
button.addTarget(self, action: #selector(self.cancelButtonTapped(_:)), for: .touchUpInside)
return button
}()
lazy private var proceedButton: UIButton = {
let button = UIButton(type: .custom)
button.translatesAutoresizingMaskIntoConstraints = false
button.backgroundColor = UIColor.Photon.Blue50
button.layer.cornerRadius = 8
button.setTitle(String.LoginsWelcomeTurnOnAutoFillButtonTitle, for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: .bold)
button.addTarget(self, action: #selector(proceedButtonTapped), for: .touchUpInside)
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.CredentialProvider.welcomeScreenBackgroundColor
view.addSubviews(cancelButton, logoImageView, titleLabel, taglineLabel, proceedButton)
NSLayoutConstraint.activate([
cancelButton.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor, constant: 10),
cancelButton.trailingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.trailingAnchor, constant: -20),
logoImageView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
logoImageView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor, multiplier: 0.4),
titleLabel.topAnchor.constraint(equalTo: logoImageView.bottomAnchor, constant: 40),
titleLabel.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
titleLabel.leadingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leadingAnchor, constant: 35, priority: .defaultHigh),
titleLabel.trailingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.trailingAnchor, constant: -35, priority: .defaultHigh),
titleLabel.widthAnchor.constraint(lessThanOrEqualToConstant: 440),
taglineLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 20),
taglineLabel.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
taglineLabel.leadingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leadingAnchor, constant: 35, priority: .defaultHigh),
taglineLabel.trailingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.trailingAnchor, constant: -35, priority: .defaultHigh),
taglineLabel.widthAnchor.constraint(lessThanOrEqualToConstant: 440),
proceedButton.bottomAnchor.constraint(equalTo: self.view.layoutMarginsGuide.bottomAnchor, constant: -20),
proceedButton.heightAnchor.constraint(equalToConstant: 44),
proceedButton.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
proceedButton.leadingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leadingAnchor, constant: 35, priority: .defaultHigh),
proceedButton.trailingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.trailingAnchor, constant: -35, priority: .defaultHigh),
proceedButton.widthAnchor.constraint(lessThanOrEqualToConstant: 360)
])
}
@objc func cancelButtonTapped(_ sender: UIButton) {
delegate?.credentialWelcomeViewControllerDidCancel()
}
@objc func proceedButtonTapped(_ sender: UIButton) {
delegate?.credentialWelcomeViewControllerDidProceed()
}
}
| 2fce0a40b1d374cffa0b5a84fedd638b | 47.776699 | 146 | 0.725717 | false | false | false | false |
volodg/iAsync.utils | refs/heads/master | Sources/Extensions/Data+ToString.swift | mit | 1 | //
// Data+ToString.swift
// iAsync_utils
//
// Created by Vladimir Gorbenko on 06.06.14.
// Copyright © 2014 EmbeddedSources. All rights reserved.
//
import Foundation
extension Data {
public func toString() -> String? {
return withUnsafeBytes { (bytes: UnsafePointer<UInt8>) in
let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: count)
buffer.assign(from: bytes, count: count)
let result = String(bytesNoCopy: buffer, length: count, encoding: .utf8, freeWhenDone: true)
return result
}
}
func hexString() -> String {
let bytesPointer = self.withUnsafeBytes { bytes in
return UnsafeBufferPointer<UInt8>(start: UnsafePointer(bytes), count: self.count)
}
let hexBytes = bytesPointer.map { return String(format: "%02hhx", $0) }
return hexBytes.joined()
}
public func apnsToString() -> String {
let result = hexString()
return result
}
}
| ef8aa4519d6fc3bafa9caf864d5baedd | 25.447368 | 104 | 0.625871 | false | false | false | false |
cloudofpoints/Pachinko | refs/heads/master | Pachinko/Model/Feature/FeatureVersion.swift | bsd-3-clause | 1 | //
// FeatureVersion.swift
// Pachinko
//
// Created by Tim Antrobus on 15/11/2015.
// Copyright © 2015 cloudofpoints. All rights reserved.
//
import Foundation
public func ==(lhs: FeatureVersion, rhs: FeatureVersion) -> Bool {
return lhs.hashValue == rhs.hashValue
}
public func <(lhs: FeatureVersion, rhs: FeatureVersion) -> Bool {
return lhs.major < rhs.major && lhs.minor < rhs.minor && lhs.patch < rhs.patch
}
public struct FeatureVersion: Hashable, Comparable {
public let major: Int
public let minor: Int
public let patch: Int
public var hashValue: Int {
return (31 &* major.hashValue) &+ minor.hashValue &+ patch.hashValue
}
public init(major: Int, minor: Int, patch: Int) {
self.major = major
self.minor = minor
self.patch = patch
}
public init?(version: String){
guard let versionTokens: [String] = version.componentsSeparatedByString(".") else {
return nil
}
if versionTokens.count != 3 {
return nil
}
guard let majorNum = Int(versionTokens[0]),
minorNum = Int(versionTokens[1]),
patchNum = Int(versionTokens[2]) else {
return nil
}
self.major = majorNum
self.minor = minorNum
self.patch = patchNum
}
public init?(major: String, minor: String, patch: String) {
if let majorNum = Int(major), minorNum = Int(minor), patchNum = Int(patch) {
self.major = majorNum
self.minor = minorNum
self.patch = patchNum
} else {
return nil
}
}
public func description() -> String {
return "\(major).\(minor).\(patch)"
}
} | d43fb79a86d0b654625e958c86e5a6ce | 25.761194 | 91 | 0.569196 | false | false | false | false |
RamonGilabert/Wall | refs/heads/master | Source/Models/Post.swift | mit | 2 | import Foundation
public protocol PostConvertible {
var wallModel: Post { get }
}
public class Post {
public var id = 0
public var publishDate = ""
public var text = ""
public var liked = false
public var seen = false
public var group = ""
public var likeCount = 0
public var seenCount = 0
public var commentCount = 0
public var author: Author?
public var reusableIdentifier = PostTableViewCell.reusableIdentifier
public var media: [Media]
// MARK: - Initialization
public init(id: Int, text: String = "", publishDate: String, author: Author? = nil,
media: [Media] = [], reusableIdentifier: String? = nil) {
self.id = id
self.text = text
self.publishDate = publishDate
self.author = author
self.media = media
if let reusableIdentifier = reusableIdentifier {
self.reusableIdentifier = reusableIdentifier
}
}
}
// MARK: - PostConvertible
extension Post: PostConvertible {
public var wallModel: Post {
return self
}
}
| 07c5acf149ec91514eec31be38de7940 | 20.702128 | 85 | 0.671569 | false | false | false | false |
Agarunov/FetchKit | refs/heads/master | Tests/QueryProtocolTests.swift | bsd-2-clause | 1 | //
// QueryProtocolTests.swift
// FetchKit
//
// Created by Anton Agarunov on 15.06.17.
//
//
import CoreData
@testable import FetchKit
import XCTest
// swiftlint:disable force_cast force_try force_unwrapping
internal class QueryProtocolTests: FetchKitTests {
func testFindFirst() {
let user = try! User.findFirst()
.sorted(by: #keyPath(User.firstName))
.execute(in: context)
XCTAssertEqual(user!.id, 3)
XCTAssertEqual(user!.firstName, "Alex")
XCTAssertEqual(user!.lastName, "Finch")
}
func testFindAll() {
let all = try! User.findAll().execute(in: context)
XCTAssertEqual(all.count, 5)
}
func testFindRange() {
let users = try! User.findRange(0..<2)
.sorted(by: #keyPath(User.firstName))
.sorted(by: #keyPath(User.lastName))
.execute(in: context)
let alex = users[0]
let ivan = users[1]
XCTAssertEqual(alex.id, 3)
XCTAssertEqual(alex.firstName, "Alex")
XCTAssertEqual(alex.lastName, "Finch")
XCTAssertEqual(ivan.id, 0)
XCTAssertEqual(ivan.firstName, "Ivan")
XCTAssertEqual(ivan.lastName, "Ivanov")
}
func testDeleteAll() {
let deleteCount = try! User.deleteAll()
.where(#keyPath(User.firstName), equals: "John")
.execute(in: context)
let newCount = try! User.getCount().execute(in: context)
XCTAssertEqual(deleteCount, 2)
XCTAssertEqual(newCount, 3)
}
func testAggregate() {
let result = try! User.aggregate(property: #keyPath(User.id), function: "min:")
.execute(in: context)
XCTAssertEqual(result as! Int64, 0)
}
func testGetMin() {
let result = try! User.getMin(property: #keyPath(User.id))
.execute(in: context)
XCTAssertEqual(result as! Int64, 0)
}
func testGetMax() {
let result = try! User.getMax(property: #keyPath(User.id))
.execute(in: context)
XCTAssertEqual(result as! Int64, 4)
}
func testGetDistinct() {
let result = try! User.getDistinct()
.propertiesToFetch([\User.firstName])
.group(by: \User.firstName)
.execute(in: context)
let nsdicts = result.map { NSDictionary(dictionary: $0) }
let expected: [NSDictionary] =
[["firstName": "Alex"], ["firstName": "Ivan"], ["firstName": "Joe"], ["firstName": "John"]]
XCTAssertEqual(nsdicts, expected)
}
func testFetchResults() {
let resultsController = try! User.fetchResults()
.group(by: #keyPath(User.firstName))
.sorted(by: #keyPath(User.firstName))
.sorted(by: #keyPath(User.lastName))
.execute(in: context)
XCTAssertEqual(resultsController.fetchedObjects!.count, 5)
XCTAssertEqual(resultsController.sections!.count, 4)
}
}
| 83272feeb403c04b41b64f2b0d37d7b1 | 29.414141 | 103 | 0.58718 | false | true | false | false |
LawrenceHan/Games | refs/heads/master | ZombieConga/ZombieConga/MyUtils.swift | mit | 1 | //
// MyUtils.swift
// ZombieConga
//
// Created by Hanguang on 3/28/16.
// Copyright © 2016 Hanguang. All rights reserved.
//
import Foundation
import CoreGraphics
import AVFoundation
func + (left: CGPoint, right: CGPoint) -> CGPoint {
return CGPoint(x: left.x + right.x, y: left.y + right.y)
}
func += (inout left: CGPoint, right: CGPoint) {
left = left + right
}
func - (left: CGPoint, right: CGPoint) -> CGPoint {
return CGPoint(x: left.x - right.x, y: left.y - right.y)
}
func -= (inout left: CGPoint, right: CGPoint) {
left = left - right
}
func * (left: CGPoint, right: CGPoint) -> CGPoint {
return CGPoint(x: left.x * right.x, y: left.y * right.y)
}
func *= (inout left: CGPoint, right: CGPoint) {
left = left * right
}
func * (point: CGPoint, scalar: CGFloat) -> CGPoint {
return CGPoint(x: point.x * scalar, y: point.y * scalar)
}
func *= (inout point: CGPoint, scalar: CGFloat) {
point = point * scalar
}
func / (left: CGPoint, right: CGPoint) -> CGPoint {
return CGPoint(x: left.x / right.x, y: left.y / right.y)
}
func /= (inout left: CGPoint, right: CGPoint) {
left = left / right
}
func / (point: CGPoint, scalar: CGFloat) -> CGPoint {
return CGPoint(x: point.x / scalar, y: point.y / scalar)
}
func /= (inout point: CGPoint, scalar: CGFloat) {
point = point / scalar
}
#if !(arch(x86_64) || arch(arm64))
func atan2(y: CGFloat, x: CGFloat) -> CGFloat {
return CGFloat(atan2f(Float(y), Float(x)))
}
func sqrt(a: CGFloat) -> CGFloat {
return CGFloat(sqrtf(Float(a)))
}
#endif
extension CGPoint {
func length() -> CGFloat {
return sqrt(x*x + y*y)
}
func normalized() -> CGPoint {
return self / length()
}
var angle: CGFloat {
return atan2(y, x)
}
}
let π = CGFloat(M_PI)
func shortestAngleBetween(angle1: CGFloat, angle2: CGFloat) -> CGFloat {
let twoπ = π * 2.0
var angle = (angle2 - angle1) % twoπ
if (angle >= π) {
angle = angle - twoπ
}
if (angle <= -π) {
angle = angle + twoπ
}
return angle
}
extension CGFloat {
func sign() -> CGFloat {
return (self >= 0.0) ? 1.0 : -1.0
}
}
extension CGFloat {
static func random() -> CGFloat {
return CGFloat(Float(arc4random()) / Float(UInt32.max))
}
static func random(min min: CGFloat, max: CGFloat) -> CGFloat {
assert(min < max)
return CGFloat.random() * (max - min) + min
}
}
var backgroundMusicPlayer: AVAudioPlayer!
func playBackgroundMusic(fileName: String) {
let resourceUrl = NSBundle.mainBundle().URLForResource(fileName, withExtension: nil)
guard let url = resourceUrl else {
print("Could not find file: \(fileName)")
return
}
do {
try backgroundMusicPlayer = AVAudioPlayer(contentsOfURL: url)
backgroundMusicPlayer.numberOfLoops = 1
backgroundMusicPlayer.prepareToPlay()
backgroundMusicPlayer.play()
} catch {
print("Could not create audio player!")
return
}
}
| 283d375b5400504f01975bd914148e3c | 21.536232 | 88 | 0.600322 | false | false | false | false |
hrscy/TodayNews | refs/heads/master | News/News/Classes/Home/Controller/HomeViewController.swift | mit | 1 | //
// HomeViewController.swift
// News
//
// Created by 杨蒙 on 2018/1/23.
// Copyright © 2018年 hrscy. All rights reserved.
//
import UIKit
import SGPagingView
import RxSwift
import RxCocoa
class HomeViewController: UIViewController {
/// 标题和内容
private var pageTitleView: SGPageTitleView?
private var pageContentView: SGPageContentView?
/// 自定义导航栏
private lazy var navigationBar = HomeNavigationView.loadViewFromNib()
private lazy var disposeBag = DisposeBag()
/// 添加频道按钮
private lazy var addChannelButton: UIButton = {
let addChannelButton = UIButton(frame: CGRect(x: screenWidth - newsTitleHeight, y: 0, width: newsTitleHeight, height: newsTitleHeight))
addChannelButton.theme_setImage("images.add_channel_titlbar_thin_new_16x16_", forState: .normal)
let separatorView = UIView(frame: CGRect(x: 0, y: newsTitleHeight - 1, width: newsTitleHeight, height: 1))
separatorView.theme_backgroundColor = "colors.separatorViewColor"
addChannelButton.addSubview(separatorView)
return addChannelButton
}()
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
UIApplication.shared.keyWindow?.theme_backgroundColor = "colors.windowColor"
// 设置状态栏属性
navigationController?.navigationBar.barStyle = .black
navigationController?.setNavigationBarHidden(false, animated: animated)
navigationController?.navigationBar.setBackgroundImage(UIImage(named: "navigation_background" + (UserDefaults.standard.bool(forKey: isNight) ? "_night" : "")), for: .default)
}
override func viewDidLoad() {
super.viewDidLoad()
// 设置 UI
setupUI()
// 点击事件
clickAction()
}
}
// MARK: - 导航栏按钮点击
extension HomeViewController {
/// 设置 UI
private func setupUI() {
view.theme_backgroundColor = "colors.cellBackgroundColor"
// 设置自定义导航栏
navigationItem.titleView = navigationBar
// 添加频道
view.addSubview(addChannelButton)
// 首页顶部新闻标题的数据
NetworkTool.loadHomeNewsTitleData {
// 向数据库中插入数据
NewsTitleTable().insert($0)
let configuration = SGPageTitleViewConfigure()
configuration.titleColor = .black
configuration.titleSelectedColor = .globalRedColor()
configuration.indicatorColor = .clear
// 标题名称的数组
self.pageTitleView = SGPageTitleView(frame: CGRect(x: 0, y: 0, width: screenWidth - newsTitleHeight, height: newsTitleHeight), delegate: self, titleNames: $0.compactMap({ $0.name }), configure: configuration)
self.pageTitleView!.backgroundColor = .clear
self.view.addSubview(self.pageTitleView!)
// 设置子控制器
_ = $0.compactMap({ (newsTitle) -> () in
switch newsTitle.category {
case .video: // 视频
let videoTableVC = VideoTableViewController()
videoTableVC.newsTitle = newsTitle
videoTableVC.setupRefresh(with: .video)
self.addChildViewController(videoTableVC)
case .essayJoke: // 段子
let essayJokeVC = HomeJokeViewController()
essayJokeVC.isJoke = true
essayJokeVC.setupRefresh(with: .essayJoke)
self.addChildViewController(essayJokeVC)
case .imagePPMM: // 街拍
let imagePPMMVC = HomeJokeViewController()
imagePPMMVC.isJoke = false
imagePPMMVC.setupRefresh(with: .imagePPMM)
self.addChildViewController(imagePPMMVC)
case .imageFunny: // 趣图
let imagePPMMVC = HomeJokeViewController()
imagePPMMVC.isJoke = false
imagePPMMVC.setupRefresh(with: .imageFunny)
self.addChildViewController(imagePPMMVC)
case .photos: // 图片,组图
let homeImageVC = HomeImageViewController()
homeImageVC.setupRefresh(with: .photos)
self.addChildViewController(homeImageVC)
case .jinritemai: // 特卖
let temaiVC = TeMaiViewController()
temaiVC.url = "https://m.maila88.com/mailaIndex?mailaAppKey=GDW5NMaKQNz81jtW2Yuw2P"
self.addChildViewController(temaiVC)
default :
let homeTableVC = HomeRecommendController()
homeTableVC.setupRefresh(with: newsTitle.category)
self.addChildViewController(homeTableVC)
}
})
// 内容视图
self.pageContentView = SGPageContentView(frame: CGRect(x: 0, y: newsTitleHeight, width: screenWidth, height: self.view.height - newsTitleHeight), parentVC: self, childVCs: self.childViewControllers)
self.pageContentView!.delegatePageContentView = self
self.view.addSubview(self.pageContentView!)
}
}
/// 点击事件
private func clickAction() {
// 搜索按钮点击
navigationBar.didSelectSearchButton = {
}
// 头像按钮点击
navigationBar.didSelectAvatarButton = { [weak self] in
self!.navigationController?.pushViewController(MineViewController(), animated: true)
}
// 相机按钮点击
navigationBar.didSelectCameraButton = {
}
/// 添加频道点击
addChannelButton.rx.controlEvent(.touchUpInside)
.subscribe(onNext: { [weak self] in
let homeAddCategoryVC = HomeAddCategoryController.loadStoryboard()
homeAddCategoryVC.modalSize = (width: .full, height: .custom(size: Float(screenHeight - (isIPhoneX ? 44 : 20))))
self!.present(homeAddCategoryVC, animated: true, completion: nil)
})
.disposed(by: disposeBag)
}
}
// MARK: - SGPageTitleViewDelegate
extension HomeViewController: SGPageTitleViewDelegate, SGPageContentViewDelegate {
/// 联动 pageContent 的方法
func pageTitleView(_ pageTitleView: SGPageTitleView!, selectedIndex: Int) {
self.pageContentView!.setPageContentViewCurrentIndex(selectedIndex)
}
/// 联动 SGPageTitleView 的方法
func pageContentView(_ pageContentView: SGPageContentView!, progress: CGFloat, originalIndex: Int, targetIndex: Int) {
self.pageTitleView!.setPageTitleViewWithProgress(progress, originalIndex: originalIndex, targetIndex: targetIndex)
}
}
| 3171df1290c2f64b37ae83add98684a4 | 42.379085 | 220 | 0.62257 | false | false | false | false |
devinross/curry | refs/heads/master | Examples/Examples/TextViewViewController.swift | mit | 1 | //
// TextViewViewController.swift
// Created by Devin Ross on 5/5/17.
//
/*
curry || https://github.com/devinross/curry
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
import UIKit
import curry
class TextViewViewController: UIViewController {
var textView : TKTextView!
var insetSlider : UISlider!
var textSizeSlider : UISlider!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.init(white: 0.9, alpha: 1)
self.edgesForExtendedLayout = .left
let textView = TKTextView(frame: CGRect(x: 0, y: 0, width: self.view.width, height: 200).insetBy(dx: 10, dy: 10))
textView.placeholder = "Placeholder"
textView.backgroundColor = UIColor.white
self.textView = textView
self.view.addSubview(textView)
let slider = UISlider(frame: CGRect(x: 0, y: textView.maxY + 10, width: self.view.width, height: 30).insetBy(dx: 20, dy: 0))
self.textSizeSlider = slider
slider.minimumValue = 10
slider.maximumValue = 30
slider.addEventHandler({ (sender) in
self.textView.font = UIFont.systemFont(ofSize: CGFloat(self.textSizeSlider.value))
}, for: .valueChanged)
self.view.addSubview(slider)
let insetSlider = UISlider(frame: CGRect(x: 0, y: slider.maxY + 10, width: self.view.width, height: 30).insetBy(dx: 20, dy: 0))
insetSlider.minimumValue = 0
insetSlider.maximumValue = 12
insetSlider.addEventHandler({ (sender) in
let inset = CGFloat(self.insetSlider.value)
self.textView.textContainerInset = UIEdgeInsets.init(top: inset, left: inset, bottom: inset, right: inset)
}, for: .valueChanged)
self.insetSlider = insetSlider
self.view.addSubview(self.insetSlider)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.textView.becomeFirstResponder()
}
}
| bf5ea31580e1e12f4c59a6244e3d02eb | 34.139241 | 129 | 0.753602 | false | false | false | false |
coach-plus/ios | refs/heads/master | Pods/YPImagePicker/Source/Pages/Gallery/LibraryMediaManager.swift | mit | 1 | //
// LibraryMediaManager.swift
// YPImagePicker
//
// Created by Sacha DSO on 26/01/2018.
// Copyright © 2018 Yummypets. All rights reserved.
//
import UIKit
import Photos
class LibraryMediaManager {
weak var v: YPLibraryView?
var collection: PHAssetCollection?
internal var fetchResult: PHFetchResult<PHAsset>!
internal var previousPreheatRect: CGRect = .zero
internal var imageManager: PHCachingImageManager?
internal var exportTimer: Timer?
internal var currentExportSessions: [AVAssetExportSession] = []
func initialize() {
imageManager = PHCachingImageManager()
resetCachedAssets()
}
func resetCachedAssets() {
imageManager?.stopCachingImagesForAllAssets()
previousPreheatRect = .zero
}
func updateCachedAssets(in collectionView: UICollectionView) {
let size = UIScreen.main.bounds.width/4 * UIScreen.main.scale
let cellSize = CGSize(width: size, height: size)
var preheatRect = collectionView.bounds
preheatRect = preheatRect.insetBy(dx: 0.0, dy: -0.5 * preheatRect.height)
let delta = abs(preheatRect.midY - previousPreheatRect.midY)
if delta > collectionView.bounds.height / 3.0 {
var addedIndexPaths: [IndexPath] = []
var removedIndexPaths: [IndexPath] = []
previousPreheatRect.differenceWith(rect: preheatRect, removedHandler: { removedRect in
let indexPaths = collectionView.aapl_indexPathsForElementsInRect(removedRect)
removedIndexPaths += indexPaths
}, addedHandler: { addedRect in
let indexPaths = collectionView.aapl_indexPathsForElementsInRect(addedRect)
addedIndexPaths += indexPaths
})
let assetsToStartCaching = fetchResult.assetsAtIndexPaths(addedIndexPaths)
let assetsToStopCaching = fetchResult.assetsAtIndexPaths(removedIndexPaths)
imageManager?.startCachingImages(for: assetsToStartCaching,
targetSize: cellSize,
contentMode: .aspectFill,
options: nil)
imageManager?.stopCachingImages(for: assetsToStopCaching,
targetSize: cellSize,
contentMode: .aspectFill,
options: nil)
previousPreheatRect = preheatRect
}
}
func fetchVideoUrlAndCrop(for videoAsset: PHAsset, cropRect: CGRect, callback: @escaping (URL) -> Void) {
let videosOptions = PHVideoRequestOptions()
videosOptions.isNetworkAccessAllowed = true
videosOptions.deliveryMode = .highQualityFormat
imageManager?.requestAVAsset(forVideo: videoAsset, options: videosOptions) { asset, _, _ in
do {
guard let asset = asset else { print("⚠️ PHCachingImageManager >>> Don't have the asset"); return }
let assetComposition = AVMutableComposition()
let trackTimeRange = CMTimeRangeMake(start: CMTime.zero, duration: asset.duration)
// 1. Inserting audio and video tracks in composition
guard let videoTrack = asset.tracks(withMediaType: AVMediaType.video).first,
let videoCompositionTrack = assetComposition
.addMutableTrack(withMediaType: .video,
preferredTrackID: kCMPersistentTrackID_Invalid) else {
print("⚠️ PHCachingImageManager >>> Problems with video track")
return
}
if let audioTrack = asset.tracks(withMediaType: AVMediaType.audio).first,
let audioCompositionTrack = assetComposition
.addMutableTrack(withMediaType: AVMediaType.audio,
preferredTrackID: kCMPersistentTrackID_Invalid) {
try audioCompositionTrack.insertTimeRange(trackTimeRange, of: audioTrack, at: CMTime.zero)
}
try videoCompositionTrack.insertTimeRange(trackTimeRange, of: videoTrack, at: CMTime.zero)
// Layer Instructions
let layerInstructions = AVMutableVideoCompositionLayerInstruction(assetTrack: videoCompositionTrack)
var transform = videoTrack.preferredTransform
transform.tx -= cropRect.minX
transform.ty -= cropRect.minY
layerInstructions.setTransform(transform, at: CMTime.zero)
// CompositionInstruction
let mainInstructions = AVMutableVideoCompositionInstruction()
mainInstructions.timeRange = trackTimeRange
mainInstructions.layerInstructions = [layerInstructions]
// Video Composition
let videoComposition = AVMutableVideoComposition(propertiesOf: asset)
videoComposition.instructions = [mainInstructions]
videoComposition.renderSize = cropRect.size // needed?
// 5. Configuring export session
let exportSession = AVAssetExportSession(asset: assetComposition,
presetName: YPConfig.video.compression)
exportSession?.outputFileType = YPConfig.video.fileType
exportSession?.shouldOptimizeForNetworkUse = true
exportSession?.videoComposition = videoComposition
exportSession?.outputURL = URL(fileURLWithPath: NSTemporaryDirectory())
.appendingUniquePathComponent(pathExtension: YPConfig.video.fileType.fileExtension)
// 6. Exporting
DispatchQueue.main.async {
self.exportTimer = Timer.scheduledTimer(timeInterval: 0.1,
target: self,
selector: #selector(self.onTickExportTimer),
userInfo: exportSession,
repeats: true)
}
self.currentExportSessions.append(exportSession!)
exportSession?.exportAsynchronously(completionHandler: {
DispatchQueue.main.async {
if let url = exportSession?.outputURL, exportSession?.status == .completed {
callback(url)
if let index = self.currentExportSessions.firstIndex(of:exportSession!) {
self.currentExportSessions.remove(at: index)
}
} else {
let error = exportSession?.error
print("error exporting video \(String(describing: error))")
}
}
})
} catch let error {
print("⚠️ PHCachingImageManager >>> \(error)")
}
}
}
@objc func onTickExportTimer(sender: Timer) {
if let exportSession = sender.userInfo as? AVAssetExportSession {
if let v = v {
if exportSession.progress > 0 {
v.updateProgress(exportSession.progress)
}
}
if exportSession.progress > 0.99 {
sender.invalidate()
v?.updateProgress(0)
self.exportTimer = nil
}
}
}
func forseCancelExporting() {
for s in self.currentExportSessions {
s.cancelExport()
}
}
}
| fd269f643be1cc19884acb65586b562e | 46 | 116 | 0.543343 | false | false | false | false |
muukii/PhotosPicker | refs/heads/master | PhotosPicker/Sources/PhotosPickerAssetsSectionView.swift | mit | 2 | // PhotosPickerAssetsSectionView
//
// Copyright (c) 2015 muukii
//
// 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
public class PhotosPickerAssetsSectionView: UICollectionReusableView {
override init(frame: CGRect) {
super.init(frame: frame)
self.setup()
self.setAppearance()
}
public required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public class func sizeForSection(#collectionView: UICollectionView) -> CGSize {
return CGSize(width: collectionView.bounds.width, height: 30)
}
public weak var sectionTitleLabel: UILabel?
public var section: DayPhotosPickerAssets? {
get {
return _section
}
set {
_section = newValue
if let section = newValue {
struct Static {
static var formatter: NSDateFormatter = {
let formatter = NSDateFormatter()
formatter.dateStyle = NSDateFormatterStyle.ShortStyle
return formatter
}()
}
self.sectionTitleLabel?.text = Static.formatter.stringFromDate(section.date)
}
}
}
public func setup() {
let sectionTitleLabel = UILabel()
sectionTitleLabel.setTranslatesAutoresizingMaskIntoConstraints(false)
self.addSubview(sectionTitleLabel)
self.setTranslatesAutoresizingMaskIntoConstraints(false)
self.sectionTitleLabel = sectionTitleLabel
let views = [
"sectionTitleLabel": sectionTitleLabel
]
self.addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat(
"|-(10)-[sectionTitleLabel]-(10)-|", options: NSLayoutFormatOptions.allZeros, metrics: nil, views: views
)
)
self.addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat(
"V:|-[sectionTitleLabel]-|", options: NSLayoutFormatOptions.AlignAllCenterY, metrics: nil, views: views
)
)
}
public func setAppearance() {
self.backgroundColor = UIColor.whiteColor()
}
private var _section: DayPhotosPickerAssets?
}
| 81b8658d9f06dc46ff1aaf5970f5b0dc | 32.980198 | 120 | 0.638695 | false | false | false | false |
lightbluefox/rcgapp | refs/heads/master | IOS App/RCGApp/RCGApp/AppDelegate.swift | gpl-2.0 | 1 | //
// AppDelegate.swift
// RCGApp
//
// Created by iFoxxy on 12.05.15.
// Copyright (c) 2015 LightBlueFox. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: true);
var itemsReceiver = NewsAndVacanciesReceiver()
//itemsReceiver.getAllNews();
//itemsReceiver.getAllVacancies();
var newsStack = itemsReceiver.newsStack;
var vacStack = itemsReceiver.vacStack
let navBarFont = UIFont(name: "Roboto-Regular", size: 17.0) ?? UIFont.systemFontOfSize(17.0);
var navBar = UINavigationBar.appearance();
var tabBar = UITabBar.appearance();
//UITabBar.appearance().backgroundImage = UIImage(named: "selectedItemImage");
if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) //Для iOS 7 и старше
{
navBar.barTintColor = UIColor(red: 194/255, green: 0, blue: 18/255, alpha: 1.0);
tabBar.barTintColor = UIColor(red: 194/255, green: 0, blue: 18/255, alpha: 1.0);
tabBar.tintColor = UIColor.whiteColor();
}
else //ниже iOS 7
{
navBar.tintColor = UIColor(red: 194/255, green: 0, blue: 18/255, alpha: 1.0);
tabBar.tintColor = UIColor(red: 194/255, green: 0, blue: 18/255, alpha: 1.0);
}
//Стиль заголовка
navBar.titleTextAttributes = [NSFontAttributeName: navBarFont, NSForegroundColorAttributeName: UIColor.whiteColor()];
//Чтобы избавиться от стандартного выделения выбранного таба, используем такой костыль.
tabBar.selectionIndicatorImage = UIImage(named: "selectedItemImage");
//Mark: Регистрация на пуш-уведомления
//IOS 7 -
UIApplication.sharedApplication().registerForRemoteNotificationTypes(UIRemoteNotificationType.Alert | UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound);
//IOS 8 +
//UIApplication.sharedApplication().registerUserNotificationSettings(UIUserNotificationType.Sound | UIUserNotificationType.Badge | UIUserNotificationType.Alert);
//UIApplication.sharedApplication().registerUserNotificationSettings(notificationSettings: UIUserNotificationSettings.Sound | UIUserNotificationType.Badge | UIUserNotificationType.Alert)
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 15a29b5e619c1654b77a04e4beba4716 | 49.54023 | 285 | 0.712304 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | refs/heads/master | Modules/Platform/Sources/PlatformKit/Coincore/Account/Fiat/PaymentMethodAccount.swift | lgpl-3.0 | 1 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Combine
import DIKit
import MoneyKit
import RxSwift
import ToolKit
// swiftformat:disable all
/// A type that represents a payment method as a `BlockchainAccount`.
public final class PaymentMethodAccount: FiatAccount {
public let paymentMethodType: PaymentMethodType
public let paymentMethod: PaymentMethod
public let priceService: PriceServiceAPI
public let accountType: AccountType
public init(
paymentMethodType: PaymentMethodType,
paymentMethod: PaymentMethod,
priceService: PriceServiceAPI = resolve()
) {
self.paymentMethodType = paymentMethodType
self.paymentMethod = paymentMethod
self.priceService = priceService
accountType = paymentMethod.isCustodial ? .trading : .nonCustodial
}
public let isDefault: Bool = false
public var activity: AnyPublisher<[ActivityItemEvent], Error> {
.just([]) // no activity to report
}
public var fiatCurrency: FiatCurrency {
guard let fiatCurrency = paymentMethodType.currency.fiatCurrency else {
impossible("Payment Method Accounts should always be denominated in fiat.")
}
return fiatCurrency
}
public var canWithdrawFunds: Single<Bool> {
.just(false)
}
public var identifier: AnyHashable {
paymentMethodType.id
}
public var label: String {
paymentMethodType.label
}
public var isFunded: AnyPublisher<Bool, Error> {
.just(true)
}
public var balance: AnyPublisher<MoneyValue, Error> {
.just(paymentMethodType.balance)
}
public func can(perform action: AssetAction) -> AnyPublisher<Bool, Error>{
.just(action == .buy)
}
public var pendingBalance: AnyPublisher<MoneyValue, Error> {
balance
}
public var actionableBalance: AnyPublisher<MoneyValue, Error> {
balance
}
public var receiveAddress: AnyPublisher<ReceiveAddress, Error> {
.failure(ReceiveAddressError.notSupported)
}
public func balancePair(
fiatCurrency: FiatCurrency,
at time: PriceTime
) -> AnyPublisher<MoneyValuePair, Error> {
balancePair(
priceService: priceService,
fiatCurrency: fiatCurrency,
at: time
)
}
public func invalidateAccountBalance() {
// NO-OP
}
}
| b355f7c2aeaea0db45455ec5174d8881 | 25.290323 | 87 | 0.667485 | false | false | false | false |
CoderYLiu/30DaysOfSwift | refs/heads/master | Project 18 - LimitCharacters/LimitCharacters/ViewController.swift | mit | 1 | //
// ViewController.swift
// LimitCharacters <https://github.com/DeveloperLY/30DaysOfSwift>
//
// Created by Liu Y on 16/4/24.
// Copyright © 2016年 DeveloperLY. All rights reserved.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
import UIKit
class ViewController: UIViewController, UITextFieldDelegate, UITextViewDelegate {
@IBOutlet weak var tweetTextView: UITextView!
@IBOutlet weak var bottomUIView: UIView!
@IBOutlet weak var avatarImageView: UIImageView!
@IBOutlet weak var characterCountLabel: UILabel!
override var preferredStatusBarStyle : UIStatusBarStyle {
return UIStatusBarStyle.lightContent
}
override func viewDidLoad() {
super.viewDidLoad()
tweetTextView.delegate = self
avatarImageView.layer.cornerRadius = avatarImageView.frame.width / 2
tweetTextView.backgroundColor = UIColor.clear
NotificationCenter.default.addObserver(self, selector:#selector(ViewController.keyBoardWillShow(_:)), name:NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector:#selector(ViewController.keyBoardWillHide(_:)), name:NSNotification.Name.UIKeyboardWillHide, object: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
let myTextViewString = tweetTextView.text
characterCountLabel.text = "\(140 - (myTextViewString?.characters.count)!)"
if range.length > 140{
return false
}
let newLength = (myTextViewString?.characters.count)! + range.length
return newLength < 140
}
func keyBoardWillShow(_ note:Notification) {
let userInfo = note.userInfo
let keyBoardBounds = (userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
let duration = (userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
let deltaY = keyBoardBounds.size.height
let animations:(() -> Void) = {
self.bottomUIView.transform = CGAffineTransform(translationX: 0,y: -deltaY)
}
if duration > 0 {
let options = UIViewAnimationOptions(rawValue: UInt((userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).intValue << 16))
UIView.animate(withDuration: duration, delay: 0, options:options, animations: animations, completion: nil)
}else {
animations()
}
}
func keyBoardWillHide(_ note:Notification) {
let userInfo = note.userInfo
let duration = (userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
let animations:(() -> Void) = {
self.bottomUIView.transform = CGAffineTransform.identity
}
if duration > 0 {
let options = UIViewAnimationOptions(rawValue: UInt((userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).intValue << 16))
UIView.animate(withDuration: duration, delay: 0, options:options, animations: animations, completion: nil)
}else{
animations()
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
}
}
| 9de51dc92dbd380a1759541a5148ad7b | 31.747826 | 167 | 0.629315 | false | false | false | false |
MasterSwift/Amaze | refs/heads/master | Sources/AmazeCore/Edge/EZAEdge.swift | bsd-3-clause | 1 | //
// EZAEdge.swift
// Amaze
//
// Created by Muhammad Tahir Vali on 2/25/18.
//
import Foundation
struct EZAEdge : Edgeable {
var index: EdgeIndex
var weight: Double
var tag: String? = nil
var description: String? = nil
static func ==(lhs: EZAEdge, rhs: EZAEdge) -> Bool {
return lhs.index == rhs.index && lhs.weight == rhs.weight
}
init(index : EdgeIndex, weight: Double ) {
self.index = index
self.weight = weight
}
init(index : EdgeIndex, weight: Double, tag : String?, description: String?) {
self.index = index
self.weight = weight
self.tag = tag
self.description = description
}
}
| b5406de1aae814a7a4648b23b8e5d4ed | 20.636364 | 82 | 0.578431 | false | false | false | false |
BelledonneCommunications/linphone-iphone | refs/heads/master | Classes/Swift/Conference/Views/ICSBubbleView.swift | gpl-3.0 | 1 | /*
* Copyright (c) 2010-2020 Belledonne Communications SARL.
*
* This file is part of linphone-iphone
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import UIKit
import Foundation
import linphonesw
import EventKit
import EventKitUI
@objc class ICSBubbleView: UIView, EKEventEditViewDelegate {
let corner_radius = 7.0
let border_width = 2.0
let rows_spacing = 6.0
let inner_padding = 8.0
let forward_reply_title_height = 10.0
let indicator_y = 3.0
let share_size = 25
let join_share_width = 150.0
let inviteTitle = StyledLabel(VoipTheme.conference_invite_title_font, VoipTexts.conference_invite_title)
let inviteCancelled = StyledLabel(VoipTheme.conference_cancelled_title_font, VoipTexts.conference_cancel_title)
let inviteUpdated = StyledLabel(VoipTheme.conference_updated_title_font, VoipTexts.conference_update_title)
let subject = StyledLabel(VoipTheme.conference_invite_subject_font)
let participants = StyledLabel(VoipTheme.conference_invite_desc_font)
let date = StyledLabel(VoipTheme.conference_invite_desc_font)
let timeDuration = StyledLabel(VoipTheme.conference_invite_desc_font)
let descriptionTitle = StyledLabel(VoipTheme.conference_invite_desc_title_font, VoipTexts.conference_description_title)
let descriptionValue = StyledLabel(VoipTheme.conference_invite_desc_font)
let joinShare = UIStackView()
let join = FormButton(title:VoipTexts.conference_invite_join.uppercased(), backgroundStateColors: VoipTheme.button_green_background)
let share = UIImageView(image:UIImage(named:"voip_export")?.tinted(with: VoipTheme.primaryTextColor.get()))
var conferenceData: ScheduledConferenceData? = nil {
didSet {
if let data = conferenceData {
subject.text = data.subject.value
participants.text = VoipTexts.conference_invite_participants_count.replacingOccurrences(of: "%d", with: String(data.conferenceInfo.participants.count+1))
participants.addIndicatorIcon(iconName: "conference_schedule_participants_default",padding : 0.0, y: -indicator_y, trailing: false)
date.text = TimestampUtils.dateToString(date: data.rawDate)
date.addIndicatorIcon(iconName: "conference_schedule_calendar_default", padding: 0.0, y:-indicator_y, trailing:false)
timeDuration.text = "\(data.time.value)" + (data.duration.value != nil ? " ( \(data.duration.value) )" : "")
timeDuration.addIndicatorIcon(iconName: "conference_schedule_time_default",padding : 0.0, y: -indicator_y, trailing: false)
descriptionTitle.isHidden = data.description.value == nil || data.description.value!.count == 0
descriptionValue.isHidden = descriptionTitle.isHidden
descriptionValue.text = data.description.value
inviteTitle.isHidden = [.Cancelled,.Updated].contains(data.conferenceInfo.state)
inviteCancelled.isHidden = data.conferenceInfo.state != .Cancelled
inviteUpdated.isHidden = data.conferenceInfo.state != .Updated
join.isEnabled = data.isConferenceCancelled.value != true
}
}
}
init() {
super.init(frame:.zero)
layer.cornerRadius = corner_radius
clipsToBounds = true
backgroundColor = VoipTheme.voip_light_gray
let rows = UIStackView()
rows.axis = .vertical
rows.spacing = rows_spacing
addSubview(rows)
rows.addArrangedSubview(inviteTitle)
rows.addArrangedSubview(inviteCancelled)
rows.addArrangedSubview(inviteUpdated)
rows.addArrangedSubview(subject)
rows.addArrangedSubview(participants)
rows.addArrangedSubview(date)
rows.addArrangedSubview(timeDuration)
rows.addArrangedSubview(descriptionTitle)
rows.addArrangedSubview(descriptionValue)
descriptionValue.numberOfLines = 5
addSubview(joinShare)
joinShare.axis = .horizontal
joinShare.spacing = rows_spacing
joinShare.addArrangedSubview(share)
share.square(share_size).done()
joinShare.addArrangedSubview(join)
rows.matchParentSideBorders(insetedByDx: inner_padding).alignParentTop(withMargin: inner_padding).done()
joinShare.alignParentBottom(withMargin: inner_padding).width(join_share_width).alignParentRight(withMargin: inner_padding).done()
join.onClick {
let view : ConferenceWaitingRoomFragment = self.VIEW(ConferenceWaitingRoomFragment.compositeViewDescription())
PhoneMainView.instance().changeCurrentView(view.compositeViewDescription())
view.setDetails(subject: (self.conferenceData?.subject.value)!, url: (self.conferenceData?.address.value)!)
}
share.onClick {
let eventStore = EKEventStore()
eventStore.requestAccess( to: EKEntityType.event, completion:{(granted, error) in
DispatchQueue.main.async {
if (granted) && (error == nil) {
let event = EKEvent(eventStore: eventStore)
event.title = self.conferenceData?.subject.value
event.startDate = self.conferenceData?.rawDate
if let duration = self.conferenceData?.conferenceInfo.duration, duration > 0 {
event.endDate = event.startDate.addingTimeInterval(TimeInterval(duration*60))
} else {
event.endDate = event.startDate.addingTimeInterval(TimeInterval(3600))
}
event.calendar = eventStore.defaultCalendarForNewEvents
if let description = self.conferenceData?.description.value, description.count > 0 {
event.notes = description + "\n\n"
}
event.notes = (event.notes != nil ? event.notes! : "") + "\(VoipTexts.call_action_participants_list):\n\(self.conferenceData?.participantsExpanded.value)"
if let urlString = self.conferenceData?.conferenceInfo.uri?.asStringUriOnly() {
event.url = URL(string:urlString)
}
let addController = EKEventEditViewController()
addController.event = event
addController.eventStore = eventStore
PhoneMainView.instance().present(addController, animated: false)
addController.editViewDelegate = self;
} else {
VoipDialog.toast(message: VoipTexts.conference_unable_to_share_via_calendar)
}
}
})
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc func setFromChatMessage(cmessage: OpaquePointer) {
let message = ChatMessage.getSwiftObject(cObject: cmessage)
message.contents.forEach { content in
if (content.isIcalendar) {
if let conferenceInfo = try? Factory.Instance.createConferenceInfoFromIcalendarContent(content: content) {
self.conferenceData = ScheduledConferenceData(conferenceInfo: conferenceInfo)
}
}
}
}
@objc static func isConferenceInvitationMessage(cmessage: OpaquePointer) -> Bool {
var isConferenceInvitationMessage = false
let message = ChatMessage.getSwiftObject(cObject: cmessage)
message.contents.forEach { content in
if (content.isIcalendar) {
isConferenceInvitationMessage = true
}
}
return isConferenceInvitationMessage
}
@objc func setLayoutConstraints(view:UIView) {
matchBordersWith(view: view, insetedByDx: inner_padding).done()
}
@objc func updateTopLayoutConstraints(view:UIView, replyOrForward: Bool) {
updateTopBorderWith(view: view, inset: inner_padding + (replyOrForward ? forward_reply_title_height : 0.0)).done()
}
func eventEditViewController(_ controller: EKEventEditViewController, didCompleteWith action: EKEventEditViewAction) {
controller.dismiss(animated: true, completion: nil)
}
@objc static func getSubjectFromContent(cmessage: OpaquePointer) -> String {
let message = ChatMessage.getSwiftObject(cObject: cmessage)
var subject = ""
message.contents.forEach { content in
if (content.isIcalendar) {
if let conferenceInfo = try? Factory.Instance.createConferenceInfoFromIcalendarContent(content: content) {
subject = conferenceInfo.subject
}
}
}
return subject
}
@objc static func getDescriptionHeightFromContent(cmessage: OpaquePointer) -> CGFloat {
let message = ChatMessage.getSwiftObject(cObject: cmessage)
var height = 0.0
message.contents.forEach { content in
if (content.isIcalendar) {
if let conferenceInfo = try? Factory.Instance.createConferenceInfoFromIcalendarContent(content: content) {
let description = NSString(string: conferenceInfo.description)
if (description.length > 0) {
let dummyTitle = StyledLabel(VoipTheme.conference_invite_desc_title_font, VoipTexts.conference_description_title)
let dummyLabel = StyledLabel(VoipTheme.conference_invite_desc_font)
let rect = CGSize(width: CGFloat(CONFERENCE_INVITATION_WIDTH-80), height: CGFloat.greatestFiniteMagnitude)
height = dummyTitle.intrinsicContentSize.height + description.boundingRect(with: rect, options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: [NSAttributedString.Key.font: dummyLabel.font!], context: nil).height
}
}
}
}
return height
}
}
| f634f7133b5b466326dc35971e7b169a | 41.642202 | 228 | 0.755379 | false | false | false | false |
Corotata/CRWeiBo | refs/heads/master | CRWeiBo/CRWeiBo/Classes/Modules/Main/CRTabBar.swift | mit | 1 | //
// CRTabBar.swift
// CRWeiBo
//
// Created by Corotata on 16/2/17.
// Copyright © 2016年 Corotata. All rights reserved.
//
import UIKit
class CRTabBar: UITabBar {
override init(frame: CGRect) {
super.init(frame: frame)
let image = UIImage(named: "tabbar_background")
backgroundColor = UIColor.init(patternImage: image!)
addSubview(composeButton)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private lazy var composeButton:UIButton = {
let button = UIButton()
button.coro_image("tabbar_compose_icon_add")
button.coro_highlightedImage("tabbar_compose_icon_add_highlighted")
button.coro_backgroundImage("tabbar_compose_button")
button.coro_highlightedBackgroundImage("tabbar_compose_button_highlighted")
button.frame.size = button.currentBackgroundImage!.size
return button
}()
override func layoutSubviews() {
let width = frame.size.width
let height = frame.size.height
composeButton.center = CGPoint(x: width/2, y: height/2)
let buttonY = CGFloat(0);
let buttonW = CGFloat(width / 5);
let buttonH = height;
var index = 0;
for button in subviews{
if !button .isKindOfClass(UIControl) || button == composeButton{
continue;
}
let buttonX = buttonW * CGFloat(index > 1 ? index + 1 :index) ;
button.frame = CGRect(x: buttonX, y: buttonY, width: buttonW, height: buttonH)
index = index + 1 ;
}
}
}
| 722857e82481ef4962ea9d2428633719 | 26.238095 | 90 | 0.587995 | false | false | false | false |
RocketChat/Rocket.Chat.iOS | refs/heads/develop | Rocket.Chat/API/Requests/Message/GetMessageRequest.swift | mit | 1 | //
// GetMessageRequest.swift
// Rocket.Chat
//
// Created by Rafael Kellermann Streit on 10/04/19.
// Copyright © 2019 Rocket.Chat. All rights reserved.
//
import Foundation
import SwiftyJSON
final class GetMessageRequest: APIRequest {
typealias APIResourceType = GetMessageResource
let requiredVersion = Version(0, 47, 0)
let method: HTTPMethod = .get
let path = "/api/v1/chat.getMessage"
var query: String?
init(msgId: String) {
self.query = "msgId=\(msgId)"
}
}
final class GetMessageResource: APIResource {
var message: Message? {
if let object = raw?["message"] {
let message = Message()
message.map(object, realm: nil)
return message
}
return nil
}
var success: Bool {
return raw?["success"].boolValue ?? false
}
}
| da352788104acd21ed552083cf5ccec1 | 19.380952 | 54 | 0.620327 | false | false | false | false |
ls1intum/proceed-storytellr | refs/heads/master | Prototyper/Classes/ScenarioInfoStepView.swift | mit | 1 | //
// ScenarioInfoStepView.swift
// StoryTellr
//
// Created by Lara Marie Reimer on 27.05.17.
// Copyright © 2017 Lara Marie Reimer. All rights reserved.
//
import UIKit
class ScenarioInfoStepView: ScenarioInfoView {
// MARK: Initialization
convenience init() {
self.init(scenarioStep: nil)
}
init(scenarioStep: ScenarioStep?) {
super.init(frame: CGRect.zero)
self.currentStep = scenarioStep
self.questions = nil
if let step = currentStep {
currentStepLabel.text = String(describing: step.stepNumber)
titleLabel.text = step.stepDescription
} else {
currentStepLabel.text = "0"
titleLabel.text = "There is no scenario step for this screen available"
}
self.setConstraints()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Autolayout
func setConstraints() {
backgroundView.addSubview(stepView)
backgroundView.addSubview(bottomView)
stepView.addSubview(currentStepLabel)
let viewsDictionary = ["step": stepView, "stepLabel": currentStepLabel, "title": titleLabel, "bottom": bottomView] as [String : Any]
//position constraints in background
let titleConstraint = NSLayoutConstraint.constraints(withVisualFormat: "H:|-20-[title]-20-|",options: NSLayoutFormatOptions(rawValue: 0),metrics: nil, views: viewsDictionary)
let vConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|-[step(50)]-40@999-[title]-40@999-[bottom]-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDictionary)
let vConstraintsStep = NSLayoutConstraint.constraints(withVisualFormat: "[step(50)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDictionary)
let centerStepX = NSLayoutConstraint(item: self.stepView, attribute:.centerX, relatedBy:.equal, toItem: self.backgroundView, attribute:.centerX, multiplier: 1.0, constant: 0.0)
let centerButtonX = NSLayoutConstraint(item: self.bottomView, attribute:.centerX, relatedBy:.equal, toItem: self.backgroundView, attribute:.centerX, multiplier: 1.0, constant: 0.0)
let centerTitleX = NSLayoutConstraint(item: self.titleLabel, attribute:.centerX, relatedBy:.equal, toItem: self.backgroundView, attribute:.centerX, multiplier: 1.0, constant: 0.0)
backgroundView.addConstraint(centerStepX)
backgroundView.addConstraint(centerButtonX)
backgroundView.addConstraint(centerTitleX)
backgroundView.addConstraints(titleConstraint)
backgroundView.addConstraints(vConstraints)
backgroundView.addConstraints(vConstraintsStep)
//position constraints in stepView
let centerX = NSLayoutConstraint(item: currentStepLabel, attribute:.centerX, relatedBy:.equal, toItem: stepView, attribute:.centerX, multiplier: 1.0, constant: 0.0)
let centerY = NSLayoutConstraint(item: currentStepLabel, attribute:.centerY, relatedBy:.equal, toItem: stepView, attribute:.centerY, multiplier: 1.0, constant: 0.0)
stepView.addConstraint(centerX)
stepView.addConstraint(centerY)
}
// MARK: Getters
var stepView : UIView = {
let view = UIView()
view.backgroundColor = PrototypeUI.ButtonColor
view.layer.cornerRadius = 25.0
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
var currentStepLabel : UILabel = {
let stepLabel = UILabel()
stepLabel.translatesAutoresizingMaskIntoConstraints = false
stepLabel.font = UIFont.boldSystemFont(ofSize: 30.0)
stepLabel.textColor = UIColor.white
stepLabel.text = "0"
return stepLabel
}()
var bottomView : UIButton = {
let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.backgroundColor = PrototypeUI.ButtonColor
button.layer.cornerRadius = 15.0
button.setImage(UIImage(named: "check"), for: .normal)
button.setTitle("OKAY", for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 15.0)
button.contentEdgeInsets = UIEdgeInsetsMake(10.0, 10.0, 10.0, 10.0)
button.addTarget(self, action: #selector(didTapOkay), for: .touchUpInside)
return button
}()
// MARK: Actions
@objc func didTapOkay(sender: UIButton) {
guard let delegate = self.delegate else { return }
delegate.didPressBottomButton(_: sender, withAnswer: nil, isLastFeedback: nil)
print("Tap received")
}
}
| ab1d8edd3a6d2b4e5d90f7e866d0ad94 | 41.087719 | 209 | 0.670905 | false | false | false | false |
boxenjim/SwiftyFaker | refs/heads/master | SwiftyFaker/Random.swift | mit | 1 | //
// RandomNumbers.swift
// SwiftyFaker
//
// Created by Jim Schultz on 9/23/15.
// Copyright © 2015 Jim Schultz. All rights reserved.
//
import Foundation
/**
Arc Random for Double and Float
*/
func arc4random <T: ExpressibleByIntegerLiteral> (_ type: T.Type) -> T {
var r: T = 0
arc4random_buf(&r, MemoryLayout<T>.size)
return r
}
extension UInt64 {
static func random(_ lower: UInt64 = min, upper: UInt64 = max) -> UInt64 {
var m: UInt64
let u = upper - lower
var r = arc4random(UInt64.self)
if u > UInt64(Int64.max) {
m = 1 + ~u
} else {
m = ((max - (u * 2)) + 1) % u
}
while r < m {
r = arc4random(UInt64.self)
}
return (r % u) + lower
}
}
extension Int64 {
static func random(_ lower: Int64 = min, upper: Int64 = max) -> Int64 {
let (s, overflow) = upper.subtractingReportingOverflow(lower)
let u = overflow ? UInt64.max - UInt64(~s) : UInt64(s)
let r = UInt64.random(upper: u)
if r > UInt64(Int64.max) {
return Int64(r - (UInt64(~lower) + 1))
} else {
return Int64(r) + lower
}
}
}
extension UInt32 {
static func random(_ lower: UInt32 = min, upper: UInt32 = max) -> UInt32 {
return arc4random_uniform(upper - lower) + lower
}
}
extension Int32 {
static func random(_ lower: Int32 = min, upper: Int32 = max) -> Int32 {
let r = arc4random_uniform(UInt32(Int64(upper) - Int64(lower)))
return Int32(Int64(r) + Int64(lower))
}
}
extension UInt {
static func random(_ lower: UInt = min, upper: UInt = max) -> UInt {
switch (__WORDSIZE) {
case 32: return UInt(UInt32.random(UInt32(lower), upper: UInt32(upper)))
case 64: return UInt(UInt64.random(UInt64(lower), upper: UInt64(upper)))
default: return lower
}
}
}
extension Int {
static func random(_ lower: Int = min, upper: Int = max) -> Int {
switch (__WORDSIZE) {
case 32: return Int(Int32.random(Int32(lower), upper: Int32(upper)))
case 64: return Int(Int64.random(Int64(lower), upper: Int64(upper)))
default: return lower
}
}
}
public extension Int {
public static func random(_ range: Range<Int>) -> Int {
let offset = range.lowerBound < 0 ? abs(range.lowerBound) : 0
let min = UInt32(range.lowerBound + offset)
let max = UInt32(range.upperBound + offset)
return Int(min + arc4random_uniform(max - min)) - offset
}
public static func random(_ digits: Int) -> Int {
let min = getMin(digits)
let max = getMax(digits)
return Int.random(min, upper: max)
}
fileprivate static func getMin(_ digits: Int) -> Int {
var strng = "1"
let absMax = UInt.max
let maxCount = "\(absMax)".characters.count
let adjCount = digits > maxCount ? maxCount : digits
for _ in 1..<adjCount {
strng += "0"
}
return Int(strng)!
}
fileprivate static func getMax(_ digits: Int) -> Int {
var strng = ""
let absMax = UInt.max
if digits >= "\(absMax)".characters.count {
strng = "\(UInt.max)"
} else {
for _ in 0..<digits {
strng += "9"
}
}
return Int(strng)!
}
}
public extension Double {
public static func random(_ min: Double = 0.0, max: Double = 1.0) -> Double {
let offset = min < 0.0 ? Swift.abs(min) : 0.0
let low = min + offset
let high = max + offset
let r = Double(arc4random(UInt64.self)) / Double(UInt64.max)
return ((r * (high - low)) + low) - offset
}
}
public extension Float {
public static func random(_ min: Float = 0.0, max: Float = 1.0) -> Float {
let offset = min < 0.0 ? Swift.abs(min) : Float(0.0)
let low = min + offset
let high = max + offset
let r = Float(arc4random(UInt32.self)) / Float(UInt32.max)
return ((r * (high - low)) + low) - offset
}
}
public extension Array {
public func random() -> Element {
let randInt = Int.random(0..<self.count)
let obj = self[randInt]
return obj
}
}
| eadfff852fffc0a608b87d2e3bc11be9 | 27.392157 | 81 | 0.546961 | false | false | false | false |
yanagiba/swift-transform | refs/heads/master | Sources/swift-transform/Option.swift | apache-2.0 | 1 | /*
Copyright 2017 Ryuichi Laboratories and the Yanagiba project contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
func computeFormats(
_ dotYanagibaTransform: DotYanagibaTransform?,
_ formatsOption: [String: Any]?
) -> [String: Any]? {
var formats: [String: Any]?
if let dotYanagibaTransform = dotYanagibaTransform, let customFormats = dotYanagibaTransform.formats {
formats = customFormats
}
if let customFormats = formatsOption {
formats = customFormats
}
return formats
}
enum OutputOption {
case standardOutput
case fileOutput(String)
}
func computeOutput(
_ dotYanagibaTransform: DotYanagibaTransform?,
_ outputPathOption: String?
) -> OutputOption {
var outputPath: String?
if let dotYanagibaTransform = dotYanagibaTransform, let outputPathOption = dotYanagibaTransform.outputPath {
outputPath = outputPathOption
}
if let outputPathOption = outputPathOption {
outputPath = outputPathOption
}
if let fileOutput = outputPath {
return .fileOutput(fileOutput)
}
return .standardOutput
}
| 37a8416ae403da06b1b4862920b6b13d | 28.5 | 110 | 0.750157 | false | false | false | false |
sfaxon/PyxisServer | refs/heads/master | Sources/HTTPResponse.swift | mit | 1 | //
// HTTPResponse.swift
// PyxisRouter
//
// Created by Seth Faxon on 8/23/15.
// Copyright © 2015 SlashAndBurn. All rights reserved.
//
public protocol HttpResponseProtocol {
var statusCode: Int { get set }
var headers: [String: String] { get set }
var body: String { get set }
}
public class HttpResponse: HttpResponseProtocol {
public var statusCode: Int = 200
public var headers: [String: String] = [:]
public var body: String = ""
// resp_body - the response body, by default is an empty string. It is set to nil after the response is set, except for test connections.
// resp_charset - the response charset, defaults to “utf-8”
// resp_cookies - the response cookies with their name and options
// resp_headers - the response headers as a dict, by default cache-control is set to "max-age=0, private, must-revalidate"
// status - the response status
public var description: String {
// HTTP/1.1 200 OK
// Content-Length: 27
//
// hello world for the request
let headerString = headers.map { "\($0): \($1)" }.joinWithSeparator("\n")
return "HTTP/1.1 \(statusCode) OK\n\(headerString)\nContent-Length: xx\n\n\(body)"
}
}
//public enum HttpResponseBody {
// case HTML(String)
// case RAW(String)
//
// var data: String {
// switch self {
// case .HTML(let body):
// return "<html><body>\(body)</body></html>"
// case .RAW(let body):
// return body
// }
// }
//}
//
//public protocol HttpResponse {
// var statusCode: Int { get }
// var headers: [String: String] { get }
// var body: String { get }
//}
//
//public protocol HTTPResponder {
// func call(request: HttpRequest, response: HttpResponse) -> HttpResponse
//}
//
//public struct BaseResponse: HttpResponse, HTTPResponder {
// public var statusCode: Int = 200
// public var headers: [String: String] = [:]
// public var body: String = ""
//
// private var request: HttpRequest
// public init(request: HttpRequest) {
// self.request = request
// }
//
// public func call(request: HttpRequest, response: HttpResponse) -> HttpResponse {
// var newResponse = BaseResponse(request: request)
// newResponse.statusCode = self.statusCode
// newResponse.headers = self.headers
// newResponse.body = self.body
//
// return self
// }
//}
//
//public struct HTTPPipeline: HTTPResponder {
// public var responders: [HTTPResponder] = []
//
// public init(responders: [HTTPResponder]) {
// self.responders = responders
// }
//
// public func call(request: HttpRequest, response: HttpResponse) -> HttpResponse {
// var response = BaseResponse(request: request) as HttpResponse
// for (index, responder) in self.responders.enumerate() {
// print("index: \(index) response: \(response)")
// response = responder.call(request, response: response)
// }
// print("final: \(response)")
// return response
// }
//}
//
//
| 88143d4ebfb35b21d1f8f9bf2a3205dc | 30.81 | 148 | 0.598554 | false | false | false | false |
elpassion/el-space-ios | refs/heads/master | ELSpaceTests/TestCases/ViewControllers/LoginViewControllerSpec.swift | gpl-3.0 | 1 | import Quick
import Nimble
import GoogleSignIn
import RxTest
@testable import ELSpace
class LoginViewControllerSpec: QuickSpec {
override func spec() {
describe("LoginViewController") {
var sut: LoginViewController!
var navigationController: UINavigationController!
var viewControllerPresenterSpy: ViewControllerPresenterSpy!
var googleUserManagerSpy: GoogleUserManagerSpy!
afterEach {
sut = nil
navigationController = nil
viewControllerPresenterSpy = nil
googleUserManagerSpy = nil
}
context("when try to initialize with init coder") {
it("should throw fatalError") {
expect { sut = LoginViewController(coder: NSCoder()) }.to(throwAssertion())
}
}
context("after initialize") {
beforeEach {
viewControllerPresenterSpy = ViewControllerPresenterSpy()
googleUserManagerSpy = GoogleUserManagerSpy()
sut = LoginViewController(googleUserManager: googleUserManagerSpy,
alertFactory: AlertFactoryFake(),
viewControllerPresenter: viewControllerPresenterSpy,
googleUserMapper: GoogleUSerMapperFake())
navigationController = UINavigationController(rootViewController: sut)
}
describe("view") {
it("should be kind of LoginView") {
expect(sut.view as? LoginView).toNot(beNil())
}
context("when appear") {
beforeEach {
sut.viewWillAppear(true)
}
it("should set navigation bar hidden") {
expect(navigationController.isNavigationBarHidden).to(beTrue())
}
}
}
context("when viewDidAppear") {
beforeEach {
sut.viewDidAppear(true)
}
it("should call autoSignIn") {
expect(googleUserManagerSpy.didCallAutoSignIn).to(beTrue())
}
}
context("when viewWillAppear") {
beforeEach {
sut.viewWillAppear(true)
}
it("should set navigation bar to hidden") {
expect(navigationController.isNavigationBarHidden).to(beTrue())
}
}
it("should have correct preferredStatusBarStyle") {
expect(sut.preferredStatusBarStyle == .lightContent).to(beTrue())
}
context("when tap sign in button and sign in with success") {
var resultToken: String!
beforeEach {
sut.googleTooken = { token in
resultToken = token
}
googleUserManagerSpy.resultUser = GIDGoogleUser()
sut.loginView.loginButton.sendActions(for: .touchUpInside)
}
it("should sign in on correct view controller") {
expect(googleUserManagerSpy.viewController).to(equal(sut))
}
it("should get correct token") {
expect(resultToken).to(equal("fake_token"))
}
}
context("when tap sign in button and sign in with ValidationError emialFormat") {
beforeEach {
googleUserManagerSpy.resultError = EmailValidator.EmailValidationError.emailFormat
sut.loginView.loginButton.sendActions(for: .touchUpInside)
}
it("should present error on correct view controller") {
expect(viewControllerPresenterSpy.presenter).to(equal(sut))
}
}
context("when tap sign in button and sign in with ValidationError incorrectDomain") {
beforeEach {
googleUserManagerSpy.resultError = EmailValidator.EmailValidationError.incorrectDomain
sut.loginView.loginButton.sendActions(for: .touchUpInside)
}
it("should present error on correct view controller") {
expect(viewControllerPresenterSpy.presenter).to(equal(sut))
}
}
context("when tap sign in button and sign in with unkown error") {
beforeEach {
googleUserManagerSpy.resultError = NSError(domain: "fake_domain",
code: 999,
userInfo: nil)
sut.loginView.loginButton.sendActions(for: .touchUpInside)
}
it("should NOT present error") {
expect(viewControllerPresenterSpy.presenter).to(beNil())
}
}
}
}
}
}
| cfdc10090e4a6de252c1ed09b87c9d56 | 38.692857 | 110 | 0.478316 | false | false | false | false |
sundeepgupta/chord | refs/heads/master | chord/BeaconId.swift | apache-2.0 | 1 | typealias BeaconId = [String: NSObject]
extension Dictionary where Key: StringLiteralConvertible, Value: NSObject {
var uuid: String {
get {
return self["uuid"] as! String
}
}
var major: NSNumber {
get {
return self["major"] as! NSNumber
}
}
var minor: NSNumber {
get {
return self["minor"] as! NSNumber
}
}
}
import CoreLocation
extension CLBeacon {
func toBeaconId() -> BeaconId {
return [
DictionaryKey.uuid: self.proximityUUID.UUIDString,
DictionaryKey.major: self.major,
DictionaryKey.minor: self.minor
]
}
}
extension SequenceType where Generator.Element == BeaconId {
func includes (element: Generator.Element) -> Bool {
return self.contains { myElement -> Bool in
return myElement == element
}
}
} | 6b32dc1107a996b151588c93bdd9520f | 20.090909 | 75 | 0.567422 | false | false | false | false |
LuAndreCast/iOS_WatchProjects | refs/heads/master | watchOS2/Heart Rate/v3 Heart Rate Stream/HealthWatchExample/MainViewController.swift | mit | 1 | //
// MainViewController.swift
// HealthWatchExample
//
// Created by Luis Castillo on 8/2/16.
// Copyright © 2016 LC. All rights reserved.
//
import UIKit
import HealthKit
class MainViewController: UIViewController,watchMessengerDelegate
{
//watch messenger
let wMessenger = WatchMessenger()
//heart Rate
let hrPermission = HeartRatePermission()
let healthStore = HKHealthStore()
@IBOutlet weak var startEndMonitoringButton: UIButton!
@IBOutlet weak var messageLabel: UILabel!
//MARK: - View
override func viewDidLoad() {
super.viewDidLoad()
self.wMessenger.delegate = self
self.wMessenger.start()
}//eom
override func viewDidAppear(_ animated: Bool)
{
self.requestHeartRatePermission()
}//eom
//MARK: - Actions
@IBAction func startEndMonitoring(_ sender: AnyObject)
{
if self.startEndMonitoringButton.isSelected
{
self.startEndMonitoringButton.isSelected = false
self.end()
}
else
{
self.startEndMonitoringButton.isSelected = true
self.start()
}
}//eom
//MARK: Start / End Monitoring
func start()
{
let messageFromPhone = [ keys.command.toString() : command.startMonitoring.toString() ]
wMessenger.sendMessage(messageFromPhone as [String : AnyObject])
{ (reply:[String : Any]?, error:Error?) in
if error != nil
{
self.startEndMonitoringButton.isSelected = false
self.updateUI()
//show error
}
else
{
}
}
}//eom
func end()
{
let messageFromPhone = [ keys.command.toString() : command.endMonitoring.toString() ]
wMessenger.sendMessage(messageFromPhone as [String : AnyObject])
{ (reply:[String : Any]?, error:Error?) in
if error != nil
{
self.startEndMonitoringButton.isSelected = true
self.updateUI()
//show error
}
else
{
}
}
}//eom
fileprivate func updateUI()
{
if self.startEndMonitoringButton.isSelected
{
self.messageLabel.text = "Started Monitoring"
self.startEndMonitoringButton.setTitle("End Monitoring", for: UIControlState())
}
else
{
self.messageLabel.text = "Ended Monitoring"
self.startEndMonitoringButton.setTitle("Start Monitoring", for: UIControlState())
}
}//eom
//MARK: - Messenger Delegates
func watchMessenger_didReceiveMessage(_ message: [String : AnyObject])
{
DispatchQueue.main.async {
//reponses
if let commandReceived:String = message[keys.response.toString()] as? String
{
switch commandReceived
{
case response.startedMonitoring.toString():
self.startEndMonitoringButton.isSelected = true
self.updateUI()
break
case response.endedMonitoring.toString():
self.startEndMonitoringButton.isSelected = false
self.updateUI()
break
case response.data.toString():
let hrValue:Double? = message[keys.heartRate.toString()] as? Double
let hrTime:String? = message[keys.time.toString()] as? String
let hrDate:String? = message[keys.date.toString()] as? String
if hrValue != nil && hrTime != nil && hrDate != nil
{
self.messageLabel.text = "Heart rate Data:\n \(hrValue!) \n at \(hrTime!) \n on \(hrDate!)"
}
break
case response.errorHealthKit.toString():
self.messageLabel.text = "Error with HealthKit"
break
case response.errorMonitoring.toString():
self.messageLabel.text = "Error with Monitoring"
break
default:
self.messageLabel.text = "Unknown response received"
break
}
}
else
{
self.messageLabel.text = "Unknown received"
}
}
}//eom
func watchMessenger_startResults(_ started: Bool, error: NSError?)
{
if error != nil
{
self.messageLabel.text = error?.localizedDescription
}
}//eom
//MARK: - Request Heart Rate Permission
func requestHeartRatePermission()
{
hrPermission.requestPermission(healthStore)
{ (success:Bool, error:NSError?) in
}
}//eom
}//eoc
| d2e83b8e7f8324e904bfc7e7b2654466 | 28.977143 | 119 | 0.506291 | false | false | false | false |
wilfreddekok/Antidote | refs/heads/master | Antidote/ErrorHandling.swift | mpl-2.0 | 1 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
import UIKit
enum ErrorHandlerType {
case CannotLoadHTML
case CreateOCTManager
case ToxSetInfoCodeName
case ToxSetInfoCodeStatusMessage
case ToxAddFriend
case RemoveFriend
case CallToChat
case ExportProfile
case DeleteProfile
case PasswordIsEmpty
case WrongOldPassword
case PasswordsDoNotMatch
case AnswerCall
case RouteAudioToSpeaker
case EnableVideoSending
case CallSwitchCamera
case ConvertImageToPNG
case ChangeAvatar
case SendFileToFriend
case AcceptIncomingFile
case CancelFileTransfer
case PauseFileTransfer
}
/**
Show alert for given error.
- Parameters:
- type: Type of error to handle.
- error: Optional erro to get code from.
- retryBlock: If set user will be asked to retry request once again.
*/
func handleErrorWithType(type: ErrorHandlerType, error: NSError? = nil, retryBlock: (Void -> Void)? = nil) {
switch type {
case .CannotLoadHTML:
UIAlertController.showErrorWithMessage(String(localized: "error_internal_message"), retryBlock: retryBlock)
case .CreateOCTManager:
let (title, message) = OCTManagerInitError(rawValue: error!.code)!.strings()
UIAlertController.showWithTitle(title, message: message, retryBlock: retryBlock)
case .ToxSetInfoCodeName:
let (title, message) = OCTToxErrorSetInfoCode(rawValue: error!.code)!.nameStrings()
UIAlertController.showWithTitle(title, message: message, retryBlock: retryBlock)
case .ToxSetInfoCodeStatusMessage:
let (title, message) = OCTToxErrorSetInfoCode(rawValue: error!.code)!.statusMessageStrings()
UIAlertController.showWithTitle(title, message: message, retryBlock: retryBlock)
case .ToxAddFriend:
let (title, message) = OCTToxErrorFriendAdd(rawValue: error!.code)!.strings()
UIAlertController.showWithTitle(title, message: message, retryBlock: retryBlock)
case .RemoveFriend:
let (title, message) = OCTToxErrorFriendDelete(rawValue: error!.code)!.strings()
UIAlertController.showWithTitle(title, message: message, retryBlock: retryBlock)
case .CallToChat:
let (title, message) = OCTToxAVErrorCall(rawValue: error!.code)!.strings()
UIAlertController.showWithTitle(title, message: message, retryBlock: retryBlock)
case .ExportProfile:
UIAlertController.showWithTitle(String(localized: "error_title"), message: error!.localizedDescription, retryBlock: retryBlock)
case .DeleteProfile:
UIAlertController.showWithTitle(String(localized: "error_title"), message: error!.localizedDescription, retryBlock: retryBlock)
case .PasswordIsEmpty:
UIAlertController.showWithTitle(String(localized: "password_is_empty_error"), retryBlock: retryBlock)
case .WrongOldPassword:
UIAlertController.showWithTitle(String(localized: "wrong_old_password"), retryBlock: retryBlock)
case .PasswordsDoNotMatch:
UIAlertController.showWithTitle(String(localized: "passwords_do_not_match"), retryBlock: retryBlock)
case .AnswerCall:
let (title, message) = OCTToxAVErrorAnswer(rawValue: error!.code)!.strings()
UIAlertController.showWithTitle(title, message: message, retryBlock: retryBlock)
case .RouteAudioToSpeaker:
UIAlertController.showWithTitle(String(localized: "error_title"), message: String(localized: "error_internal_message"), retryBlock: retryBlock)
case .EnableVideoSending:
UIAlertController.showWithTitle(String(localized: "error_title"), message: String(localized: "error_internal_message"), retryBlock: retryBlock)
case .CallSwitchCamera:
UIAlertController.showWithTitle(String(localized: "error_title"), message: String(localized: "error_internal_message"), retryBlock: retryBlock)
case .ConvertImageToPNG:
UIAlertController.showWithTitle(String(localized: "error_title"), message: String(localized: "change_avatar_error_convert_image"), retryBlock: retryBlock)
case .ChangeAvatar:
let (title, message) = OCTSetUserAvatarError(rawValue: error!.code)!.strings()
UIAlertController.showWithTitle(title, message: message, retryBlock: retryBlock)
case .SendFileToFriend:
let (title, message) = OCTSendFileError(rawValue: error!.code)!.strings()
UIAlertController.showWithTitle(title, message: message, retryBlock: retryBlock)
case .AcceptIncomingFile:
let (title, message) = OCTAcceptFileError(rawValue: error!.code)!.strings()
UIAlertController.showWithTitle(title, message: message, retryBlock: retryBlock)
case .CancelFileTransfer:
let (title, message) = OCTFileTransferError(rawValue: error!.code)!.strings()
UIAlertController.showWithTitle(title, message: message, retryBlock: retryBlock)
case .PauseFileTransfer:
let (title, message) = OCTFileTransferError(rawValue: error!.code)!.strings()
UIAlertController.showWithTitle(title, message: message, retryBlock: retryBlock)
}
}
extension OCTManagerInitError {
func strings() -> (title: String, message: String) {
switch self {
case .PassphraseFailed:
return (String(localized: "error_wrong_password_title"),
String(localized: "error_wrong_password_message"))
case .CannotImportToxSave:
return (String(localized: "error_import_not_exist_title"),
String(localized: "error_import_not_exist_message"))
case .DatabaseKeyCannotCreateKey:
fallthrough
case .DatabaseKeyCannotReadKey:
fallthrough
case .DatabaseKeyMigrationToEncryptedFailed:
return (String(localized: "error_title"),
String(localized: "error_internal_message"))
case .ToxFileDecryptNull:
fallthrough
case .DatabaseKeyDecryptNull:
return (String(localized: "error_decrypt_title"),
String(localized: "error_decrypt_empty_data_message"))
case .ToxFileDecryptBadFormat:
fallthrough
case .DatabaseKeyDecryptBadFormat:
return (String(localized: "error_decrypt_title"),
String(localized: "error_decrypt_bad_format_message"))
case .ToxFileDecryptFailed:
fallthrough
case .DatabaseKeyDecryptFailed:
return (String(localized: "error_decrypt_title"),
String(localized: "error_decrypt_wrong_password_message"))
case .CreateToxUnknown:
return (String(localized: "error_title"),
String(localized: "error_general_unknown_message"))
case .CreateToxMemoryError:
return (String(localized: "error_title"),
String(localized: "error_general_no_memory_message"))
case .CreateToxPortAlloc:
return (String(localized: "error_title"),
String(localized: "error_general_bind_port_message"))
case .CreateToxProxyBadType:
return (String(localized: "error_proxy_title"),
String(localized: "error_internal_message"))
case .CreateToxProxyBadHost:
return (String(localized: "error_proxy_title"),
String(localized: "error_proxy_invalid_address_message"))
case .CreateToxProxyBadPort:
return (String(localized: "error_proxy_title"),
String(localized: "error_proxy_invalid_port_message"))
case .CreateToxProxyNotFound:
return (String(localized: "error_proxy_title"),
String(localized: "error_proxy_host_not_resolved_message"))
case .CreateToxEncrypted:
return (String(localized: "error_title"),
String(localized: "error_general_profile_encrypted_message"))
case .CreateToxBadFormat:
return (String(localized: "error_title"),
String(localized: "error_general_bad_format_message"))
}
}
}
extension OCTToxErrorSetInfoCode {
func nameStrings() -> (title: String, message: String) {
switch self {
case .Unknow:
return (String(localized: "error_title"),
String(localized: "error_internal_message"))
case .TooLong:
return (String(localized: "error_title"),
String(localized: "error_name_too_long"))
}
}
func statusMessageStrings() -> (title: String, message: String) {
switch self {
case .Unknow:
return (String(localized: "error_title"),
String(localized: "error_internal_message"))
case .TooLong:
return (String(localized: "error_title"),
String(localized: "error_status_message_too_long"))
}
}
}
extension OCTToxErrorFriendAdd {
func strings() -> (title: String, message: String) {
switch self {
case .TooLong:
return (String(localized: "error_title"),
String(localized: "error_contact_request_too_long"))
case .NoMessage:
return (String(localized: "error_title"),
String(localized: "error_contact_request_no_message"))
case .OwnKey:
return (String(localized: "error_title"),
String(localized: "error_contact_request_own_key"))
case .AlreadySent:
return (String(localized: "error_title"),
String(localized: "error_contact_request_already_sent"))
case .BadChecksum:
return (String(localized: "error_title"),
String(localized: "error_contact_request_bad_checksum"))
case .SetNewNospam:
return (String(localized: "error_title"),
String(localized: "error_contact_request_new_nospam"))
case .Malloc:
fallthrough
case .Unknown:
return (String(localized: "error_title"),
String(localized: "error_internal_message"))
}
}
}
extension OCTToxErrorFriendDelete {
func strings() -> (title: String, message: String) {
switch self {
case .NotFound:
return (String(localized: "error_title"),
String(localized: "error_internal_message"))
}
}
}
extension OCTToxAVErrorCall {
func strings() -> (title: String, message: String) {
switch self {
case .AlreadyInCall:
return (String(localized: "error_title"),
String(localized: "call_error_already_in_call"))
case .FriendNotConnected:
return (String(localized: "error_title"),
String(localized: "call_error_contact_is_offline"))
case .FriendNotFound:
fallthrough
case .InvalidBitRate:
fallthrough
case .Malloc:
fallthrough
case .Sync:
fallthrough
case .Unknown:
return (String(localized: "error_title"),
String(localized: "error_internal_message"))
}
}
}
extension OCTToxAVErrorAnswer {
func strings() -> (title: String, message: String) {
switch self {
case .FriendNotCalling:
return (String(localized: "error_title"),
String(localized: "call_error_no_active_call"))
case .CodecInitialization:
fallthrough
case .Sync:
fallthrough
case .InvalidBitRate:
fallthrough
case .Unknown:
fallthrough
case .FriendNotFound:
return (String(localized: "error_title"),
String(localized: "error_internal_message"))
}
}
}
extension OCTSetUserAvatarError {
func strings() -> (title: String, message: String) {
switch self {
case .TooBig:
return (String(localized: "error_title"),
String(localized: "error_internal_message"))
}
}
}
extension OCTSendFileError {
func strings() -> (title: String, message: String) {
switch self {
case .InternalError:
fallthrough
case .CannotReadFile:
fallthrough
case .CannotSaveFileToUploads:
fallthrough
case .NameTooLong:
fallthrough
case .FriendNotFound:
return (String(localized: "error_title"),
String(localized: "error_internal_message"))
case .FriendNotConnected:
return (String(localized: "error_title"),
String(localized: "error_contact_not_connected"))
case .TooMany:
return (String(localized: "error_title"),
String(localized: "error_too_many_files"))
}
}
}
extension OCTAcceptFileError {
func strings() -> (title: String, message: String) {
switch self {
case .InternalError:
fallthrough
case .CannotWriteToFile:
fallthrough
case .FriendNotFound:
fallthrough
case .WrongMessage:
return (String(localized: "error_title"),
String(localized: "error_internal_message"))
case .FriendNotConnected:
return (String(localized: "error_title"),
String(localized: "error_contact_not_connected"))
}
}
}
extension OCTFileTransferError {
func strings() -> (title: String, message: String) {
switch self {
case .WrongMessage:
return (String(localized: "error_title"),
String(localized: "error_internal_message"))
}
}
}
| ed87761991e27b841120482867ba63e8 | 43.260479 | 166 | 0.596225 | false | false | false | false |
studyYF/YueShiJia | refs/heads/master | YueShiJia/YueShiJia/Classes/Main/YFTabBarViewController.swift | apache-2.0 | 1 | //
// YFTabBarViewController.swift
// YueShiJia
//
// Created by YangFan on 2017/5/10.
// Copyright © 2017年 YangFan. All rights reserved.
//
import UIKit
class YFTabBarViewController: UITabBarController {
//MARK: 定义属性
//MARK: 生命周期函数
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
tabBar.isTranslucent = false
addChildVC(vc: YFHomeViewController(), title: "首页", image: "YS_index_nor", selImage: "YS_index_sel", tag: 100)
addChildVC(vc: YFSubjectViewController(), title: "专题", image: "YS_pro_nor", selImage: "YS_pro_sel", tag: 101)
addChildVC(vc: YFShopViewController(), title: "店铺", image: "YS_shop_nor", selImage: "YS_shop_sel", tag: 102)
addChildVC(vc: YFBasketViewController(), title: "购物篮", image: "YS_car_nor", selImage: "YS_car_sel", tag: 103)
let vc = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "YFProfileViewController")
addChildVC(vc: vc, title: "我", image: "YS_mine_nor", selImage: "YS_mine_sel", tag: 104)
}
}
//MARK: 设置UI
extension YFTabBarViewController {
fileprivate func addChildVC(vc: UIViewController, title: String, image: String,selImage: String,tag: Int) {
vc.tabBarItem.title = title
vc.tabBarItem.tag = tag
vc.tabBarItem.image = UIImage(named: image)
vc.tabBarItem.selectedImage = UIImage(named: selImage)
addChildViewController(YFNavigationController(rootViewController: vc))
}
}
// MARK: - UITabBarControllerDelegate
extension YFTabBarViewController: UITabBarControllerDelegate {
//获取选中的UITabBarButton,并添加图片动画
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
var view = tabBar.subviews[item.tag - 99]
if !view.isKind(of: NSClassFromString("UITabBarButton")!) {
view = tabBar.subviews[item.tag - 99 + 1]
}
for imageView in view.subviews {
//添加关键帧动画
if imageView.isKind(of: NSClassFromString("UITabBarSwappableImageView")!) {
let keyAnimation = CAKeyframeAnimation(keyPath: "transform.scale")
keyAnimation.values = [1.0,1.3,0.9,1.15,0.95,1.02,1.0]
keyAnimation.duration = 0.8
keyAnimation.calculationMode = kCAAnimationCubic
imageView.layer.add(keyAnimation, forKey: "transform.scale")
}
}
}
}
| 67d5887652e203b8e09e98e5c5a35a8f | 36.454545 | 130 | 0.652104 | false | false | false | false |
nishiyamaosamu/ColorLogger | refs/heads/master | ColorLoggerExample/ColorLoggerExample/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// ColorLoggerExample
//
// Created by Osamu Nishiyama on 2015/04/09.
// Copyright (c) 2015年 EVER SENSE, INC. All rights reserved.
//
import UIKit
let log = ColorLogger.defaultInstance
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
log.verbose("This is Verbose Log") //verbose not active. Default outputLogLevel is Debug
log.debug("This is Debug Log")
log.info("This is Info Log")
log.warning("This is Warning Log")
log.error("This is Error Log")
log.debug([1,2,3,4]) // AnyObject
let a : NSObject? = nil
log.debug(a) //nil
log.debug("one", 2, [3,4]) //variadic parameter
log.outputLogLevel = .Verbose
log.showFileInfo = false
log.showDate = false
log.showLogLevel = true
log.showFunctionName = false
print("")
log.verbose("This is Verbose Log")
log.debug("This is Debug Log")
log.info("This is Info Log")
log.warning("This is Warning Log")
log.error("This is Error Log")
log.outputLogLevel = .Warning
log.showLogLevel = false
log.showFileInfo = false
log.showFunctionName = true
log.showDate = true
print("")
log.verbose("This is Verbose Log") // not active
log.debug("This is Debug Log") // not active
log.info("This is Info Log") // not active
log.warning("This is Warning Log")
log.error("This is Error Log")
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 3dff3424d0e72133138bb6278102a26b | 38.077778 | 285 | 0.676713 | false | false | false | false |
Zhendeshede/weiboBySwift | refs/heads/master | 新浪微博/新浪微博/NetworkTool.swift | mit | 1 | //
// NetworkTool.swift
// 新浪微博
//
// Created by 李旭飞 on 15/10/10.
// Copyright © 2015年 lee. All rights reserved.
//
import UIKit
private let ErrorDomain="network.error"
//网络访问错误枚举
private enum NetworkError:Int{
case emptyDataError = -1
case emptyTokenError = -2
///错误描述
private var errorDescription:String{
switch self {
case .emptyDataError: return "空数据"
case .emptyTokenError: return "没有权限"
}
}
///根据枚举类型返回错误信息
private func error()->NSError{
return NSError(domain: ErrorDomain, code: rawValue, userInfo:[ErrorDomain:errorDescription])
}
}
class NetworkTool: NSObject {
//MARK:- 检查token
private func checkToken(finished:FinishedCallBack)->[String:AnyObject]?{
if UserAccess.loadUserAccount?.access_token == nil{
let error = NetworkError.emptyTokenError.error()
finished(result: nil, error: error)
return nil
}
//返回字典时为啦包成参数,这样直接再添加额外参数就可
return ["access_token":UserAccess.loadUserAccount!.access_token!]
}
//MARK:- 加载微博数据
func loadWeiboData(since_id:Int,max_id:Int,finished:FinishedCallBack){
guard var param=checkToken(finished) else{
return
}
if since_id>0{
param["since_id"]="\(since_id)";
}
if max_id>0{
param["max_id"]="\(max_id-1)";
}
let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
networkRequest(.GET, URLString: urlString, paramater: param, finished: finished)
}
static let shareNetworkTool=NetworkTool()
//MARK: - OAuth授权
private let clientId="2260003661"
private let appSecret="84630ccd2050db7da66f9d1e7c25d105"
let redirectURL="http://www.baidu.com"
func oauthURL()->NSURL{
let path=NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(clientId)&redirect_uri=\(redirectURL)")
return path!
}
//MARK:- 获取用户信息
func loadUserInfo(uid:String,finished:FinishedCallBack){
//判断token是否存在
guard var param = checkToken(finished) else{
finished(result: nil, error: NetworkError.emptyTokenError.error())
return
}
let url="https://api.weibo.com/2/users/show.json"
param["uid"]=uid
networkRequest(.GET, URLString: url, paramater: param, finished: finished)
}
// MARK:- 获取授权码token
func oauthToken(code:String,finished:FinishedCallBack){
let dict=["client_id":clientId,
"client_secret":appSecret,
"grant_type":"authorization_code",
"code":code,
"redirect_uri":redirectURL]
let url="https://api.weibo.com/oauth2/access_token"
networkRequest(.POST, URLString: url, paramater: dict, finished: finished)
}
// 这里要加问号,有可能为空
typealias FinishedCallBack = (result:AnyObject?,error:NSError?)->()
///网络请求方式枚举
enum HttpMethod:String{
case GET = "GET"
case POST = "POST"
}
//MARK:- 封装网络请求方法
func networkRequest(methed:HttpMethod,URLString:String,paramater:[String:AnyObject],finished:FinishedCallBack){
var body = ""
for (key,value) in paramater{
body += "\(key)=\(value as! String)&"
}
body = (body as NSString).substringToIndex(body.characters.count-1)
let request = NSMutableURLRequest()
switch methed{
case .POST :
request.URL = NSURL(string: URLString)
request.HTTPMethod = "POST"
request.HTTPBody = body.dataUsingEncoding(NSUTF8StringEncoding)
case .GET :
request.URL = NSURL(string: "\(URLString)?\(body)")
request.HTTPMethod = "GET"
}
NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) -> Void in
if error != nil || data == nil{
finished(result: nil, error: error)
return
}
do{
let obj = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(rawValue: 0))
dispatch_async(dispatch_get_main_queue(), { () -> Void in
finished(result: obj, error: nil)
})
}catch{
finished(result: nil, error: NetworkError.emptyDataError.error())
}
}.resume()
}
} | b7920e38d7f5a95ae27b35262794accb | 25.086486 | 119 | 0.550674 | false | false | false | false |
fahidattique55/FAPanels | refs/heads/master | FAPanels/Classes/FAPanel.swift | apache-2.0 | 1 | //
// FAPanel.swift
// FAPanels
//
// Created by Fahid Attique on 10/06/2017.
// Copyright © 2017 Fahid Attique. All rights reserved.
//
import UIKit
// FAPanel Delegate
public protocol FAPanelStateDelegate {
func centerPanelWillBecomeActive()
func leftPanelWillBecomeActive()
func rightPanelWillBecomeActive()
func centerPanelDidBecomeActive()
func leftPanelDidBecomeActive()
func rightPanelDidBecomeActive()
}
public extension FAPanelStateDelegate {
func centerPanelWillBecomeActive() {}
func leftPanelWillBecomeActive() {}
func rightPanelWillBecomeActive() {}
func centerPanelDidBecomeActive() {}
func leftPanelDidBecomeActive() {}
func rightPanelDidBecomeActive() {}
}
// Left Panel Position
public enum FASidePanelPosition: Int {
case front = 0, back
}
// FAPanel Controller
open class FAPanelController: UIViewController {
// MARK:- Open
open var configs = FAPanelConfigurations()
open func center( _ controller: UIViewController, afterThat completion: (() -> Void)?) {
setCenterPanelVC(controller, afterThat: completion)
}
@discardableResult
open func center( _ controller: UIViewController) -> FAPanelController {
centerPanelVC = controller
return self
}
@discardableResult
open func left( _ controller: UIViewController?) -> FAPanelController {
leftPanelVC = controller
return self
}
@discardableResult
open func right( _ controller: UIViewController?) -> FAPanelController {
rightPanelVC = controller
return self
}
open func openLeft(animated:Bool) {
openLeft(animated: animated, shouldBounce: configs.bounceOnLeftPanelOpen)
}
open func openRight(animated:Bool) {
openRight(animated: animated, shouldBounce: configs.bounceOnRightPanelOpen)
}
open func openCenter(animated:Bool) { // Can be used for the same menu option selected
if centerPanelHidden {
centerPanelHidden = false
unhideCenterPanel()
}
openCenter(animated: animated, shouldBounce: configs.bounceOnCenterPanelOpen, afterThat: nil)
}
open func closeLeft() {
if isLeftPanelOnFront { slideLeftPanelOut(animated: true, afterThat: nil) }
else { openCenter(animated: true) }
}
open func closeRight() {
if isRightPanelOnFront { slideRightPanelOut(animated: true, afterThat: nil) }
else { openCenter(animated: true) }
}
// MARK:- Life Cycle
public init() {
super.init(nibName: nil, bundle: nil)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override open func viewDidLoad() {
super.viewDidLoad()
viewConfigurations()
}
override open func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
layoutSideContainers(withDuration: 0.0, animated: false)
layoutSidePanelVCs()
centerPanelContainer.frame = updateCenterPanelSlidingFrame()
}
override open func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
_ = updateCenterPanelSlidingFrame()
}
override open func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
let shadowPath = UIBezierPath(rect: leftPanelContainer.bounds)
leftPanelContainer.layer.masksToBounds = false
leftPanelContainer.layer.shadowColor = configs.shadowColor
leftPanelContainer.layer.shadowOffset = configs.shadowOffset
leftPanelContainer.layer.shadowOpacity = configs.shadowOppacity
leftPanelContainer.layer.shadowPath = shadowPath.cgPath
}
deinit {
if centerPanelVC != nil {
centerPanelVC!.removeObserver(self, forKeyPath: keyPathOfView)
}
}
private func viewConfigurations() {
view.autoresizingMask = [.flexibleHeight, .flexibleWidth]
centerPanelContainer = UIView(frame: view.bounds)
centeralPanelSlidingFrame = self.centerPanelContainer.frame
centerPanelHidden = false
leftPanelContainer = UIView(frame: view.bounds)
layoutLeftContainer()
leftPanelContainer.isHidden = true
rightPanelContainer = UIView(frame: view.bounds)
layoutRightContainer()
rightPanelContainer.isHidden = true
containersConfigurations()
view.addSubview(centerPanelContainer)
view.addSubview(leftPanelContainer)
view.addSubview(rightPanelContainer)
state = .center
swapCenter(animated: false, FromVC: nil, withVC: centerPanelVC)
view.bringSubviewToFront(centerPanelContainer)
tapView = UIView()
tapView?.alpha = 0.0
}
private func containersConfigurations() {
leftPanelContainer.autoresizingMask = [.flexibleHeight, .flexibleRightMargin]
rightPanelContainer.autoresizingMask = [.flexibleHeight, .flexibleLeftMargin]
centerPanelContainer.autoresizingMask = [.flexibleHeight, .flexibleWidth]
centerPanelContainer.frame = view.bounds
}
// MARK:- internal Properties
internal var leftPanelContainer : UIView!
internal var rightPanelContainer : UIView!
internal var centerPanelContainer: UIView!
internal var visiblePanelVC: UIViewController!
internal var centeralPanelSlidingFrame: CGRect = CGRect.zero
internal var centerPanelOriginBeforePan: CGPoint = CGPoint.zero
internal var leftPanelOriginBeforePan: CGPoint = CGPoint.zero
internal var rightPanelOriginBeforePan: CGPoint = CGPoint.zero
internal let keyPathOfView = "view"
internal static var kvoContext: Character!
internal var _leftPanelPosition : FASidePanelPosition = .back {
didSet {
if _leftPanelPosition == .front {
configs.resizeLeftPanel = false
}
layoutLeftContainer()
}
}
internal var isLeftPanelOnFront : Bool {
return leftPanelPosition == .front
}
open var leftPanelPosition : FASidePanelPosition {
get {
return _leftPanelPosition
}
set {
_leftPanelPosition = newValue
}
}
internal var _rightPanelPosition : FASidePanelPosition = .back {
didSet {
if _rightPanelPosition == .front {
configs.resizeRightPanel = true
}
layoutRightContainer()
layoutSidePanelVCs()
}
}
internal var isRightPanelOnFront : Bool {
return rightPanelPosition == .front
}
open var rightPanelPosition : FASidePanelPosition {
get {
return _rightPanelPosition
}
set {
_rightPanelPosition = newValue
}
}
internal enum GestureStartDirection: UInt { case left = 0, right, none }
internal var paningStartDirection: GestureStartDirection = .none
internal var _leftPanelVC: UIViewController? = nil
internal var leftPanelVC : UIViewController? {
get{
return _leftPanelVC
}
set{
if newValue != _leftPanelVC {
_leftPanelVC?.willMove(toParent: nil)
_leftPanelVC?.view.removeFromSuperview()
_leftPanelVC?.removeFromParent()
_leftPanelVC = newValue
if _leftPanelVC != nil {
addChild(_leftPanelVC!)
_leftPanelVC!.didMove(toParent: self)
}
else {
leftPanelContainer.isHidden = true
}
if state == .left {
visiblePanelVC = _leftPanelVC
}
}
}
}
open var left: UIViewController? {
get {
return leftPanelVC
}
}
internal var _rightPanelVC: UIViewController? = nil
internal var rightPanelVC : UIViewController? {
get{
return _rightPanelVC
}
set{
if newValue != _rightPanelVC {
_rightPanelVC?.willMove(toParent: nil)
_rightPanelVC?.view.removeFromSuperview()
_rightPanelVC?.removeFromParent()
_rightPanelVC = newValue
if _rightPanelVC != nil {
addChild(_rightPanelVC!)
_rightPanelVC?.didMove(toParent: self)
}
else {
rightPanelContainer.isHidden = true
}
if state == .right {
visiblePanelVC = _rightPanelVC
}
}
}
}
open var right: UIViewController? {
get {
return rightPanelVC
}
}
internal var _centerPanelVC: UIViewController? = nil
internal var centerPanelVC : UIViewController? {
get{
return _centerPanelVC
}
set{
setCenterPanelVC(newValue, afterThat: nil)
}
}
open var center: UIViewController? {
get {
return centerPanelVC
}
}
internal func setCenterPanelVC( _ newValue: UIViewController?, afterThat completion: (() -> Void)? = nil) {
let previousVC: UIViewController? = _centerPanelVC
if _centerPanelVC != newValue {
_centerPanelVC?.removeObserver(self, forKeyPath: keyPathOfView)
_centerPanelVC = newValue
_centerPanelVC!.addObserver(self, forKeyPath: keyPathOfView, options: NSKeyValueObservingOptions.initial, context: &FAPanelController.kvoContext)
if state == .center {
visiblePanelVC = _centerPanelVC
}
}
if isViewLoaded && state == .center {
swapCenter(animated: configs.changeCenterPanelAnimated, FromVC: previousVC, withVC: _centerPanelVC!)
}
else if (self.isViewLoaded) {
if state == .left {
if isLeftPanelOnFront {
swapCenter(animated: false,FromVC: previousVC, withVC: self._centerPanelVC)
slideLeftPanelOut(animated: true, afterThat: completion)
return
}
}
else if state == .right {
if isRightPanelOnFront {
swapCenter(animated: false, FromVC: previousVC, withVC: self._centerPanelVC)
slideRightPanelOut(animated: true, afterThat: completion)
return
}
}
UIView.animate(withDuration: 0.2, animations: {
if self.configs.bounceOnCenterPanelChange {
let x: CGFloat = (self.state == .left) ? self.view.bounds.size.width : -self.view.bounds.size.width
self.centeralPanelSlidingFrame.origin.x = x
}
self.centerPanelContainer.frame = self.centeralPanelSlidingFrame
}, completion: { (finised) in
self.swapCenter(animated: false,FromVC: previousVC, withVC: self._centerPanelVC)
self.openCenter(animated: true, shouldBounce: false, afterThat: completion)
})
}
}
// Left panel frame on basis of its position type i.e: front or back
internal func layoutLeftContainer() {
if isLeftPanelOnFront {
if leftPanelContainer != nil {
var frame = leftPanelContainer.frame
frame.size.width = widthForLeftPanelVC
frame.origin.x = -widthForLeftPanelVC
leftPanelContainer.frame = frame
}
}
else {
if leftPanelContainer != nil {
leftPanelContainer.frame = view.bounds
}
}
}
internal func layoutRightContainer() {
if isRightPanelOnFront {
if rightPanelContainer != nil {
var frame = rightPanelContainer.frame
frame.size.width = widthForRightPanelVC
frame.origin.x = view.frame.size.width
rightPanelContainer.frame = frame
}
}
else {
if rightPanelContainer != nil {
rightPanelContainer.frame = view.bounds
}
}
}
// tap view on centeral panel, to dismiss side panels if visible
internal var _tapView: UIView? = nil
internal var tapView: UIView? {
get{
return _tapView
}
set{
if newValue != _tapView {
_tapView?.removeFromSuperview()
_tapView = newValue
if _tapView != nil {
_tapView?.backgroundColor = configs.colorForTapView
_tapView?.frame = centerPanelContainer.bounds
_tapView?.autoresizingMask = [.flexibleWidth, .flexibleHeight]
addTapGestureToView(view: _tapView!)
if configs.canRecognizePanGesture { addPanGesture(toView: _tapView!) }
centerPanelContainer.addSubview(_tapView!)
}
}
}
}
// visible widths for side panels
internal var widthForLeftPanelVC: CGFloat {
get{
if centerPanelHidden && configs.resizeLeftPanel {
return view.bounds.size.width
}
else {
return configs.leftPanelWidth == 0.0 ? CGFloat(floorf(Float(view.bounds.size.width * configs.leftPanelGapPercentage))) : configs.leftPanelWidth
}
}
}
internal var widthForRightPanelVC: CGFloat {
get{
if centerPanelHidden && configs.resizeRightPanel {
return view.bounds.size.width
}
else {
return configs.rightPanelWidth == 0 ? CGFloat(floorf(Float(view.bounds.size.width * configs.rightPanelGapPercentage))) : configs.rightPanelWidth
}
}
}
// style for panels
internal func applyStyle(onView: UIView) {
onView.layer.cornerRadius = configs.cornerRadius
onView.clipsToBounds = true
}
// Panel States
open var delegate: FAPanelStateDelegate? = nil
internal var _state: FAPanelVisibleState = .center {
willSet {
switch newValue {
case .center:
delegate?.centerPanelWillBecomeActive()
break
case .left:
delegate?.leftPanelWillBecomeActive()
break
case .right:
delegate?.rightPanelWillBecomeActive()
break
}
}
didSet {
switch _state {
case .center:
delegate?.centerPanelDidBecomeActive()
break
case .left:
delegate?.leftPanelDidBecomeActive()
break
case .right:
delegate?.rightPanelDidBecomeActive()
break
}
}
}
internal var state: FAPanelVisibleState {
get{
return _state
}
set{
if _state != newValue {
_state = newValue
switch _state {
case .center:
visiblePanelVC = centerPanelVC
leftPanelContainer.isUserInteractionEnabled = false
rightPanelContainer.isUserInteractionEnabled = false
break
case .left:
visiblePanelVC = leftPanelVC
leftPanelContainer.isUserInteractionEnabled = true
break
case .right:
visiblePanelVC = rightPanelVC
rightPanelContainer.isUserInteractionEnabled = true
break
}
setNeedsStatusBarAppearanceUpdate()
}
}
}
// Center Panel Hiding Functions
internal var _centerPanelHidden: Bool = false
internal var centerPanelHidden: Bool {
get{
return _centerPanelHidden
}
set{
setCenterPanelHidden(newValue, animated: false, duration: 0.0)
}
}
internal func setCenterPanelHidden(_ hidden: Bool, animated: Bool, duration: TimeInterval) {
if hidden != _centerPanelHidden && state != .center {
_centerPanelHidden = hidden
let animationDuration = animated ? duration : 0.0
if hidden {
UIView.animate(withDuration: animationDuration, animations: {
var frame: CGRect = self.centerPanelContainer.frame
frame.origin.x = self.state == .left ? self.centerPanelContainer.frame.size.width : -self.centerPanelContainer.frame.size.width
self.centerPanelContainer.frame = frame
self.layoutSideContainers(withDuration: 0.0, animated: false)
if self.configs.resizeLeftPanel || self.configs.resizeRightPanel {
self.layoutSidePanelVCs()
}
}, completion: { (finished) in
if self._centerPanelHidden {
self.hideCenterPanel()
}
})
}
else {
unhideCenterPanel()
UIView.animate(withDuration: animationDuration, animations: {
if self.state == .left {
self.openLeft(animated: false)
}
else {
self.openRight(animated: false)
}
if self.configs.resizeLeftPanel || self.configs.resizeRightPanel {
self.layoutSidePanelVCs()
}
})
}
}
}
}
| 972ef3b67df854a90498b7dda246af27 | 25.125837 | 160 | 0.532076 | false | false | false | false |
karstengresch/trhs-ios | refs/heads/master | stormy/Stormy/Stormy/DailyWeather.swift | unlicense | 1 | //
// DailyWeather.swift
// Stormy
//
// Created by Karsten Gresch on 07.09.15.
// Copyright (c) 2015 Closure One. All rights reserved.
//
import Foundation
import UIKit
struct DailyWeather {
let maxTemperature: Int?
let minTemperature: Int?
let humidity: Int?
let preciperationChance: Int?
let summary: String?
var icon: UIImage? = UIImage(named: "default.png")
var largeIcon: UIImage? = UIImage(named: "default_large.png")
var sunriseTime: String?
var sunsetTime: String?
var day: String?
let dateFormatter = NSDateFormatter()
init(dailyweatherData: [String: AnyObject]) {
maxTemperature = dailyweatherData["temperatureMax"] as? Int
minTemperature = dailyweatherData["temperatureMin"] as? Int
if let humidityFloat = dailyweatherData["humidity"] as? Double {
humidity = Int(humidityFloat * 100)
} else {
humidity = nil
}
if let preciperationChanceFloat = dailyweatherData["precipProbability"] as? Double {
preciperationChance = Int(preciperationChanceFloat * 100)
} else {
preciperationChance = nil
}
summary = dailyweatherData["summary"] as? String
if let iconString = dailyweatherData["icon"] as? String,
let iconEnum = Icon(rawValue: iconString) {
(icon, largeIcon) = iconEnum.toImage()
}
if let sunriseDate = dailyweatherData["sunriseTime"] as? Double {
sunriseTime = timeStringFromUnixTime(sunriseDate)
} else {
sunriseTime = nil
}
if let sunsetDate = dailyweatherData["sunsetTime"] as? Double {
sunsetTime = timeStringFromUnixTime(sunsetDate)
} else {
sunsetTime = nil
}
if let time = dailyweatherData["time"] as? Double {
day = dayStringFromTime(time)
}
}
func timeStringFromUnixTime(unixTime: Double) -> String {
let date = NSDate(timeIntervalSince1970: unixTime)
// "hh:mm a"
dateFormatter.dateFormat = "HH:mm"
return dateFormatter.stringFromDate(date)
}
func dayStringFromTime(time: Double) -> String {
let date = NSDate(timeIntervalSince1970: time)
dateFormatter.locale = NSLocale(localeIdentifier: NSLocale.currentLocale().localeIdentifier)
dateFormatter.dateFormat = "EEEE"
return dateFormatter.stringFromDate(date)
}
}
| b7ead9ef6ba794468a522aeaf6d358a6 | 27.530864 | 96 | 0.678494 | false | false | false | false |
xuzhenguo/LayoutComposer | refs/heads/master | Example/LayoutComposer/TopViewController.swift | mit | 1 | //
// TopViewController.swift
// LayoutComposer
//
// Created by Yusuke Kawakami on 08/22/2015.
// Copyright (c) 2015 Yusuke Kawakami. All rights reserved.
//
import UIKit
import LayoutComposer
class TopViewController: BaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func loadView() {
doLayout()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func doLayout() {
view = UIView()
view.backgroundColor = UIColor.whiteColor()
let header = UIView()
header.backgroundColor = UIColor.blackColor()
let titleLabel = UILabel()
titleLabel.text = "LayoutComposer Examples"
titleLabel.textColor = UIColor.whiteColor()
let scrollView = UIScrollView()
view.applyLayout(VBox(), items: [
$(header, height: 65, layout: Relative(), item:
$(titleLabel, halign: .Center, marginTop: 20)
),
$(scrollView, flex: 1, layout: VBox(align: .Center, pack: .Fit, defaultMargins: (10, 0, 0, 0)), items: [
$(makeButton(title: "VBox Basic", action: "onVBoxExampleTapped:", tag: VBoxExampleType.Basic.rawValue)),
$(makeButton(title: "VBox Margin", action: "onVBoxExampleTapped:", tag: VBoxExampleType.Margin.rawValue)),
$(makeButton(title: "VBox Default Margin", action: "onVBoxExampleTapped:", tag: VBoxExampleType.DefaultMargin.rawValue)),
$(makeButton(title: "VBox Flex Height", action: "onVBoxExampleTapped:", tag: VBoxExampleType.Flex.rawValue)),
$(makeButton(title: "VBox Align Start(Left)", action: "onVBoxExampleTapped:", tag: VBoxExampleType.AlignStart.rawValue)),
$(makeButton(title: "VBox Align End(Right)", action: "onVBoxExampleTapped:", tag: VBoxExampleType.AlignEnd.rawValue)),
$(makeButton(title: "VBox Align Center", action: "onVBoxExampleTapped:", tag: VBoxExampleType.AlignCenter.rawValue)),
$(makeButton(title: "VBox Align Stretch", action: "onVBoxExampleTapped:", tag: VBoxExampleType.AlignStretch.rawValue)),
$(makeButton(title: "VBox Align Each Component", action: "onVBoxExampleTapped:", tag: VBoxExampleType.AlignEachComponent.rawValue)),
$(makeButton(title: "VBox Pack Start(Top)", action: "onVBoxExampleTapped:", tag: VBoxExampleType.PackStart.rawValue)),
$(makeButton(title: "VBox Pack End(Bottom)", action: "onVBoxExampleTapped:", tag: VBoxExampleType.PackEnd.rawValue)),
$(makeButton(title: "VBox Pack Center", action: "onVBoxExampleTapped:", tag: VBoxExampleType.PackCenter.rawValue)),
$(makeButton(title: "VBox Pack Fit", action: "onVBoxExampleTapped:", tag: VBoxExampleType.PackFit.rawValue)),
$(makeButton(title: "HBox Basic", action: "onHBoxExampleTapped:", tag: HBoxExampleType.Basic.rawValue)),
$(makeButton(title: "HBox Margin", action: "onHBoxExampleTapped:", tag: HBoxExampleType.Margin.rawValue)),
$(makeButton(title: "HBox Default Margin", action: "onHBoxExampleTapped:", tag: HBoxExampleType.DefaultMargin.rawValue)),
$(makeButton(title: "HBox Flex Width", action: "onHBoxExampleTapped:", tag: HBoxExampleType.Flex.rawValue)),
$(makeButton(title: "HBox Align Start(Top)", action: "onHBoxExampleTapped:", tag: HBoxExampleType.AlignStart.rawValue)),
$(makeButton(title: "HBox Align End(Bottom)", action: "onHBoxExampleTapped:", tag: HBoxExampleType.AlignEnd.rawValue)),
$(makeButton(title: "HBox Align Center", action: "onHBoxExampleTapped:", tag: HBoxExampleType.AlignCenter.rawValue)),
$(makeButton(title: "HBox Align Stretch", action: "onHBoxExampleTapped:", tag: HBoxExampleType.AlignStretch.rawValue)),
$(makeButton(title: "HBox Align Each Component", action: "onHBoxExampleTapped:", tag: HBoxExampleType.AlignEachComponent.rawValue)),
$(makeButton(title: "HBox Pack Start(Left)", action: "onHBoxExampleTapped:", tag: HBoxExampleType.PackStart.rawValue)),
$(makeButton(title: "HBox Pack End(Right)", action: "onHBoxExampleTapped:", tag: HBoxExampleType.PackEnd.rawValue)),
$(makeButton(title: "HBox Pack Center", action: "onHBoxExampleTapped:", tag: HBoxExampleType.PackCenter.rawValue)),
$(makeButton(title: "HBox Pack Fit", action: "onHBoxExampleTapped:", tag: HBoxExampleType.PackFit.rawValue)),
$(makeButton(title: "Relative 1", action: "onRelativeExampleTapped:", tag: RelativeExampleType.Example1.rawValue)),
$(makeButton(title: "Relative 2", action: "onRelativeExampleTapped:", tag: RelativeExampleType.Example2.rawValue)),
$(makeButton(title: "Relative 3", action: "onRelativeExampleTapped:", tag: RelativeExampleType.Example3.rawValue)),
$(makeButton(title: "Fit", action: "onFitExampleTapped:", tag: FitExampleType.Example1.rawValue)),
$(makeButton(title: "Nesting Layout", action: "onNestExampleTapped:", tag: NestExampleType.Example1.rawValue))
])
])
}
private func makeButton(#title: String, action: Selector, tag: Int) -> UIButton {
let button = UIButton.buttonWithType(.System) as! UIButton
button.setTitle(title, forState: .Normal)
button.addTarget(self, action: action, forControlEvents: .TouchUpInside)
button.tag = tag
return button
}
func onVBoxExampleTapped(sender: UIButton) {
if let title = sender.titleForState(.Normal),
exampleType = VBoxExampleType(rawValue: sender.tag)
{
let vc = VBoxExampleViewController(exampleType: exampleType, headerTitle: title)
navigationController?.pushViewController(vc, animated: true)
}
}
func onHBoxExampleTapped(sender: UIButton) {
if let title = sender.titleForState(.Normal),
exampleType = HBoxExampleType(rawValue: sender.tag)
{
let vc = HBoxExampleViewController(exampleType: exampleType, headerTitle: title)
navigationController?.pushViewController(vc, animated: true)
}
}
func onRelativeExampleTapped(sender: UIButton) {
if let title = sender.titleForState(.Normal),
exampleType = RelativeExampleType(rawValue: sender.tag)
{
let vc = RelativeExampleViewController(exampleType: exampleType, headerTitle: title)
navigationController?.pushViewController(vc, animated: true)
}
}
func onFitExampleTapped(sender: UIButton) {
if let title = sender.titleForState(.Normal),
exampleType = FitExampleType(rawValue: sender.tag)
{
let vc = FitExampleViewController(exampleType: exampleType, headerTitle: title)
navigationController?.pushViewController(vc, animated: true)
}
}
func onNestExampleTapped(sender: UIButton) {
if let title = sender.titleForState(.Normal),
exampleType = NestExampleType(rawValue: sender.tag)
{
let vc = NestExampleViewController(exampleType: exampleType, headerTitle: title)
navigationController?.pushViewController(vc, animated: true)
}
}
}
| cc5759bd1875e5dda948f292b1632842 | 54.583942 | 148 | 0.655417 | false | false | false | false |
lgp123456/tiantianTV | refs/heads/master | douyuTV/douyuTV/douyuTV.swift | mit | 1 | //
// douyuTV.swift
// douyuTV
//
// Created by 李贵鹏 on 16/8/24.
// Copyright © 2016年 李贵鹏. All rights reserved.
//
import UIKit
///屏幕宽度
let XTScreenW = UIScreen.mainScreen().bounds.width
///屏幕高度
let XTScreenH = UIScreen.mainScreen().bounds.height
///顶部预留的间距
let XTTopSpace = XTScreenW / 414 * 240
///标题(顶部view)栏高度
let XTTopViewH = XTScreenW / 414 * 35
///间距
let XTMagin = 10
///基本的url
let baseUrl = "http://capi.douyucdn.cn" | fb293896f83fbfec6e096913b264d739 | 15.730769 | 51 | 0.679724 | false | false | false | false |
Caktuspace/iTunesCover | refs/heads/master | iTunesCover/iTunesCover/Classes/Modules/List/User Interface/Presenter/AlbumDisplayData.swift | gpl-2.0 | 1 | //
// AlbumDisplayData.swift
// iTunesCover
//
// Created by Quentin Metzler on 20/12/15.
// Copyright © 2015 LocalFitness. All rights reserved.
//
import Foundation
struct AlbumDisplayData : Equatable {
var items : [AlbumDisplayItem] = []
init(items: [AlbumDisplayItem]) {
self.items = items
}
}
func == (leftSide: AlbumDisplayData, rightSide: AlbumDisplayData) -> Bool {
var hasEqualSections = false
hasEqualSections = rightSide.items == leftSide.items
return hasEqualSections
} | 133f92885ae7bff1f1ca6698be73c3b4 | 21.826087 | 75 | 0.688931 | false | false | false | false |
HamzaGhazouani/HGCircularSlider | refs/heads/master | HGCircularSlider/Classes/CircularSlider.swift | mit | 1 | //
// CircularSlider.swift
// Pods
//
// Created by Hamza Ghazouani on 19/10/2016.
//
//
import UIKit
/**
* A visual control used to select a single value from a continuous range of values.
* Can also be used like a circular progress view
* CircularSlider uses the target-action mechanism to report changes made during the course of editing:
* ValueChanged, EditingDidBegin and EditingDidEnd
*/
@IBDesignable
open class CircularSlider: UIControl {
// MARK: Changing the Slider’s Appearance
/**
* The color shown for the selected portion of the slider disk. (between start and end values)
* The default value is a transparent color.
*/
@IBInspectable
open var diskFillColor: UIColor = .clear
/**
* The color shown for the unselected portion of the slider disk. (outside start and end values)
* The default value of this property is the black color with alpha = 0.3.
*/
@IBInspectable
open var diskColor: UIColor = .gray
/**
* The color shown for the selected track portion. (between start and end values)
* The default value of this property is the tint color.
*/
@IBInspectable
open var trackFillColor: UIColor = .clear
/**
* The color shown for the unselected track portion. (outside start and end values)
* The default value of this property is the white color.
*/
@IBInspectable
open var trackColor: UIColor = .white
/**
* The width of the circular line
*
* The default value of this property is 5.0.
*/
@IBInspectable
open var lineWidth: CGFloat = 5.0
/**
* The width of the unselected track portion of the slider
*
* The default value of this property is 5.0.
*/
@IBInspectable
open var backtrackLineWidth: CGFloat = 5.0
/**
* The shadow offset of the slider
*
* The default value of this property is .zero.
*/
@IBInspectable
open var trackShadowOffset: CGPoint = .zero
/**
* The color of the shadow offset of the slider
*
* The default value of this property is .gray.
*/
@IBInspectable
open var trackShadowColor: UIColor = .gray
/**
* The width of the thumb stroke line
*
* The default value of this property is 4.0.
*/
@IBInspectable
open var thumbLineWidth: CGFloat = 4.0
/**
* The radius of the thumb
*
* The default value of this property is 13.0.
*/
@IBInspectable
open var thumbRadius: CGFloat = 13.0
/**
* The color used to tint the thumb
* Ignored if the endThumbImage != nil
*
* The default value of this property is the groupTableViewBackgroundColor.
*/
@IBInspectable
open var endThumbTintColor: UIColor = .groupTableViewBackground
/**
* The stroke highlighted color of the end thumb
* The default value of this property is blue
*/
@IBInspectable
open var endThumbStrokeHighlightedColor: UIColor = .blue
/**
* The color used to tint the stroke of the end thumb
* Ignored if the endThumbImage != nil
*
* The default value of this property is red.
*/
@IBInspectable
open var endThumbStrokeColor: UIColor = .red
/**
* The image of the end thumb
* Clears any custom color you may have provided for the end thumb.
*
* The default value of this property is nil
*/
open var endThumbImage: UIImage?
// MARK: Accessing the Slider’s Value Limits
/**
* Fixed number of rounds - how many circles has user to do to reach max value (like apple bedtime clock - which have 2)
* the default value if this property is 1
*/
@IBInspectable
open var numberOfRounds: Int = 1 {
didSet {
assert(numberOfRounds > 0, "Number of rounds has to be positive value!")
setNeedsDisplay()
}
}
/**
* The minimum value of the receiver.
*
* If you change the value of this property, and the end value of the receiver is below the new minimum, the end point value is adjusted to match the new minimum value automatically.
* The default value of this property is 0.0.
*/
@IBInspectable
open var minimumValue: CGFloat = 0.0 {
didSet {
if endPointValue < minimumValue {
endPointValue = minimumValue
}
}
}
/**
* The maximum value of the receiver.
*
* If you change the value of this property, and the end value of the receiver is above the new maximum, the end value is adjusted to match the new maximum value automatically.
* The default value of this property is 1.0.
*/
@IBInspectable
open var maximumValue: CGFloat = 1.0 {
didSet {
if endPointValue > maximumValue {
endPointValue = maximumValue
}
}
}
/**
* The offset of the thumb centre from the circle.
*
* You can use this to move the thumb inside or outside the circle of the slider
* If the value is grather than 0 the thumb will be displayed outside the cirlce
* And if the value is negative, the thumb will be displayed inside the circle
*/
@IBInspectable
open var thumbOffset: CGFloat = 0.0 {
didSet {
setNeedsDisplay()
}
}
/**
* Stop the thumb going beyond the min/max.
*
*/
@IBInspectable
open var stopThumbAtMinMax: Bool = false
/**
* The value of the endThumb (changed when the user change the position of the end thumb)
*
* If you try to set a value that is above the maximum value, the property automatically resets to the maximum value.
* And if you try to set a value that is below the minimum value, the property automatically resets to the minimum value.
*
* The default value of this property is 0.5
*/
open var endPointValue: CGFloat = 0.5 {
didSet {
if oldValue == endPointValue {
return
}
if endPointValue > maximumValue {
endPointValue = maximumValue
}
if endPointValue < minimumValue {
endPointValue = minimumValue
}
setNeedsDisplay()
}
}
/**
* The radius of circle
*/
internal var radius: CGFloat {
get {
// the minimum between the height/2 and the width/2
var radius = min(bounds.center.x, bounds.center.y)
// if we use an image for the thumb, the radius of the image will be used
let maxThumbRadius = max(thumbRadius, (self.endThumbImage?.size.height ?? 0) / 2)
// all elements should be inside the view rect, for that we should subtract the highest value between the radius of thumb and the line width
radius -= max(lineWidth, (maxThumbRadius + thumbLineWidth + thumbOffset))
return radius
}
}
/// See superclass documentation
override open var isHighlighted: Bool {
didSet {
setNeedsDisplay()
}
}
// MARK: init methods
/**
See superclass documentation
*/
override public init(frame: CGRect) {
super.init(frame: frame)
setup()
}
/**
See superclass documentation
*/
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
internal func setup() {
trackFillColor = tintColor
}
// MARK: Drawing methods
/**
See superclass documentation
*/
override open func draw(_ rect: CGRect) {
guard let context = UIGraphicsGetCurrentContext() else { return }
drawCircularSlider(inContext: context)
let valuesInterval = Interval(min: minimumValue, max: maximumValue, rounds: numberOfRounds)
// get end angle from end value
let endAngle = CircularSliderHelper.scaleToAngle(value: endPointValue, inInterval: valuesInterval) + CircularSliderHelper.circleInitialAngle
drawFilledArc(fromAngle: CircularSliderHelper.circleInitialAngle, toAngle: endAngle, inContext: context)
// draw end thumb
endThumbTintColor.setFill()
(isHighlighted == true) ? endThumbStrokeHighlightedColor.setStroke() : endThumbStrokeColor.setStroke()
drawThumbAt(endAngle, with: endThumbImage, inContext: context)
}
// MARK: User interaction methods
/**
See superclass documentation
*/
override open func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
sendActions(for: .editingDidBegin)
return true
}
/**
See superclass documentation
*/
override open func continueTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
// the position of the pan gesture
let touchPosition = touch.location(in: self)
let startPoint = CGPoint(x: bounds.center.x, y: 0)
let value = newValue(from: endPointValue, touch: touchPosition, start: startPoint)
endPointValue = value
sendActions(for: .valueChanged)
return true
}
/**
See superclass documentation
*/
open override func endTracking(_ touch: UITouch?, with event: UIEvent?) {
sendActions(for: .editingDidEnd)
}
// MARK: Utilities methods
internal func newValue(from oldValue: CGFloat, touch touchPosition: CGPoint, start startPosition: CGPoint) -> CGFloat {
let angle = CircularSliderHelper.angle(betweenFirstPoint: startPosition, secondPoint: touchPosition, inCircleWithCenter: bounds.center)
let interval = Interval(min: minimumValue, max: maximumValue, rounds: numberOfRounds)
let deltaValue = CircularSliderHelper.delta(in: interval, for: angle, oldValue: oldValue)
var newValue = oldValue + deltaValue - minimumValue
let range = maximumValue - minimumValue
if !stopThumbAtMinMax {
if newValue > maximumValue {
newValue -= range
}
else if newValue < minimumValue {
newValue += range
}
}
return newValue
}
}
| 4b3bd6a862fd934af53985064a200c59 | 29.176301 | 186 | 0.617182 | false | false | false | false |
Abedalkareem/LanguageManger-iOS | refs/heads/master | Example/LanguageManger-iOS/SettingsViewController.swift | mit | 1 | //
// SettingsViewController.swift
// LanguageManager
//
// Created by abedalkareem omreyh on 4/9/17.
// Copyright © 2017 abedalkareem. All rights reserved.
//
import UIKit
import LanguageManager_iOS
class SettingsViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func changeLanguage(_ sender: UIButton) {
let selectedLanguage: Languages = sender.tag == 1 ? .en : .ar
// change the language
LanguageManager.shared.setLanguage(language: selectedLanguage,
viewControllerFactory: { title -> UIViewController in
let storyboard = UIStoryboard(name: "Main", bundle: nil)
// the view controller that you want to show after changing the language
return storyboard.instantiateInitialViewController()!
}) { view in
// do custom animation
view.transform = CGAffineTransform(scaleX: 2, y: 2)
view.alpha = 0
}
}
}
| 4290e381b414a55568d8603a39a9b88a | 25.162162 | 92 | 0.674587 | false | false | false | false |
MastodonKit/MastodonKit | refs/heads/master | Sources/MastodonKit/Requests/Lists.swift | mit | 1 | //
// Lists.swift
// MastodonKit
//
// Created by Ornithologist Coder on 1/2/18.
// Copyright © 2018 MastodonKit. All rights reserved.
//
import Foundation
/// `Lists` requests.
public enum Lists {
/// Retrieves lists.
///
/// - Returns: Request for `[List]`.
public static func all() -> Request<[List]> {
return Request<[List]>(path: "/api/v1/lists")
}
/// Retrieves accounts in a list.
///
/// - Parameter id: The list ID.
/// - Returns: Request for `[Account]`.
public static func accounts(id: String) -> Request<[Account]> {
return Request<[Account]>(path: "/api/v1/lists/\(id)/accounts")
}
/// Retrieves a list.
///
/// - Parameter id: The list ID.
/// - Returns: Request for `List`.
public static func list(id: String) -> Request<List> {
return Request<List>(path: "/api/v1/lists/\(id)")
}
/// Creates a list.
///
/// - Parameter title: The title of the list.
/// - Returns: Request for `List`.
public static func create(title: String) -> Request<List> {
let parameter = [Parameter(name: "title", value: title)]
let method = HTTPMethod.post(.parameters(parameter))
return Request<List>(path: "/api/v1/lists", method: method)
}
/// Updates the list title.
///
/// - Parameters:
/// - id: The list ID.
/// - title: The title of the list.
/// - Returns: Request for `List`.
public static func update(id: String, title: String) -> Request<List> {
let parameter = [Parameter(name: "title", value: title)]
let method = HTTPMethod.put(.parameters(parameter))
return Request<List>(path: "/api/v1/lists/\(id)", method: method)
}
/// Deletes a list.
///
/// - Parameter id: The list ID.
/// - Returns: Request for `Empty`.
public static func delete(id: String) -> Request<Empty> {
return Request<Empty>(path: "/api/v1/lists/\(id)", method: .delete(.empty))
}
/// Adds accounts to a list.
///
/// - Parameters:
/// - accountIDs: The account IDs to be added to the list.
/// - id: The list ID>
/// - Returns: Request for `Empty`.
public static func add(accountIDs: [String], toList id: String) -> Request<Empty> {
let parameter = accountIDs.map(toArrayOfParameters(withName: "account_ids"))
let method = HTTPMethod.post(.parameters(parameter))
return Request<Empty>(path: "/api/v1/lists/\(id)/accounts", method: method)
}
/// Removes accounts from a list.
///
/// - Parameters:
/// - accountIDs: The account IDs to be removed from the list.
/// - id: The list ID>
/// - Returns: Request for `Empty`.
public static func remove(accountIDs: [String], fromList id: String) -> Request<Empty> {
let parameter = accountIDs.map(toArrayOfParameters(withName: "account_ids"))
let method = HTTPMethod.delete(.parameters(parameter))
return Request<Empty>(path: "/api/v1/lists/\(id)/accounts", method: method)
}
}
| 3e2332df2439f98c03e8e85b017fb4b6 | 31.946237 | 92 | 0.594321 | false | false | false | false |
keygx/GradientCircularProgress | refs/heads/master | GCProgressSample/GradientCircularProgress/Progress/Elements/ArcView.swift | mit | 2 | //
// Arc.swift
// GradientCircularProgress
//
// Created by keygx on 2015/06/24.
// Copyright (c) 2015年 keygx. All rights reserved.
//
import UIKit
class ArcView: UIView {
var prop: Property?
var ratio: CGFloat = 1.0
var color: UIColor = UIColor.black
var lineWidth: CGFloat = 0.0
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init(frame: CGRect, lineWidth: CGFloat) {
super.init(frame: frame)
backgroundColor = UIColor.clear
layer.masksToBounds = true
self.lineWidth = lineWidth
}
override func draw(_ rect: CGRect) {
drawArc(rect: rect)
}
private func drawArc(rect: CGRect) {
guard let prop = prop else {
return
}
let circularRect: CGRect = prop.progressRect
let arcPoint: CGPoint = CGPoint(x: rect.width/2, y: rect.height/2)
let arcRadius: CGFloat = circularRect.width/2 + prop.arcLineWidth/2
let arcStartAngle: CGFloat = -CGFloat.pi/2
let arcEndAngle: CGFloat = ratio * 2.0 * CGFloat.pi - CGFloat.pi/2
let arc: UIBezierPath = UIBezierPath(arcCenter: arcPoint,
radius: arcRadius,
startAngle: arcStartAngle,
endAngle: arcEndAngle,
clockwise: true)
color.setStroke()
arc.lineWidth = lineWidth
arc.lineCapStyle = prop.arcLineCapStyle
arc.stroke()
}
}
| 351d94ffda7c59f93031b674c89754eb | 27.016393 | 79 | 0.528964 | false | false | false | false |
phatblat/3DTouchDemo | refs/heads/master | 3DTouchDemo/MasterViewController+UIViewControllerPreviewing.swift | mit | 1 | //
// MasterViewController.swift
// 3DTouchDemo
//
// Created by Ben Chatelain on 9/28/15.
// Copyright © 2015 Ben Chatelain. All rights reserved.
//
import UIKit
extension MasterViewController: UIViewControllerPreviewingDelegate {
// MARK: - UIViewControllerPreviewingDelegate
/// Create a previewing view controller to be shown as a "Peek".
func previewingContext(previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
// Obtain the index path and the cell that was pressed.
guard let indexPath = tableView.indexPathForRowAtPoint(location),
cell = tableView.cellForRowAtIndexPath(indexPath) else { return nil }
if #available(iOS 9, *) {
// Set the source rect to the cell frame, so surrounding elements are blurred.
previewingContext.sourceRect = cell.frame
}
return viewControllerForIndexPath(indexPath)
}
/// Present the view controller for the "Pop" action.
func previewingContext(previewingContext: UIViewControllerPreviewing, commitViewController viewControllerToCommit: UIViewController) {
// Reuse the "Peek" view controller for presentation.
showViewController(viewControllerToCommit, sender: self)
}
}
extension MasterViewController {
private func viewControllerForIndexPath(indexPath: NSIndexPath) -> UIViewController? {
switch indexPath.row {
case 0..<touchCanvasRow:
// Create a detail view controller and set its properties.
guard let detailViewController = storyboard?.instantiateViewControllerWithIdentifier("DetailViewController") as? DetailViewController else { return nil }
let previewDetail = sampleData[indexPath.row]
detailViewController.detailItemTitle = previewDetail.title
if let color = previewDetail.color {
detailViewController.view.backgroundColor = color
}
// Set the height of the preview by setting the preferred content size of the detail view controller.
// Width should be zero, because it's not used in portrait.
detailViewController.preferredContentSize = CGSize(width: 0.0, height: previewDetail.preferredHeight)
return detailViewController
case touchCanvasRow:
return storyboard?.instantiateViewControllerWithIdentifier("TouchCanvasViewController")
case touchCanvasRow + 1:
return storyboard?.instantiateViewControllerWithIdentifier("ForceProgressViewController")
default:
return nil
}
}
}
| 4a3b75272d9df536b84b2d47b739ee6b | 37.695652 | 165 | 0.702996 | false | false | false | false |
Syject/MyLessPass-iOS | refs/heads/master | LessPass/Libraries/BigInteger/MG Benchmark Tools.swift | gpl-3.0 | 1 | /*
————————————————————————————————————————————————————————————————————————————
MG Benchmark Tools.swift
————————————————————————————————————————————————————————————————————————————
Created by Marcel Kröker on 03.04.15.
Copyright (c) 2016 Blubyte. All rights reserved.
*/
import Foundation
#if os(Linux)
import Glibc
import CBSD
private func mach_absolute_time() -> UInt64 {
var tv = timeval();
guard gettimeofday(&tv, nil) != -1 else { return 0 }
let t = UInt64(tv.tv_usec) + UInt64(tv.tv_sec) * 1000000
return t;
}
private struct mach_timebase_info_data_t {
var numer: Int = 1000
var denom: Int = 1
}
private func mach_timebase_info(_: inout mach_timebase_info_data_t) {}
#endif
private func durationNS(_ call: () -> ()) -> Int
{
var start = UInt64()
var end = UInt64()
start = mach_absolute_time()
call()
end = mach_absolute_time()
let elapsed = end - start
var timeBaseInfo = mach_timebase_info_data_t()
mach_timebase_info(&timeBaseInfo)
let elapsedNano = Int(elapsed) * Int(timeBaseInfo.numer) / Int(timeBaseInfo.denom)
return elapsedNano
}
private func adjustPrecision(_ ns: Int, toPrecision: String) -> Int
{
switch toPrecision
{
case "ns": // nanoseconds
return ns
case "us": // microseconds
return ns / 1_000
case "ms": // milliseconds
return ns / 1_000_000
default: // seconds
return ns / 1_000_000_000
}
}
/**
Measure execution time of trailing closure.
- Parameter precision: Precision of measurement. Possible
values:
- "ns": nanoseconds
- "us": microseconds
- "ms" or omitted parameter: milliseconds
- "s" or invalid input: seconds
*/
public func benchmark(_ precision: String = "ms", _ call: () -> ()) -> Int
{
// empty call duration to subtract
let emptyCallNano = durationNS({})
let elapsedNano = durationNS(call)
let elapsedCorrected = elapsedNano >= emptyCallNano
? elapsedNano - emptyCallNano
: 0
return adjustPrecision(elapsedCorrected, toPrecision: precision)
}
/**
Measure execution time of trailing closure, and print result
with description into the console.
- Parameter precision: Precision of measurement. Possible
values:
- "ns": nanoseconds
- "us": microseconds
- "ms" or omitted parameter: milliseconds
- "s" or invalid input: seconds
- Parameter title: Description of benchmark.
*/
public func benchmarkPrint(_ precision: String = "ms", title: String, _ call: () -> ())
{
print(title + ": \(benchmark(precision, call))" + precision)
}
/**
Measure the average execution time of trailing closure.
- Parameter precision: Precision of measurement. Possible
values:
- "ns": nanoseconds
- "us": microseconds
- "ms" or omitted parameter: milliseconds
- "s" or invalid input: seconds
- Parameter title: Description of benchmark.
- Parameter times: Amount of executions.
Default when parameter is omitted: 100.
- Returns: Minimum, Average and Maximum execution time of
benchmarks as 3-tuple.
*/
public func benchmarkAvg(
_ precision: String = "ms",
title: String = "",
times: Int = 10,
_ call: () -> ())
-> (min: Int, avg: Int, max: Int)
{
let emptyCallsNano = durationNS(
{
for _ in 0..<times {}
})
var min = Int.max
var max = 0
var elapsedNanoCombined = 0
for _ in 0..<times
{
let duration = durationNS(call)
if duration < min { min = duration }
if duration > max { max = duration }
elapsedNanoCombined += duration
}
let elapsedCorrected = elapsedNanoCombined >= emptyCallsNano
? elapsedNanoCombined - emptyCallsNano
: 0
return (adjustPrecision(min, toPrecision: precision),
adjustPrecision(elapsedCorrected / times, toPrecision: precision),
adjustPrecision(max, toPrecision: precision)
)
}
| 9c146cd38e53805dc25fcbdb3bb08142 | 22.531646 | 87 | 0.655729 | false | false | false | false |
JeffESchmitz/OnTheMap | refs/heads/master | OnTheMap/OnTheMap/StudentInformation.swift | mit | 1 | //
// StudentInformation.swift
// OnTheMap
//
// Created by Jeff Schmitz on 4/30/16.
// Copyright © 2016 Jeff Schmitz. All rights reserved.
//
import Foundation
// Represents a post of student information returned from the data table via the parse server.
struct StudentInformation {
var objectId: String?
var uniqueKey: String?
var firstName: String?
var lastName: String?
var mapString: String?
var mediaURL: String?
var latitude: Double?
var longitude: Double?
var createdAt: String?
var updatedAt: String?
init(dictionary: [String:AnyObject]) {
objectId = dictionary[Constants.ParseAPI.ObjectId] as? String
uniqueKey = dictionary[Constants.ParseAPI.UniqueKey] as? String
firstName = dictionary[Constants.ParseAPI.FirstName] as? String
lastName = dictionary[Constants.ParseAPI.LastName] as? String
mapString = dictionary[Constants.ParseAPI.MapString] as? String
mediaURL = dictionary[Constants.ParseAPI.MediaURL] as? String
latitude = dictionary[Constants.ParseAPI.Latitude] as? Double
longitude = dictionary[Constants.ParseAPI.Longitude] as? Double
createdAt = dictionary[Constants.ParseAPI.CreatedAt] as? String
updatedAt = dictionary[Constants.ParseAPI.UpdatedAt] as? String
}
} | ea047320e538920391787425cb8c3171 | 34.921053 | 94 | 0.690616 | false | false | false | false |
DDSSwiftTech/SwiftMine | refs/heads/master | Sources/SwiftMineCore/src/Config/ServerConfig.swift | apache-2.0 | 1 | //
// BaseClass.swift
// SwiftMine
//
// Created by David Schwartz on 8/24/16.
// Copyright © 2016 David Schwartz. All rights reserved.
//
import Foundation
internal final class ServerConfig {
/// Currently supported server config version
static let VERSION: Int8 = 2
//all default configuration goes here
static let DEFAULT_CONFIG_DICT: Dictionary<String, Any> = [
"_config_version": Int(VERSION),
"port": 19132,
"server_name": "§cSwiftMine Server",
"max_players": 999,
"log_level": LogLevel.info.rawValue
]
internal var configurationArray: Dictionary<String, Any> = [:]
private let configurationFilename = "swiftmine.sws"
internal let configPath: URL
internal init(withPath path: URL) {
self.configPath = path.appendingPathComponent("config/\(configurationFilename)")
if FileManager.default.fileExists(atPath: self.configPath.path) {
let inStream = InputStream(url: self.configPath)!
inStream.open()
let tempConfig = (try! JSONSerialization.jsonObject(with: inStream, options: JSONSerialization.ReadingOptions(
rawValue: JSONSerialization.ReadingOptions.mutableContainers.rawValue | JSONSerialization.ReadingOptions.mutableLeaves.rawValue)) as! Dictionary<String, Any>)
if (tempConfig["_config_version"] as! Int) == ServerConfig.VERSION {
configurationArray = tempConfig
return
}
}
doConfig(forItems: nil)
}
//separate function, to keep the init less cluttered
internal func doConfig(forItems items: [String]?) {
var items = items
/// Used to determine whether or not we should care about private configuration items
var configuringAllItems = false
// This means that we should configure or reconfigure everything
if items == nil {
print("Welcome to the SwiftMine version \(GLOBAL_VARS["VERSION"]!) setup!")
configuringAllItems = true
items = Array(ServerConfig.DEFAULT_CONFIG_DICT.keys)
}
guard (try? FileManager.default.createDirectory(at: configPath.deletingLastPathComponent(), withIntermediateDirectories: true, attributes: nil)) != nil else {
print("could not create config directory")
Server.main.stop(code: .CONFIG_DIR_CREATE_FAILED)
}
var configChanged = false
for (item) in items! {
if ServerConfig.DEFAULT_CONFIG_DICT.keys.contains(item) {
guard !item.hasPrefix("_") else {
if !configuringAllItems {
print("Cannot configure private item \(item).")
}
self.configurationArray[item] = ServerConfig.DEFAULT_CONFIG_DICT[item]!
continue
}
print("Enter a value for \(item) (default value - \(ServerConfig.DEFAULT_CONFIG_DICT[item]!)): ")
let ENTRY_STRING = readLine(strippingNewline: true)!
switch type(of: ServerConfig.DEFAULT_CONFIG_DICT[item]!) {
case is String.Type:
// need custom behavior for log_level, to verify that the log level exists
if item == "log_level" {
configurationArray[item] = (LogLevel(rawValue: ENTRY_STRING) != nil ? ENTRY_STRING : ServerConfig.DEFAULT_CONFIG_DICT[item]!)
} else {
configurationArray[item] = (ENTRY_STRING != "" ? ENTRY_STRING : ServerConfig.DEFAULT_CONFIG_DICT[item]!)
}
case is Int.Type:
configurationArray[item] = NumberFormatter().number(from: ENTRY_STRING) ?? ServerConfig.DEFAULT_CONFIG_DICT[item]!
default:
continue
}
configChanged = true
} else {
print("Config item \(item) not found.")
}
}
if configChanged {
if FileManager.default.fileExists(atPath: configPath.path) {
try! FileManager.default.removeItem(atPath: configPath.path)
}
let outStream = OutputStream(url: configPath, append: false)!
outStream.open()
#if os(Linux)
do {
_ = try JSONSerialization.writeJSONObject(configurationArray, toStream: outStream, options: JSONSerialization.WritingOptions.prettyPrinted)
} catch (let error) {
print(error)
Server.main.stop()
}
#else
if JSONSerialization.writeJSONObject(configurationArray, to: outStream, options: JSONSerialization.WritingOptions.prettyPrinted, error: nil) == 0 {
print("Could not save config")
Server.main.stop()
}
#endif
print("saving config...")
}
}
}
| 58ca33357c358d7dd706118492485486 | 38.30597 | 174 | 0.558572 | false | true | false | false |
vanshg/MacAssistant | refs/heads/master | MacAssistant/Auth/Authenticator.swift | mit | 1 | //
// Created by Vansh Gandhi on 7/26/18.
// Copyright (c) 2018 Vansh Gandhi. All rights reserved.
//
import Foundation
import Cocoa
import Alamofire
import SwiftyJSON
import Log
import SwiftyUserDefaults
public class Authenticator {
static let instance = Authenticator(scope: "https://www.googleapis.com/auth/assistant-sdk-prototype")
let Log = Logger()
var scope: String
var authUrl: String
var tokenUrl: String
var redirectUrl: String
var clientId: String
var clientSecret: String
var loginUrl: String
init(scope: String) {
self.scope = scope
let url = Bundle.main.url(forResource: "google_oauth", withExtension: "json")!
let json = try! JSON(data: Data(contentsOf: url))["installed"]
authUrl = json["auth_uri"].stringValue
tokenUrl = json["token_uri"].stringValue
redirectUrl = json["redirect_uris"][1].stringValue // Get the "http://localhost" url
clientId = json["client_id"].stringValue
clientSecret = json["client_secret"].stringValue
loginUrl = "\(authUrl)?client_id=\(clientId)&scope=\(scope)&response_type=code&redirect_uri=\(redirectUrl)"
Timer.scheduledTimer(withTimeInterval: 600, repeats: true) { _ in
// First run is at time 0 (aka, when the app first starts up)
if Defaults[.isLoggedIn] {
self.refreshTokenIfNecessary()
}
}.fire()
}
func authenticate(code: String, onLoginResult: @escaping (Error?) -> Void) {
let parameters = [
"code": code,
"client_id": clientId,
"client_secret": clientSecret,
"redirect_uri": redirectUrl,
"grant_type": "authorization_code",
]
Alamofire.request(tokenUrl, method: .post, parameters: parameters).responseJSON() { response in
switch response.result {
case .success(let value):
let json = JSON(value)
if let err = json["error"].string {
self.Log.debug("\(err): \(json["error_description"].string ?? "no error msg")")
onLoginResult(NSError())
return
}
let tokenExpiration = Date(timeInterval: TimeInterval(json["expires_in"].intValue), since: Date())
Defaults[.tokenExpirationDate] = tokenExpiration
Defaults[.accessToken] = json["access_token"].stringValue
Defaults[.refreshToken] = json["refresh_token"].stringValue
Defaults[.isLoggedIn] = true
self.Log.debug("Login success")
onLoginResult(nil)
case .failure(let error):
self.Log.error("Error fetching access token \(error)")
onLoginResult(error)
}
}
}
func refresh() {
let parameters = [
"refresh_token": Defaults[.refreshToken],
"client_id": clientId,
"client_secret": clientSecret,
"grant_type": "refresh_token",
]
Alamofire.request(tokenUrl, method: .post, parameters: parameters).responseJSON() { response in
switch response.result {
case .success(let value):
let json = JSON(value)
if let err = json["error"].string {
self.Log.debug("\(err): \(json["error_description"].string ?? "No error msg provided")")
return
}
let tokenExpiration = Date(timeInterval: TimeInterval(json["expires_in"].int!), since: Date())
Defaults[.tokenExpirationDate] = tokenExpiration
Defaults[.accessToken] = json["access_token"].stringValue
self.Log.debug("Refresh token success")
case .failure(let error):
self.Log.error("Error refreshing token: \(error)")
}
}
}
func refreshTokenIfNecessary() {
Log.info("Checking if token needs to be refreshed")
if var date = Defaults[.tokenExpirationDate] {
date.addTimeInterval(60 * 5) //refresh token with 5 mins left
if date < Date() && Defaults[.isLoggedIn] {
refresh()
}
}
}
func logout() {
Defaults[.isLoggedIn] = false
Defaults[.accessToken] = ""
Defaults[.refreshToken] = ""
}
}
| 6e3c7c874592559319dd18deb6284bfd | 35.735537 | 115 | 0.568954 | false | false | false | false |
deyton/swift | refs/heads/master | test/Generics/associated_type_typo.swift | apache-2.0 | 7 | // RUN: %target-typecheck-verify-swift
// RUN: not %target-swift-frontend -typecheck -debug-generic-signatures %s > %t.dump 2>&1
// RUN: %FileCheck -check-prefix CHECK-GENERIC %s < %t.dump
protocol P1 {
associatedtype Assoc
}
protocol P2 {
associatedtype AssocP2 : P1
}
protocol P3 { }
protocol P4 { }
// expected-error@+1{{'T' does not have a member type named 'assoc'; did you mean 'Assoc'?}}
func typoAssoc1<T : P1>(x: T.assoc, _: T) { }
// expected-error@+2{{'T' does not have a member type named 'assoc'; did you mean 'Assoc'?}}{{53-58=Assoc}}
// expected-error@+1{{'U' does not have a member type named 'assoc'; did you mean 'Assoc'?}}{{64-69=Assoc}}
func typoAssoc2<T : P1, U : P1>(_: T, _: U) where T.assoc == U.assoc {}
// CHECK-GENERIC-LABEL: .typoAssoc2
// CHECK-GENERIC: Generic signature: <T, U where T : P1, U : P1>
// expected-error@+3{{'T.AssocP2' does not have a member type named 'assoc'; did you mean 'Assoc'?}}{{42-47=Assoc}}
// expected-error@+2{{'U.AssocP2' does not have a member type named 'assoc'; did you mean 'Assoc'?}}{{19-24=Assoc}}
func typoAssoc3<T : P2, U : P2>(t: T, u: U)
where U.AssocP2.assoc : P3, T.AssocP2.assoc : P4,
T.AssocP2 == U.AssocP2 {}
// expected-error@+2{{'T.AssocP2' does not have a member type named 'assoc'; did you mean 'Assoc'?}}
// expected-error@+1{{'T' does not have a member type named 'Assocp2'; did you mean 'AssocP2'?}}{{39-46=AssocP2}}
func typoAssoc4<T : P2>(_: T) where T.Assocp2.assoc : P3 {}
// CHECK-GENERIC-LABEL: .typoAssoc4@
// CHECK-GENERIC-NEXT: Requirements:
// CHECK-GENERIC-NEXT: τ_0_0 : P2 [τ_0_0: Explicit @ {{.*}}:21]
// CHECK-GENERIC-NEXT: τ_0_0[.P2].AssocP2 : P1 [τ_0_0: Explicit @ {{.*}}:21 -> Protocol requirement (via Self.AssocP2 in P2)
// CHECK-GENERIC-NEXT: Potential archetypes
// <rdar://problem/19620340>
func typoFunc1<T : P1>(x: TypoType) { // expected-error{{use of undeclared type 'TypoType'}}
let _: (T.Assoc) -> () = { let _ = $0 }
}
func typoFunc2<T : P1>(x: TypoType, y: T) { // expected-error{{use of undeclared type 'TypoType'}}
let _: (T.Assoc) -> () = { let _ = $0 }
}
func typoFunc3<T : P1>(x: TypoType, y: (T.Assoc) -> ()) { // expected-error{{use of undeclared type 'TypoType'}}
}
// rdar://problem/29261689
typealias Element_<S: Sequence> = S.Iterator.Element
public protocol _Indexable1 {
associatedtype Slice // expected-note{{declared here}}
}
public protocol Indexable : _Indexable1 {
associatedtype Slice : _Indexable1 // expected-warning{{redeclaration of associated type 'Slice'}}
}
protocol Pattern {
associatedtype Element : Equatable
// FIXME: This works for all of the wrong reasons, but it is correct that
// it works.
func matched<C: Indexable>(atStartOf c: C)
where Element_<C> == Element
, Element_<C.Slice> == Element
}
class C {
typealias SomeElement = Int
}
func typoSuperclass1<T : C>(_: T) where T.someElement: P3 { }
// expected-error@-1{{'T' does not have a member type named 'someElement'; did you mean 'SomeElement'?}}{{43-54=SomeElement}}
class D {
typealias AElement = Int // expected-note{{did you mean 'AElement'?}}
typealias BElement = Int // expected-note{{did you mean 'BElement'?}}
}
func typoSuperclass2<T : D>(_: T, _: T.Element) { } // expected-error{{'Element' is not a member type of 'T'}}
| f25c3f0af6b21a06e89bf7adcae611ae | 36.089888 | 126 | 0.657679 | false | false | false | false |
Alecrim/AlecrimAsyncKit | refs/heads/master | Sources/Cancellation.swift | mit | 1 | //
// Cancellation.swift
// AlecrimAsyncKit
//
// Created by Vanderlei Martinelli on 10/03/18.
// Copyright © 2018 Alecrim. All rights reserved.
//
import Foundation
// MARK: -
private let _cancellationDispatchQueue = DispatchQueue(label: "com.alecrim.AlecrimAsyncKit.Cancellation", qos: .utility, attributes: .concurrent, target: DispatchQueue.global(qos: .utility))
// MARK: -
public typealias CancellationHandler = () -> Void
// MARK: -
public final class Cancellation {
private var _cancellationHandlersLock = os_unfair_lock_s()
private var _cancellationHandlers: [CancellationHandler]?
internal init() {
}
fileprivate func addCancellationHandler(_ newValue: @escaping CancellationHandler) {
os_unfair_lock_lock(&self._cancellationHandlersLock); defer { os_unfair_lock_unlock(&self._cancellationHandlersLock) }
if self._cancellationHandlers == nil {
self._cancellationHandlers = [newValue]
}
else {
self._cancellationHandlers!.append(newValue)
}
}
internal func run() {
var cancellationHandlers: [CancellationHandler]?
do {
os_unfair_lock_lock(&self._cancellationHandlersLock); defer { os_unfair_lock_unlock(&self._cancellationHandlersLock) }
cancellationHandlers = self._cancellationHandlers
self._cancellationHandlers = nil
}
//
cancellationHandlers?.forEach {
$0()
}
}
internal func run(after workItem: DispatchWorkItem) {
workItem.notify(queue: _cancellationDispatchQueue, execute: self.run)
}
}
// MARK: -
public func +=(left: Cancellation, right: @escaping CancellationHandler) {
left.addCancellationHandler(right)
}
| 72f163c95d721b3999c665be627511ab | 25.432836 | 190 | 0.66629 | false | false | false | false |
newtonstudio/cordova-plugin-device | refs/heads/master | imgly-sdk-ios-master/imglyKit/Frontend/Camera/IMGLYCameraController.swift | apache-2.0 | 1 | //
// IMGLYCameraController.swift
// imglyKit
//
// Created by Sascha Schwabbauer on 15/05/15.
// Copyright (c) 2015 9elements GmbH. All rights reserved.
//
import Foundation
import AVFoundation
import OpenGLES
import GLKit
import CoreMotion
struct IMGLYSDKVersion: Comparable, Printable {
let majorVersion: Int
let minorVersion: Int
let patchVersion: Int
var description: String {
return "\(majorVersion).\(minorVersion).\(patchVersion)"
}
}
func ==(lhs: IMGLYSDKVersion, rhs: IMGLYSDKVersion) -> Bool {
return (lhs.majorVersion == rhs.majorVersion) && (lhs.minorVersion == rhs.minorVersion) && (lhs.patchVersion == rhs.patchVersion)
}
func <(lhs: IMGLYSDKVersion, rhs: IMGLYSDKVersion) -> Bool {
if lhs.majorVersion < rhs.majorVersion {
return true
} else if lhs.majorVersion > rhs.majorVersion {
return false
}
if lhs.minorVersion < rhs.minorVersion {
return true
} else if lhs.minorVersion > rhs.minorVersion {
return false
}
if lhs.patchVersion < rhs.patchVersion {
return true
} else if lhs.patchVersion > rhs.patchVersion {
return false
}
return false
}
let CurrentSDKVersion = IMGLYSDKVersion(majorVersion: 2, minorVersion: 2, patchVersion: 1)
private let kIMGLYIndicatorSize = CGFloat(75)
private var CapturingStillImageContext = 0
private var SessionRunningAndDeviceAuthorizedContext = 0
private var FocusAndExposureContext = 0
@objc public protocol IMGLYCameraControllerDelegate: class {
optional func cameraControllerDidStartCamera(cameraController: IMGLYCameraController)
optional func cameraControllerDidStopCamera(cameraController: IMGLYCameraController)
optional func cameraControllerDidStartStillImageCapture(cameraController: IMGLYCameraController)
optional func cameraControllerDidFailAuthorization(cameraController: IMGLYCameraController)
optional func cameraController(cameraController: IMGLYCameraController, didChangeToFlashMode flashMode: AVCaptureFlashMode)
optional func cameraControllerDidCompleteSetup(cameraController: IMGLYCameraController)
optional func cameraController(cameraController: IMGLYCameraController, willSwitchToCameraPosition cameraPosition: AVCaptureDevicePosition)
optional func cameraController(cameraController: IMGLYCameraController, didSwitchToCameraPosition cameraPosition: AVCaptureDevicePosition)
}
public typealias IMGLYTakePhotoBlock = (UIImage?, NSError?) -> Void
public class IMGLYCameraController: NSObject {
// MARK: - Properties
/// The response filter that is applied to the live-feed.
public var effectFilter: IMGLYResponseFilter = IMGLYNoneFilter()
public let previewView: UIView
public weak var delegate: IMGLYCameraControllerDelegate?
public let tapGestureRecognizer = UITapGestureRecognizer()
dynamic private let session = AVCaptureSession()
private let sessionQueue = dispatch_queue_create("capture_session_queue", nil)
private let sampleBufferQueue = dispatch_queue_create("sample_buffer_queue", nil)
private var videoDeviceInput: AVCaptureDeviceInput?
private var videoDataOutput: AVCaptureVideoDataOutput?
dynamic private var stillImageOutput: AVCaptureStillImageOutput?
private var runtimeErrorHandlingObserver: NSObjectProtocol?
dynamic private var deviceAuthorized = false
private var glContext: EAGLContext?
private var ciContext: CIContext?
private var videoPreviewView: GLKView?
private var setupComplete = false
private var videoPreviewFrame = CGRectZero
private let focusIndicatorLayer = CALayer()
private var focusIndicatorFadeOutTimer: NSTimer?
private var focusIndicatorAnimating = false
private let motionManager: CMMotionManager = {
let motionManager = CMMotionManager()
motionManager.accelerometerUpdateInterval = 0.2
return motionManager
}()
private let motionManagerQueue = NSOperationQueue()
private var captureVideoOrientation: AVCaptureVideoOrientation?
dynamic private var sessionRunningAndDeviceAuthorized: Bool {
return session.running && deviceAuthorized
}
// MARK: - Initializers
init(previewView: UIView) {
self.previewView = previewView
super.init()
}
// MARK: - NSKeyValueObserving
class func keyPathsForValuesAffectingSessionRunningAndDeviceAuthorized() -> Set<String> {
return Set(["session.running", "deviceAuthorized"])
}
public override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
if context == &CapturingStillImageContext {
let capturingStillImage = change[NSKeyValueChangeNewKey]?.boolValue
if let isCapturingStillImage = capturingStillImage where isCapturingStillImage {
self.delegate?.cameraControllerDidStartStillImageCapture?(self)
}
} else if context == &SessionRunningAndDeviceAuthorizedContext {
let running = change[NSKeyValueChangeNewKey]?.boolValue
if let isRunning = running {
if isRunning {
self.delegate?.cameraControllerDidStartCamera?(self)
} else {
self.delegate?.cameraControllerDidStopCamera?(self)
}
}
} else if context == &FocusAndExposureContext {
dispatch_async(dispatch_get_main_queue()) {
self.updateFocusIndicatorLayer()
}
} else {
super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
}
}
// MARK: - SDK
private func versionComponentsFromString(version: String) -> (majorVersion: Int, minorVersion: Int, patchVersion: Int)? {
let versionComponents = version.componentsSeparatedByString(".")
if count(versionComponents) == 3 {
if let major = versionComponents[0].toInt(), minor = versionComponents[1].toInt(), patch = versionComponents[2].toInt() {
return (major, minor, patch)
}
}
return nil
}
private func checkSDKVersion() {
let appIdentifier = NSBundle.mainBundle().infoDictionary?["CFBundleIdentifier"] as? String
if let appIdentifier = appIdentifier, url = NSURL(string: "http://photoeditorsdk.com/version.json?type=ios&app=\(appIdentifier)") {
let task = NSURLSession.sharedSession().dataTaskWithURL(url) { data, response, error in
if let data = data {
let json = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as? [String: AnyObject]
if let json = json, version = json["version"] as? String, versionComponents = self.versionComponentsFromString(version) {
let remoteVersion = IMGLYSDKVersion(majorVersion: versionComponents.majorVersion, minorVersion: versionComponents.minorVersion, patchVersion: versionComponents.patchVersion)
if CurrentSDKVersion < remoteVersion {
println("Your version of the img.ly SDK is outdated. You are using version \(CurrentSDKVersion), the latest available version is \(remoteVersion). Please consider updating.")
}
}
}
}
task.resume()
}
}
// MARK: - Authorization
public func checkDeviceAuthorizationStatus() {
AVCaptureDevice.requestAccessForMediaType(AVMediaTypeVideo, completionHandler: { granted in
if granted {
self.deviceAuthorized = true
} else {
self.delegate?.cameraControllerDidFailAuthorization?(self)
self.deviceAuthorized = false
}
})
}
// MARK: - Camera
/// Use this property to determine if more than one camera is available. Within the SDK this property is used to determine if the toggle button is visible.
public var moreThanOneCameraPresent: Bool {
let videoDevices = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo)
return videoDevices.count > 1
}
public func toggleCameraPosition() {
if let device = videoDeviceInput?.device {
let nextPosition: AVCaptureDevicePosition
switch (device.position) {
case .Front:
nextPosition = .Back
case .Back:
nextPosition = .Front
default:
nextPosition = .Back
}
delegate?.cameraController?(self, willSwitchToCameraPosition: nextPosition)
focusIndicatorLayer.hidden = true
let sessionGroup = dispatch_group_create()
if let videoPreviewView = videoPreviewView {
// Hiding live preview
videoPreviewView.hidden = true
// Adding a simple snapshot and immediately showing it
let snapshot = videoPreviewView.snapshotViewAfterScreenUpdates(false)
snapshot.transform = videoPreviewView.transform
snapshot.frame = videoPreviewView.frame
previewView.addSubview(snapshot)
// Creating a snapshot with a UIBlurEffect added
let snapshotWithBlur = videoPreviewView.snapshotViewAfterScreenUpdates(false)
snapshotWithBlur.transform = videoPreviewView.transform
snapshotWithBlur.frame = videoPreviewView.frame
let visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .Dark))
visualEffectView.frame = snapshotWithBlur.bounds
visualEffectView.autoresizingMask = .FlexibleWidth | .FlexibleHeight
snapshotWithBlur.addSubview(visualEffectView)
// Transitioning between the regular snapshot and the blurred snapshot, this automatically removes `snapshot` and adds `snapshotWithBlur` to the view hierachy
UIView.transitionFromView(snapshot, toView: snapshotWithBlur, duration: 0.4, options: .TransitionFlipFromLeft | .CurveEaseOut, completion: { _ in
// Wait for camera to toggle
dispatch_group_notify(sessionGroup, dispatch_get_main_queue()) {
// Cross fading between blur and live preview, this sets `snapshotWithBlur.hidden` to `true` and `videoPreviewView.hidden` to false
UIView.transitionFromView(snapshotWithBlur, toView: videoPreviewView, duration: 0.2, options: .TransitionCrossDissolve | .ShowHideTransitionViews, completion: { _ in
// Deleting the blurred snapshot
snapshotWithBlur.removeFromSuperview()
})
}
})
}
dispatch_async(sessionQueue) {
dispatch_group_enter(sessionGroup)
self.session.beginConfiguration()
self.session.removeInput(self.videoDeviceInput)
self.removeObserversFromInputDevice()
self.setupInputsForPreferredCameraPosition(nextPosition)
self.addObserversToInputDevice()
self.session.commitConfiguration()
dispatch_group_leave(sessionGroup)
self.delegate?.cameraController?(self, didSwitchToCameraPosition: nextPosition)
}
}
}
// MARK: - Flash
/**
Selects the next flash-mode. The order is Auto->On->Off.
If the current device does not support auto-flash, this method
just toggles between on and off.
*/
public func selectNextFlashMode() {
var nextFlashMode: AVCaptureFlashMode = .Off
switch flashMode {
case .Auto:
if let device = videoDeviceInput?.device where device.isFlashModeSupported(.On) {
nextFlashMode = .On
}
case .On:
nextFlashMode = .Off
case .Off:
if let device = videoDeviceInput?.device {
if device.isFlashModeSupported(.Auto) {
nextFlashMode = .Auto
} else if device.isFlashModeSupported(.On) {
nextFlashMode = .On
}
}
}
flashMode = nextFlashMode
}
public private(set) var flashMode: AVCaptureFlashMode {
get {
if let device = self.videoDeviceInput?.device {
return device.flashMode
} else {
return .Off
}
}
set {
dispatch_async(sessionQueue) {
var error: NSError?
self.session.beginConfiguration()
if let device = self.videoDeviceInput?.device {
device.lockForConfiguration(&error)
//device.flashMode = newValue
device.unlockForConfiguration()
}
self.session.commitConfiguration()
if let error = error {
println("Error changing flash mode: \(error.description)")
return
}
self.delegate?.cameraController?(self, didChangeToFlashMode: newValue)
}
}
}
// MARK: - Focus
private func setupFocusIndicator() {
focusIndicatorLayer.borderColor = UIColor.whiteColor().CGColor
focusIndicatorLayer.borderWidth = 1
focusIndicatorLayer.frame.size = CGSize(width: kIMGLYIndicatorSize, height: kIMGLYIndicatorSize)
focusIndicatorLayer.hidden = true
focusIndicatorLayer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
previewView.layer.addSublayer(focusIndicatorLayer)
tapGestureRecognizer.addTarget(self, action: "tapped:")
if let videoPreviewView = videoPreviewView {
videoPreviewView.addGestureRecognizer(tapGestureRecognizer)
}
}
private func showFocusIndicatorLayerAtLocation(location: CGPoint) {
focusIndicatorFadeOutTimer?.invalidate()
focusIndicatorFadeOutTimer = nil
focusIndicatorAnimating = false
CATransaction.begin()
focusIndicatorLayer.opacity = 1
focusIndicatorLayer.hidden = false
focusIndicatorLayer.borderColor = UIColor.whiteColor().CGColor
focusIndicatorLayer.frame.size = CGSize(width: kIMGLYIndicatorSize, height: kIMGLYIndicatorSize)
focusIndicatorLayer.position = location
focusIndicatorLayer.transform = CATransform3DIdentity
focusIndicatorLayer.removeAllAnimations()
CATransaction.commit()
let resizeAnimation = CABasicAnimation(keyPath: "transform")
resizeAnimation.fromValue = NSValue(CATransform3D: CATransform3DMakeScale(1.5, 1.5, 1))
resizeAnimation.duration = 0.25
focusIndicatorLayer.addAnimation(resizeAnimation, forKey: nil)
}
@objc private func tapped(recognizer: UITapGestureRecognizer) {
if focusPointSupported || exposurePointSupported {
if let videoPreviewView = videoPreviewView {
let focusPointLocation = recognizer.locationInView(videoPreviewView)
let scaleFactor = videoPreviewView.contentScaleFactor
let videoFrame = CGRectMake(CGRectGetMinX(videoPreviewFrame) / scaleFactor, CGRectGetMinY(videoPreviewFrame) / scaleFactor, CGRectGetWidth(videoPreviewFrame) / scaleFactor, CGRectGetHeight(videoPreviewFrame) / scaleFactor)
if CGRectContainsPoint(videoFrame, focusPointLocation) {
let focusIndicatorLocation = recognizer.locationInView(previewView)
showFocusIndicatorLayerAtLocation(focusIndicatorLocation)
var pointOfInterest = CGPoint(x: focusPointLocation.x / CGRectGetWidth(videoFrame), y: focusPointLocation.y / CGRectGetHeight(videoFrame))
pointOfInterest.x = 1 - pointOfInterest.x
if let device = videoDeviceInput?.device where device.position == .Front {
pointOfInterest.y = 1 - pointOfInterest.y
}
focusWithMode(.AutoFocus, exposeWithMode: .AutoExpose, atDevicePoint: pointOfInterest, monitorSubjectAreaChange: true)
}
}
}
}
private var focusPointSupported: Bool {
if let device = videoDeviceInput?.device {
return device.focusPointOfInterestSupported && device.isFocusModeSupported(.AutoFocus) && device.isFocusModeSupported(.ContinuousAutoFocus)
}
return false
}
private var exposurePointSupported: Bool {
if let device = videoDeviceInput?.device {
return device.exposurePointOfInterestSupported && device.isExposureModeSupported(.AutoExpose) && device.isExposureModeSupported(.ContinuousAutoExposure)
}
return false
}
private func focusWithMode(focusMode: AVCaptureFocusMode, exposeWithMode exposureMode: AVCaptureExposureMode, atDevicePoint point: CGPoint, monitorSubjectAreaChange: Bool) {
dispatch_async(sessionQueue) {
if let device = self.videoDeviceInput?.device {
var error: NSError?
if device.lockForConfiguration(&error) {
if self.focusPointSupported {
device.focusMode = focusMode
device.focusPointOfInterest = point
}
if self.exposurePointSupported {
device.exposureMode = exposureMode
device.exposurePointOfInterest = point
}
device.subjectAreaChangeMonitoringEnabled = monitorSubjectAreaChange
device.unlockForConfiguration()
} else {
println("Error in focusWithMode:exposeWithMode:atDevicePoint:monitorSubjectAreaChange: \(error?.description)")
}
}
}
}
private func updateFocusIndicatorLayer() {
if let device = videoDeviceInput?.device {
if focusIndicatorLayer.hidden == false {
if device.focusMode == .Locked && device.exposureMode == .Locked {
focusIndicatorLayer.borderColor = UIColor(white: 1, alpha: 0.5).CGColor
}
}
}
}
@objc private func subjectAreaDidChange(notification: NSNotification) {
dispatch_async(dispatch_get_main_queue()) {
self.disableFocusLockAnimated(true)
}
}
public func disableFocusLockAnimated(animated: Bool) {
if focusIndicatorAnimating {
return
}
focusIndicatorAnimating = true
focusIndicatorFadeOutTimer?.invalidate()
if focusPointSupported || exposurePointSupported {
focusWithMode(.ContinuousAutoFocus, exposeWithMode: .ContinuousAutoExposure, atDevicePoint: CGPoint(x: 0.5, y: 0.5), monitorSubjectAreaChange: false)
if animated {
CATransaction.begin()
CATransaction.setDisableActions(true)
focusIndicatorLayer.borderColor = UIColor.whiteColor().CGColor
focusIndicatorLayer.frame.size = CGSize(width: kIMGLYIndicatorSize * 2, height: kIMGLYIndicatorSize * 2)
focusIndicatorLayer.transform = CATransform3DIdentity
focusIndicatorLayer.position = previewView.center
CATransaction.commit()
let resizeAnimation = CABasicAnimation(keyPath: "transform")
resizeAnimation.duration = 0.25
resizeAnimation.fromValue = NSValue(CATransform3D: CATransform3DMakeScale(1.5, 1.5, 1))
resizeAnimation.delegate = IMGLYAnimationDelegate(block: { finished in
if finished {
self.focusIndicatorFadeOutTimer = NSTimer.after(0.85) { [unowned self] in
self.focusIndicatorLayer.opacity = 0
let fadeAnimation = CABasicAnimation(keyPath: "opacity")
fadeAnimation.duration = 0.25
fadeAnimation.fromValue = 1
fadeAnimation.delegate = IMGLYAnimationDelegate(block: { finished in
if finished {
CATransaction.begin()
CATransaction.setDisableActions(true)
self.focusIndicatorLayer.hidden = true
self.focusIndicatorLayer.opacity = 1
self.focusIndicatorLayer.frame.size = CGSize(width: kIMGLYIndicatorSize, height: kIMGLYIndicatorSize)
CATransaction.commit()
self.focusIndicatorAnimating = false
}
})
self.focusIndicatorLayer.addAnimation(fadeAnimation, forKey: nil)
}
}
})
focusIndicatorLayer.addAnimation(resizeAnimation, forKey: nil)
} else {
focusIndicatorLayer.hidden = true
focusIndicatorAnimating = false
}
} else {
focusIndicatorLayer.hidden = true
focusIndicatorAnimating = false
}
}
// MARK: - Capture Session
/**
Initializes the camera and has to be called before calling `startCamera()` / `stopCamera()`
*/
public func setup() {
if setupComplete {
return
}
checkSDKVersion()
checkDeviceAuthorizationStatus()
glContext = EAGLContext(API: .OpenGLES2)
videoPreviewView = GLKView(frame: CGRectZero, context: glContext)
videoPreviewView!.autoresizingMask = .FlexibleWidth | .FlexibleHeight
videoPreviewView!.transform = CGAffineTransformMakeRotation(CGFloat(M_PI_2))
videoPreviewView!.frame = previewView.bounds
previewView.addSubview(videoPreviewView!)
previewView.sendSubviewToBack(videoPreviewView!)
ciContext = CIContext(EAGLContext: glContext)
videoPreviewView!.bindDrawable()
setupWithPreferredCameraPosition(.Back) {
if let device = self.videoDeviceInput?.device {
if device.isFlashModeSupported(.Auto) {
self.flashMode = .Auto
}
}
self.delegate?.cameraControllerDidCompleteSetup?(self)
}
setupFocusIndicator()
setupComplete = true
}
private func setupWithPreferredCameraPosition(cameraPosition: AVCaptureDevicePosition, completion: (() -> (Void))?) {
dispatch_async(sessionQueue) {
if self.session.canSetSessionPreset(AVCaptureSessionPresetPhoto) {
self.session.sessionPreset = AVCaptureSessionPresetPhoto
}
self.setupInputsForPreferredCameraPosition(cameraPosition)
self.setupOutputs()
completion?()
}
}
private func setupInputsForPreferredCameraPosition(cameraPosition: AVCaptureDevicePosition) {
var error: NSError?
let videoDevice = IMGLYCameraController.deviceWithMediaType(AVMediaTypeVideo, preferringPosition: cameraPosition)
let videoDeviceInput = AVCaptureDeviceInput(device: videoDevice, error: &error)
if let error = error {
println("Error in setupInputsForPreferredCameraPosition: \(error.description)")
}
if self.session.canAddInput(videoDeviceInput) {
self.session.addInput(videoDeviceInput)
self.videoDeviceInput = videoDeviceInput
dispatch_async(dispatch_get_main_queue()) {
if let videoPreviewView = self.videoPreviewView, device = videoDevice {
if device.position == .Front {
// front camera is mirrored so we need to transform the preview view
videoPreviewView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI_2))
videoPreviewView.transform = CGAffineTransformScale(videoPreviewView.transform, 1, -1)
} else {
videoPreviewView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI_2))
}
}
}
}
}
private func setupOutputs() {
let videoDataOutput = AVCaptureVideoDataOutput()
videoDataOutput.setSampleBufferDelegate(self, queue: self.sampleBufferQueue)
if self.session.canAddOutput(videoDataOutput) {
self.session.addOutput(videoDataOutput)
self.videoDataOutput = videoDataOutput
}
let stillImageOutput = AVCaptureStillImageOutput()
if self.session.canAddOutput(stillImageOutput) {
self.session.addOutput(stillImageOutput)
self.stillImageOutput = stillImageOutput
}
}
/**
Starts the camera preview.
*/
public func startCamera() {
assert(setupComplete, "setup() needs to be called before calling startCamera()")
if session.running {
return
}
startCameraWithCompletion(nil)
// Used to determine device orientation even if orientation lock is active
motionManager.startAccelerometerUpdatesToQueue(motionManagerQueue, withHandler: { accelerometerData, _ in
if abs(accelerometerData.acceleration.y) < abs(accelerometerData.acceleration.x) {
if accelerometerData.acceleration.x > 0 {
self.captureVideoOrientation = .LandscapeLeft
} else {
self.captureVideoOrientation = .LandscapeRight
}
} else {
if accelerometerData.acceleration.y > 0 {
self.captureVideoOrientation = .PortraitUpsideDown
} else {
self.captureVideoOrientation = .Portrait
}
}
})
}
private func startCameraWithCompletion(completion: (() -> (Void))?) {
dispatch_async(sessionQueue) {
self.addObserver(self, forKeyPath: "sessionRunningAndDeviceAuthorized", options: .Old | .New, context: &SessionRunningAndDeviceAuthorizedContext)
self.addObserver(self, forKeyPath: "stillImageOutput.capturingStillImage", options: .Old | .New, context: &CapturingStillImageContext)
self.addObserversToInputDevice()
self.runtimeErrorHandlingObserver = NSNotificationCenter.defaultCenter().addObserverForName(AVCaptureSessionRuntimeErrorNotification, object: self.session, queue: nil, usingBlock: { [unowned self] _ in
dispatch_async(self.sessionQueue) {
self.session.startRunning()
}
})
self.session.startRunning()
completion?()
}
}
private func addObserversToInputDevice() {
if let device = self.videoDeviceInput?.device {
device.addObserver(self, forKeyPath: "focusMode", options: .Old | .New, context: &FocusAndExposureContext)
device.addObserver(self, forKeyPath: "exposureMode", options: .Old | .New, context: &FocusAndExposureContext)
}
NSNotificationCenter.defaultCenter().addObserver(self, selector: "subjectAreaDidChange:", name: AVCaptureDeviceSubjectAreaDidChangeNotification, object: self.videoDeviceInput?.device)
}
private func removeObserversFromInputDevice() {
if let device = self.videoDeviceInput?.device {
device.removeObserver(self, forKeyPath: "focusMode", context: &FocusAndExposureContext)
device.removeObserver(self, forKeyPath: "exposureMode", context: &FocusAndExposureContext)
}
NSNotificationCenter.defaultCenter().removeObserver(self, name: AVCaptureDeviceSubjectAreaDidChangeNotification, object: self.videoDeviceInput?.device)
}
/**
Stops the camera preview.
*/
public func stopCamera() {
assert(setupComplete, "setup() needs to be called before calling stopCamera()")
if !session.running {
return
}
stopCameraWithCompletion(nil)
motionManager.stopAccelerometerUpdates()
}
private func stopCameraWithCompletion(completion: (() -> (Void))?) {
dispatch_async(sessionQueue) {
self.session.stopRunning()
self.removeObserversFromInputDevice()
if let runtimeErrorHandlingObserver = self.runtimeErrorHandlingObserver {
NSNotificationCenter.defaultCenter().removeObserver(runtimeErrorHandlingObserver)
}
self.removeObserver(self, forKeyPath: "sessionRunningAndDeviceAuthorized", context: &SessionRunningAndDeviceAuthorizedContext)
self.removeObserver(self, forKeyPath: "stillImageOutput.capturingStillImage", context: &CapturingStillImageContext)
completion?()
}
}
/// Check if the current device has a flash.
public var flashAvailable: Bool {
if let device = self.videoDeviceInput?.device {
return device.flashAvailable
}
return false
}
// MARK: - Still Image Capture
/**
Takes a photo and hands it over to the completion block.
:param: completion A completion block that has an image and an error as parameters.
If the image was taken sucessfully the error is nil.
*/
public func takePhoto(completion: IMGLYTakePhotoBlock) {
if let stillImageOutput = self.stillImageOutput {
dispatch_async(sessionQueue) {
let connection = stillImageOutput.connectionWithMediaType(AVMediaTypeVideo)
// Update the orientation on the still image output video connection before capturing.
if let captureVideoOrientation = self.captureVideoOrientation {
connection.videoOrientation = captureVideoOrientation
}
stillImageOutput.captureStillImageAsynchronouslyFromConnection(connection) {
(imageDataSampleBuffer: CMSampleBuffer?, error: NSError?) -> Void in
if let imageDataSampleBuffer = imageDataSampleBuffer {
let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer)
let image = UIImage(data: imageData)
completion(image, nil)
} else {
completion(nil, error)
}
}
}
}
}
// MARK: - Helpers
class func deviceWithMediaType(mediaType: String, preferringPosition position: AVCaptureDevicePosition) -> AVCaptureDevice? {
let devices = AVCaptureDevice.devicesWithMediaType(mediaType) as! [AVCaptureDevice]
var captureDevice = devices.first
for device in devices {
if device.position == position {
captureDevice = device
break
}
}
return captureDevice
}
}
extension IMGLYCameraController: AVCaptureVideoDataOutputSampleBufferDelegate {
public func captureOutput(captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, fromConnection connection: AVCaptureConnection!) {
let formatDescription = CMSampleBufferGetFormatDescription(sampleBuffer)
let mediaType = CMFormatDescriptionGetMediaType(formatDescription)
let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)
let sourceImage = CIImage(CVPixelBuffer: imageBuffer as CVPixelBufferRef, options: nil)
let filteredImage: CIImage?
if effectFilter is IMGLYNoneFilter {
filteredImage = sourceImage
} else {
filteredImage = IMGLYPhotoProcessor.processWithCIImage(sourceImage, filters: [effectFilter])
}
let sourceExtent = sourceImage.extent()
if let videoPreviewView = videoPreviewView {
let targetRect = CGRect(x: 0, y: 0, width: videoPreviewView.drawableWidth, height: videoPreviewView.drawableHeight)
videoPreviewFrame = sourceExtent
videoPreviewFrame.fittedIntoTargetRect(targetRect, withContentMode: .ScaleAspectFit)
if glContext != EAGLContext.currentContext() {
EAGLContext.setCurrentContext(glContext)
}
videoPreviewView.bindDrawable()
glClearColor(0, 0, 0, 1.0)
glClear(GLbitfield(GL_COLOR_BUFFER_BIT))
if let filteredImage = filteredImage {
ciContext?.drawImage(filteredImage, inRect: videoPreviewFrame, fromRect: sourceExtent)
}
videoPreviewView.display()
}
}
}
extension CGRect {
mutating func fittedIntoTargetRect(targetRect: CGRect, withContentMode contentMode: UIViewContentMode) {
if !(contentMode == .ScaleAspectFit || contentMode == .ScaleAspectFill) {
// Not implemented
return
}
var scale = targetRect.width / self.width
if contentMode == .ScaleAspectFit {
if self.height * scale > targetRect.height {
scale = targetRect.height / self.height
}
} else if contentMode == .ScaleAspectFill {
if self.height * scale < targetRect.height {
scale = targetRect.height / self.height
}
}
let scaledWidth = self.width * scale
let scaledHeight = self.height * scale
let scaledX = targetRect.width / 2 - scaledWidth / 2
let scaledY = targetRect.height / 2 - scaledHeight / 2
self.origin.x = scaledX
self.origin.y = scaledY
self.size.width = scaledWidth
self.size.height = scaledHeight
}
}
| a45f10dc03a290fb6da0364b2dc5c45c | 41.450418 | 238 | 0.615012 | false | false | false | false |
PureSwift/Kronos | refs/heads/master | Sources/Kronos/Capability.swift | mit | 2 | //
// Capability.swift
// Kronos
//
// Created by Alsey Coleman Miller on 1/21/16.
// Copyright © 2016 PureSwift. All rights reserved.
//
#if os(iOS) || os(tvOS)
import OpenGLES
#endif
/// OpenGL server-side Capabilities. Can be enabled or disabled.
///
/// - Note: All cases, with the exception of `Dither`, are false by default.
public enum Capability: GLenum {
case Texture2D = 0x0DE1
/// If enabled, cull polygons based on their winding in window coordinates.
case CullFace = 0x0B44
/// If enabled, blend the computed fragment color values with the values in the color buffers.
case Blend = 0x0BE2
/// If enabled, dither color components or indices before they are written to the color buffer.
case Dither = 0x0BD0
/// If enabled, do stencil testing and update the stencil buffer.
case StencilTest = 0x0B90
/// If enabled, do depth comparisons and update the depth buffer.
///
/// - Note: Even if the depth buffer exists and the depth mask is non-zero,
/// the depth buffer is not updated if the depth test is disabled.
case DepthTest = 0x0B71
/// If enabled, discard fragments that are outside the scissor rectangle.
case ScissorTest = 0x0C11
/// If enabled, an offset is added to depth values of a polygon's fragments produced by rasterization.
case PloygonOffsetFill = 0x8037
/// If enabled, compute a temporary coverage value where each bit is determined by the alpha value at
/// the corresponding sample location. The temporary coverage value is then ANDed with the fragment coverage value.
case SampleAlphaToCoverage = 0x809E
/// If enabled, the fragment's coverage is ANDed with the temporary coverage value.
/// If `GL_SAMPLE_COVERAGE_INVERT` is set to `GL_TRUE`, invert the coverage value.
case SampleCoverage = 0x80A0
public var enabled: Bool {
return glIsEnabled(rawValue).boolValue
}
@inline(__always)
public func enable() {
glEnable(rawValue)
}
@inline(__always)
public func disable() {
glDisable(rawValue)
}
}
| 065bc2f81405b654cdf25193a7208059 | 32.289855 | 119 | 0.634741 | false | true | false | false |
ProjectGinsberg/SDK | refs/heads/master | ExampleApp/iOS/Example1/Src/VCPost.swift | mit | 1 | //
// ViewController.swift
// Example1
//
// Created by CD on 22/07/2014.
// Copyright (c) 2014 Ginsberg. All rights reserved.
//
import UIKit
//
// Main handler of demonstrating getting and posting of users Ginsberg data
//
class VCPost: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate, GAPIProtocol
{
//
// MARK: Outlets
//
@IBOutlet weak var aiBusy: UIView!
@IBOutlet weak var vMain: UIView!
@IBOutlet weak var lbText: UILabel!
@IBOutlet weak var pkType: UIPickerView!
@IBOutlet weak var pkGetPeriod: UIPickerView!
@IBOutlet weak var pkGetFrom: UIPickerView!
@IBOutlet weak var pkGetTo: UIPickerView!
@IBOutlet weak var lbGetID: UITextField!
@IBOutlet weak var lbGetFrom: UITextField!
@IBOutlet weak var lbGetTo: UITextField!
@IBOutlet weak var lbDeleteID: UITextField!
@IBOutlet weak var svSendData: UIScrollView!
@IBOutlet weak var svOutput: UIScrollView!
@IBOutlet weak var btGet: UIButton!
@IBOutlet weak var btPost: UIButton!
@IBOutlet weak var btDelete: UIButton!
@IBOutlet weak var vFromTo: UIView!
@IBOutlet weak var vPost: UIView!
//
// MARK: Onscreen items
//
let Types = [/*"Aggregate",*/ "Correlations", "Daily Summary", "Notifications", "Profile", "Tag", "Activity" , "Alcohol", "Body" , "Caffeine", "Exercise", "Events", "Measures", "Nutrition", "Sleep", "Smoking", "Social", "Stepcount", "Survey", "Wellbeing", "Mood", "Happy", "Uneasy", "Well", "Sad"];
let Range = ["All", "ID", "FromBelow", "ToBelow", "FromToBelow"];
let Time = ["Yesterday", "Lastweek", "Lastyear", "Date"];
var dataRequested:Bool = false;
//
// MARK: View Controller
//
override func viewDidLoad()
{
super.viewDidLoad();
//Set callbacks to this instance
GAPI.Instance().SetCallbacks(self);
//Hide busy indicator
SetBusy(false);
//Set onscreen dates to now
pressedSetTimeNow(nil);
//Set text colour for when buttons are disabled
btPost.setTitleColor(UIColor.grayColor(), forState: UIControlState.Disabled);
btDelete.setTitleColor(UIColor.grayColor(), forState: UIControlState.Disabled);
//Set initial picker selection
self.pickerView(pkType, didSelectRow: 0, inComponent: 0);
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
override func viewWillAppear(animated: Bool)
{
super.viewWillAppear(animated)
}
override func viewDidAppear(animated: Bool)
{
super.viewDidAppear(animated);
//Make pickers a bit smaller
pkType.transform = CGAffineTransformMakeScale(0.6, 0.4);
pkGetPeriod.transform = CGAffineTransformMakeScale(0.6, 0.4);
pkGetFrom.transform = CGAffineTransformMakeScale(0.6, 0.4);
pkGetTo.transform = CGAffineTransformMakeScale(0.6, 0.4);
//Configure send data entries
svSendData.contentSize = CGSizeMake(svSendData.contentSize.width, 620.0);
svOutput.contentSize = CGSizeMake(svOutput.contentSize.width, 2000.0);
//Space out send data
for subView in svSendData.subviews
{
var obj:UIView = subView as UIView;
var i = obj.tag;
if(i != 0)
{
obj.frame = CGRectMake(obj.frame.origin.x, CGFloat(30*((i-1)/2)), obj.frame.size.width, obj.frame.size.height);
}
}
}
//
// MARK: TextField
//
func textFieldShouldReturn(textField: UITextField) -> Bool
{
//Hide keyboard on return press
textField.resignFirstResponder();
return false;
}
//
// MARK: Pickerview
//
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int
{
return 1;
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int
{
if(pickerView == pkType)
{
return Types.count;
}
else
if(pickerView == pkGetPeriod)
{
return Range.count;
}
else
if(pickerView == pkGetFrom)
{
return Time.count;
}
else
if(pickerView == pkGetTo)
{
return Time.count;
}
return 0;
}
func pickerView(pickerView: UIPickerView!, titleForRow row: Int, forComponent component: Int) -> String!
{
if(pickerView == pkType)
{
return Types[row];
}
else
if(pickerView == pkGetPeriod)
{
return Range[row];
}
else
if(pickerView == pkGetFrom)
{
return Time[row];
}
else
if(pickerView == pkGetTo)
{
return Time[row];
}
return "";
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
//Format view per selection
var selection:String = Types[pkType.selectedRowInComponent(0)];
switch(selection)
{
//case "Aggregate":Int(ID)); break;
case "Correlations": EnableViews(false, postData:false, deleteData:false, valueType:nil); break;
case "Daily Summary":EnableViews(true, postData:false, deleteData:false, valueType:nil); break;
case "Tag": EnableViews(true, postData:false, deleteData:false, valueType:nil); break;
case "Profile": EnableViews(false, postData:false, deleteData:false, valueType:nil); break;
case "Activity": EnableViews(true, postData:true, deleteData:true, valueType:nil, variables:"timeStart","timeEnd","distance","calories","steps","timeStamp"); break;
case "Alcohol": EnableViews(true, postData:true, deleteData:true, valueType:"Units", variables:"timeStamp"); break;
case "Body": EnableViews(true, postData:true, deleteData:true, valueType:nil,
variables:"weight", "fat", "timeStamp"); break;
case "Caffeine": EnableViews(true, postData:true, deleteData:true, valueType:"Caffeine", variables:"timeStamp"); break;
case "Events": EnableViews(true, postData:true, deleteData:true, valueType:nil, variables:"timeStamp"); break;
case "Exercise": EnableViews(true, postData:true, deleteData:true, valueType:"Distance", variables:"timeStamp"); break;
case "Measures": EnableViews(false, postData:false, deleteData:false, valueType:nil); break;
case "Notifications": EnableViews(true, postData:false, deleteData:false, valueType:nil); break;
case "Nutrition": EnableViews(true, postData:true, deleteData:true, valueType:nil, variables:"calories","carbohydrates","fat","fiber","protein","sugar","timeStamp"); break;
case "Sleep": EnableViews(true, postData:true, deleteData:true, valueType:nil,
variables:"timesAwoken","awake","lightSleep","remSleep","deepSleep","totalSleep","sleepQuality","timeStamp"); break;
case "Smoking": EnableViews(true, postData:true, deleteData:true, valueType:"Quantity", variables:"timeStamp"); break;
case "Social": EnableViews(true, postData:true, deleteData:true, valueType:nil, variables:"timeStamp"); break;
case "Stepcount": EnableViews(true, postData:true, deleteData:true, valueType:nil,
variables:"timeStart","timeEnd","distance","calories","steps","timeStamp"); break;
case "Survey": EnableViews(false, postData:false, deleteData:false, valueType:nil); break;
case "Wellbeing": EnableViews(true, postData:true, deleteData:true, valueType:nil); break;
case "Mood": EnableViews(true, postData:true, deleteData:true, valueType:"Value"); break;
case "Happy": EnableViews(true, postData:true, deleteData:true, valueType:"Value"); break;
case "Uneasy": EnableViews(true, postData:true, deleteData:true, valueType:"Value"); break;
case "Well": EnableViews(true, postData:true, deleteData:true, valueType:"Value"); break;
case "Sad": EnableViews(true, postData:true, deleteData:true, valueType:"Value"); break;
default: break;
}
}
// Customise view
func EnableViews(getPeriod:Bool, postData:Bool, deleteData:Bool, valueType:String?, variables:String...)
{
//Show/hide used/unused views
UIView.animateWithDuration(0.5)
{
self.vFromTo.userInteractionEnabled = !getPeriod;
self.vPost.userInteractionEnabled = !postData;
if(getPeriod)
{
self.vFromTo.alpha = 0.0;
}
else
{
self.vFromTo.alpha = 1.0;
}
if(postData)
{
self.vPost.alpha = 0.0;
}
else
{
self.vPost.alpha = 1.0;
}
}
//Enable buttons
btPost.enabled = postData;
btDelete.enabled = deleteData;
lbDeleteID.enabled = deleteData;
if(deleteData)
{
lbDeleteID.textColor = UIColor.blackColor();
}
else
{
lbDeleteID.textColor = UIColor.grayColor();
}
//Hide all posting items
for subView in svSendData.subviews
{
var obj:UIView = subView as UIView;
obj.hidden = true;
}
svSendData.setContentOffset(CGPoint(x:0.0,y:0.0),animated:true);
var i = 0;
//If using the value entry posting box then enable it and put at top of posting panel
if(valueType != nil)
{
RepositionView(7, index:i++);
(svSendData.viewWithTag(7) as UILabel).text = valueType;
}
//Enable data entry items listed in the passed variables list
for variable in variables
{
switch(variable)
{
case "timeStamp": RepositionView(1, index:i); break;
case "weight": RepositionView(13, index:i); break;
case "fat": RepositionView(15, index:i); break;
case "timeStart": RepositionView(3, index:i); break;
case "timeEnd": RepositionView(5, index:i); break;
case "distance": RepositionView(9, index:i); break;
case "calories": RepositionView(11, index:i); break;
case "steps": RepositionView(37, index:i); break;
case "carbohydrates": RepositionView(17, index:i); break;
case "fiber": RepositionView(19, index:i); break;
case "protein": RepositionView(21, index:i); break;
case "sugar": RepositionView(23, index:i); break;
case "timesAwoken": RepositionView(35, index:i); break;
case "awake": RepositionView(33, index:i); break;
case "lightSleep": RepositionView(31, index:i); break;
case "remSleep": RepositionView(29, index:i); break;
case "deepSleep": RepositionView(27, index:i); break;
case "totalSleep": RepositionView(25, index:i); break;
case "sleepQuality": RepositionView(125, index:i); break;
default: break;
}
++i;
}
}
//Reposition and enable passed item
func RepositionView(tag:Int, index:Int)
{
var viewTitle:UIView! = svSendData.viewWithTag(tag);
var viewValue:UIView! = svSendData.viewWithTag(tag+1);
viewTitle.hidden = false;
viewValue.hidden = false;
viewTitle.frame = CGRectMake(viewTitle.frame.origin.x, CGFloat(10+35*index), viewTitle.frame.size.width, viewTitle.frame.size.height);
viewValue.frame = CGRectMake(viewValue.frame.origin.x, CGFloat(10+35*index), viewValue.frame.size.width, viewValue.frame.size.height);
}
//
// MARK: Actions
//
@IBAction func pressedPostData(sender: UIButton)
{
SetBusy(true);
// Get all potential data from view
var ev:String = "1";
var selection:String=Types[pkType.selectedRowInComponent(0)];
var timeStamp:String = (svSendData.viewWithTag(2) as UITextField).text; //"2014-07-23T14:38:58";
var ed:Double = ((svSendData.viewWithTag(8) as UITextField).text as NSString).doubleValue;
var ei:Int = Int(ed);
var timeStart:String = (svSendData.viewWithTag(4) as UITextField).text;
var timeEnd:String = (svSendData.viewWithTag(6) as UITextField).text;
var distance:Double = ((svSendData.viewWithTag(10) as UITextField).text as NSString).doubleValue;
var calories:Double = ((svSendData.viewWithTag(12) as UITextField).text as NSString).doubleValue;
var weight:Double = ((svSendData.viewWithTag(14) as UITextField).text as NSString).doubleValue;
var fat:Double = ((svSendData.viewWithTag(16) as UITextField).text as NSString).doubleValue;
var carbohydrates:Double = ((svSendData.viewWithTag(18) as UITextField).text as NSString).doubleValue;
var fiber:Double = ((svSendData.viewWithTag(20) as UITextField).text as NSString).doubleValue;
var protein:Double = ((svSendData.viewWithTag(22) as UITextField).text as NSString).doubleValue;
var sugar:Double = ((svSendData.viewWithTag(24) as UITextField).text as NSString).doubleValue;
var totalSleep:Double = ((svSendData.viewWithTag(26) as UITextField).text as NSString).doubleValue;
var deepSleep:Double = ((svSendData.viewWithTag(28) as UITextField).text as NSString).doubleValue;
var remSleep:Double = ((svSendData.viewWithTag(30) as UITextField).text as NSString).doubleValue;
var lightSleep:Double = ((svSendData.viewWithTag(32) as UITextField).text as NSString).doubleValue;
var awake:Double = ((svSendData.viewWithTag(34) as UITextField).text as NSString).doubleValue;
var timesAwoken:Int = ((svSendData.viewWithTag(36) as UITextField).text as NSString).integerValue;
var stepCount:Int = ((svSendData.viewWithTag(38) as UITextField).text as NSString).integerValue;
var wellbeingType:Int = ((svSendData.viewWithTag(40) as UITextField).text as NSString).integerValue;
var wellbeingQues:String = "I've been interested in new things";
//Post data with the respective SDK call
switch(selection)
{
case "Body": GAPI.Instance().PostBody(timeStamp, weight:weight, fat:fat); break;
case "Caffeine": GAPI.Instance().PostCaffeine(timeStamp, amount:ed); break;
case "Smoking": GAPI.Instance().PostSmoking(timeStamp, amount:Int32(ei)); break;
case "Stepcount": GAPI.Instance().PostStepcount(timeStamp, timeStart:timeStart, timeEnd:timeEnd, distance:distance, calories:calories, steps:Int32(stepCount)); break;
case "Social": GAPI.Instance().PostSocial(timeStamp); break;
case "Nutrition": GAPI.Instance().PostNutrition(timeStamp, calories:calories, carbohydrates:carbohydrates, fat:fat, fiber:fiber, protein:protein, sugar:sugar); break;
case "Activity": GAPI.Instance().PostActivity(timeStamp, start:timeStart, end:timeEnd, dist:distance, cal:calories, steps:Int32(stepCount)); break;
case "Alcohol": GAPI.Instance().PostAlcohol(timeStamp, units:ed); break;
case "Events": GAPI.Instance().PostEvent(timeStamp, event:"Todays event string", ID:GAPI.Instance().todaysEventID); break;
case "Sleep": GAPI.Instance().PostSleep(timeStamp, timesAwoken:Int32(timesAwoken), awake:Double(awake), lightSleep:Double(lightSleep), remSleep:Double(remSleep), deepSleep:Double(deepSleep), totalSleep:Double(totalSleep), quality:Int32(10)); break;
//case "Survey": GAPI.Instance().PostSurvey(1234); break;
//To finish
case "Exercise": GAPI.Instance().PostExercise(timeStamp, activity:"Jogging", distance:ed); break;
case "Wellbeing": GAPI.Instance().PostWellbeing(timeStamp, value:Int32(5), wbques:"I've been interested in new things", wbtype:Int32(10)); break;
case "Profile": GAPI.Instance().PostProfile("Chris", lastName:"Brown", phoneNumber:"12345", country:Int32(0+1)); break;
case "Mood": GAPI.Instance().PostMood(timeStamp, value:Int32(ei)); break;
case "Happy": GAPI.Instance().PostHappy(timeStamp, value:Int32(ei)); break;
case "Uneasy": GAPI.Instance().PostUneasy(timeStamp, value:Int32(ei)); break;
case "Well": GAPI.Instance().PostWell(timeStamp, value:Int32(ei)); break;
case "Sad": GAPI.Instance().PostSad(timeStamp, value:Int32(ei)); break;
//Done other than input values
//case "Notifications": GAPI.Instance().PostNotifications(timeStamp, value:Int32(ei));
default: break;
}
}
@IBAction func pressedGetData(sender: UIButton)
{
SetBusy(true);
dataRequested = true;
var selection:String = Types[pkType.selectedRowInComponent(0)];
var range:String = Range[pkGetPeriod.selectedRowInComponent(0)];
var typeFrom:String = Time[pkGetFrom.selectedRowInComponent(0)];
var typeTo:String = Time[pkGetTo.selectedRowInComponent(0)];
var dateFrom:String = lbGetFrom.text;
var dateTo:String = lbGetTo.text;
var ID:Int! = lbGetID.text.toInt();
//Get data with the respective SDK call
switch(selection)
{
//case "Aggregate": GAPI.Instance().GetAggregate(range,typeFrom:typeFrom,dateFrom:dateFrom,typeTo:typeTo,dateTo:dateTo,ID:Int(ID)); break;
case "Correlations": GAPI.Instance().GetCorrelations(); break;
case "Daily Summary": GAPI.Instance().GetDailySummary(range,typeFrom:typeFrom,dateFrom:dateFrom,typeTo:typeTo,dateTo:dateTo); break;
case "Profile": GAPI.Instance().GetProfile(); break;
case "Tag": GAPI.Instance().GetTag(range,typeFrom:typeFrom,dateFrom:dateFrom,typeTo:typeTo,dateTo:dateTo); break;
case "Activity": GAPI.Instance().GetActivity(range,typeFrom:typeFrom,dateFrom:dateFrom,typeTo:typeTo,dateTo:dateTo,ID:Int(ID)); break;
case "Alcohol": GAPI.Instance().GetAlcohol(range,typeFrom:typeFrom,dateFrom:dateFrom,typeTo:typeTo,dateTo:dateTo,ID:Int(ID)); break;
case "Body": GAPI.Instance().GetBody(range,typeFrom:typeFrom,dateFrom:dateFrom,typeTo:typeTo,dateTo:dateTo,ID:Int(ID)); break;
case "Caffeine": GAPI.Instance().GetCaffeine(range,typeFrom:typeFrom,dateFrom:dateFrom,typeTo:typeTo,dateTo:dateTo,ID:Int(ID)); break;
case "Events": GAPI.Instance().GetEvent(range,typeFrom:typeFrom,dateFrom:dateFrom,typeTo:typeTo,dateTo:dateTo,ID:Int(ID)); break;
case "Exercise": GAPI.Instance().GetExercise(range,typeFrom:typeFrom,dateFrom:dateFrom,typeTo:typeTo,dateTo:dateTo,ID:Int(ID)); break;
//case "Measures": GAPI.Instance().GetMeasures(Int(ID)); break;
case "Notifications": GAPI.Instance().GetNotifications(range,typeFrom:typeFrom,dateFrom:dateFrom,typeTo:typeTo,dateTo:dateTo,ID:Int(ID)); break;
case "Nutrition": GAPI.Instance().GetNutrition(range,typeFrom:typeFrom,dateFrom:dateFrom,typeTo:typeTo,dateTo:dateTo,ID:Int(ID)); break;
case "Sleep": GAPI.Instance().GetSleep(range,typeFrom:typeFrom,dateFrom:dateFrom,typeTo:typeTo,dateTo:dateTo,ID:Int(ID)); break;
case "Smoking": GAPI.Instance().GetSmoking(range,typeFrom:typeFrom,dateFrom:dateFrom,typeTo:typeTo,dateTo:dateTo,ID:Int(ID)); break;
case "Social": GAPI.Instance().GetSocial(range,typeFrom:typeFrom,dateFrom:dateFrom,typeTo:typeTo,dateTo:dateTo,ID:Int(ID)); break;
case "Stepcount": GAPI.Instance().GetStepcount(range,typeFrom:typeFrom,dateFrom:dateFrom,typeTo:typeTo,dateTo:dateTo,ID:Int(ID)); break;
//case "Survey": GAPI.Instance().GetSurvey(); break;
case "Wellbeing": GAPI.Instance().GetWellbeing(range,typeFrom:typeFrom,dateFrom:dateFrom,typeTo:typeTo,dateTo:dateTo,ID:Int(ID)); break;
case "Mood": GAPI.Instance().GetMood(range,typeFrom:typeFrom,dateFrom:dateFrom,typeTo:typeTo,dateTo:dateTo,ID:Int(ID)); break;
case "Happy": GAPI.Instance().GetHappy(range,typeFrom:typeFrom,dateFrom:dateFrom,typeTo:typeTo,dateTo:dateTo,ID:Int(ID)); break;
case "Uneasy": GAPI.Instance().GetUneasy(range,typeFrom:typeFrom,dateFrom:dateFrom,typeTo:typeTo,dateTo:dateTo,ID:Int(ID)); break;
case "Well": GAPI.Instance().GetWell(range,typeFrom:typeFrom,dateFrom:dateFrom,typeTo:typeTo,dateTo:dateTo,ID:Int(ID)); break;
case "Sad": GAPI.Instance().GetSad(range,typeFrom:typeFrom,dateFrom:dateFrom,typeTo:typeTo,dateTo:dateTo,ID:Int(ID)); break;
default: break;
}
}
@IBAction func pressedDelete(sender: UIButton)
{
SetBusy(true);
var selection:String = Types[pkType.selectedRowInComponent(0)];
var ev:String = lbDeleteID.text;
var ei:Int! = ev.toInt();
//Delete data record with the respective SDK call
switch(selection)
{
case "Activity": GAPI.Instance().DeleteActivity(Int32(ei)); break;
case "Alcohol": GAPI.Instance().DeleteAlcohol(Int32(ei)); break;
case "Body": GAPI.Instance().DeleteBody(Int32(ei)); break;
case "Caffeine": GAPI.Instance().DeleteCaffeine(Int32(ei)); break;
case "Events": GAPI.Instance().DeleteEvent(Int32(ei)); break;
case "Exercise": GAPI.Instance().DeleteExercise(Int32(ei)); break;
//case "Measures": GAPI.Instance().DeleteMeasures(Int32(ei)); break;
//case "Notifications": GAPI.Instance().DeleteNotifications(Int32(ei)); break;
case "Nutrition": GAPI.Instance().DeleteNutrition(Int32(ei)); break;
case "Sleep": GAPI.Instance().DeleteSleep(Int32(ei)); break;
case "Smoking": GAPI.Instance().DeleteSmoking(Int32(ei)); break;
case "Social": GAPI.Instance().DeleteSocial(Int32(ei)); break;
case "Stepcount": GAPI.Instance().DeleteStepcount(Int32(ei)); break;
//case "Survey": GAPI.Instance().DeleteSurvey(Int32(ei)); break;
case "Wellbeing": GAPI.Instance().DeleteWellbeing(Int32(ei)); break;
case "Mood": GAPI.Instance().DeleteWellbeing(Int32(ei)); break;
case "Happy": GAPI.Instance().DeleteWellbeing(Int32(ei)); break;
case "Uneasy": GAPI.Instance().DeleteWellbeing(Int32(ei)); break;
case "Well": GAPI.Instance().DeleteWellbeing(Int32(ei)); break;
case "Sad": GAPI.Instance().DeleteWellbeing(Int32(ei)); break;
default: break;
}
}
// Clear output view at top of screen
@IBAction func pressedClear(sender: UIButton)
{
lbText.text = "";
lbText.sizeToFit();
lbText.frame = CGRectMake(lbText.frame.origin.x, lbText.frame.origin.y, 300, lbText.frame.size.height);
svOutput.setContentOffset(CGPoint(x:0.0,y:0.0),animated:true);
}
// Clear user login token, resulting in current/different user having to log in again
@IBAction func pressedClearToken(sender: UIButton)
{
GAPI.Instance().ClearToken();
self.dismissViewControllerAnimated(true, completion: nil);
}
//Update views time entries to current date
@IBAction func pressedSetTimeNow(sender: UIButton?)
{
var date = GAPI.GetDateShort(0);
var now = GAPI.GetDateTime(0);
lbGetFrom.text = date;
lbGetTo.text = date;
//Time now
(svSendData.viewWithTag(2) as UITextField).text = now;
//Start time
(svSendData.viewWithTag(4) as UITextField).text = now;
//End time
(svSendData.viewWithTag(6) as UITextField).text = now;
}
//
// MARK: Callbacks
//
func SetBusy(truth: Bool)
{
aiBusy.hidden = !truth;
}
func Comment(text: String)
{
//Add comment to top of view
lbText.text = text + "\n" + lbText.text!;
lbText.sizeToFit();
lbText.frame = CGRectMake(lbText.frame.origin.x, lbText.frame.origin.y, 300, lbText.frame.size.height);
}
func CommentError(text: String)
{
Comment(text);
}
func CommentResult(text: String)
{
}
func CommentSystem(text: String)
{
}
func DataReceived(endPoint:String, withData:NSDictionary?, andString:String)
{
//Is data recieved not from default login process, display at top of view, as data apps user requested directly
if( dataRequested ||
( endPoint != "/defaults.json" && endPoint != "/account/signupmetadata"
&& endPoint != "/v1/me" && endPoint != "/v1/wellbeing"
&& endPoint != "/v1/o/events" && endPoint != "/v1/tags") )
{
Comment("Got data from '\(endPoint)' of '\(andString)'");
SetBusy(false);
dataRequested = false;
}
}
}
| 982f3279c49666867a77dceeb3751b5d | 43.765009 | 302 | 0.613955 | false | false | false | false |
coffee-cup/solis | refs/heads/master | SunriseSunset/Spring/Misc.swift | mit | 1 | // The MIT License (MIT)
//
// Copyright (c) 2015 Meng To (meng@designcode.io)
//
// 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
public extension String {
func toURL() -> NSURL? {
return NSURL(string: self)
}
}
public func htmlToAttributedString(text: String) -> NSAttributedString! {
let htmlData = text.data(using: String.Encoding.utf8, allowLossyConversion: false)
let htmlString: NSAttributedString?
do {
htmlString = try NSAttributedString(data: htmlData!, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil)
} catch _ {
htmlString = nil
}
return htmlString
}
public func degreesToRadians(degrees: CGFloat) -> CGFloat {
return degrees * CGFloat(CGFloat.pi / 180)
}
public func delay(delay:Double, closure: @escaping ()->()) {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure)
}
public func imageFromURL(_ Url: String) -> UIImage {
let url = Foundation.URL(string: Url)
let data = try? Data(contentsOf: url!)
return UIImage(data: data!)!
}
public func rgbaToUIColor(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) -> UIColor {
return UIColor(red: red, green: green, blue: blue, alpha: alpha)
}
public func UIColorFromRGB(rgbValue: UInt) -> UIColor {
return UIColor(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
public func stringFromDate(date: NSDate, format: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.string(from: date as Date)
}
public func dateFromString(date: String, format: String) -> Date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
if let date = dateFormatter.date(from: date) {
return date
} else {
return Date(timeIntervalSince1970: 0)
}
}
public func randomStringWithLength (len : Int) -> NSString {
let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
let randomString : NSMutableString = NSMutableString(capacity: len)
for _ in 0 ..< len {
let length = UInt32 (letters.length)
let rand = arc4random_uniform(length)
randomString.appendFormat("%C", letters.character(at: Int(rand)))
}
return randomString
}
public func timeAgoSinceDate(date: Date, numericDates: Bool) -> String {
let calendar = Calendar.current
let unitFlags = Set<Calendar.Component>(arrayLiteral: Calendar.Component.minute, Calendar.Component.hour, Calendar.Component.day, Calendar.Component.weekOfYear, Calendar.Component.month, Calendar.Component.year, Calendar.Component.second)
let now = Date()
let dateComparison = now.compare(date)
var earliest: Date
var latest: Date
switch dateComparison {
case .orderedAscending:
earliest = now
latest = date
default:
earliest = date
latest = now
}
let components: DateComponents = calendar.dateComponents(unitFlags, from: earliest, to: latest)
guard
let year = components.year,
let month = components.month,
let weekOfYear = components.weekOfYear,
let day = components.day,
let hour = components.hour,
let minute = components.minute,
let second = components.second
else {
fatalError()
}
if (year >= 2) {
return "\(year)y"
} else if (year >= 1) {
if (numericDates){
return "1y"
} else {
return "1y"
}
} else if (month >= 2) {
return "\(month * 4)w"
} else if (month >= 1) {
if (numericDates){
return "4w"
} else {
return "4w"
}
} else if (weekOfYear >= 2) {
return "\(weekOfYear)w"
} else if (weekOfYear >= 1){
if (numericDates){
return "1w"
} else {
return "1w"
}
} else if (day >= 2) {
return "\(String(describing: components.day))d"
} else if (day >= 1){
if (numericDates){
return "1d"
} else {
return "1d"
}
} else if (hour >= 2) {
return "\(hour)h"
} else if (hour >= 1){
if (numericDates){
return "1h"
} else {
return "1h"
}
} else if (minute >= 2) {
return "\(minute)m"
} else if (minute >= 1){
if (numericDates){
return "1m"
} else {
return "1m"
}
} else if (second >= 3) {
return "\(second)s"
} else {
return "now"
}
}
| 618a1a24e586332f9be802cb92ee7d4a | 30.796791 | 242 | 0.62849 | false | false | false | false |
Chaosspeeder/YourGoals | refs/heads/master | YourGoals/UI/Controller/SelectableCommitDatesCreator.swift | lgpl-3.0 | 1 | //
// CommitDatesCreator.swift
// YourGoals
//
// Created by André Claaßen on 17.12.17.
// Copyright © 2017 André Claaßen. All rights reserved.
//
import Foundation
enum CommitDateType {
case noCommitDate
case explicitCommitDate
case userDefinedCommitDate
}
/// a tuple representing a commit date in the future and a string representation
struct CommitDateTuple:Equatable {
static func ==(lhs: CommitDateTuple, rhs: CommitDateTuple) -> Bool {
return lhs.date == rhs.date && lhs.type == rhs.type
}
let text:String
let date:Date?
let type:CommitDateType
}
/// utility class for creating a list of commit dates
class SelectableCommitDatesCreator {
/// convert a commit date to a tuple with a readable text explanatin
///
/// - Parameter date: the date
/// - Returns: the tuple
func dateAsTuple(date:Date?, type: CommitDateType) -> CommitDateTuple {
switch type {
case .noCommitDate:
return CommitDateTuple(text: "No commit date", date: nil, type: type)
case .userDefinedCommitDate:
return CommitDateTuple(text: "Select date", date: nil, type: type)
default:
return CommitDateTuple(text: date!.formattedWithTodayTommorrowYesterday(), date: date, type: type)
}
}
/// create a list of commit dates for the next 7 days with a string
/// representation of the date
///
/// None (date = nil)
/// Today
/// Tommorrow
/// Tuesday (12/19/2017) (for 19.12.2017
/// Wednesday
///
/// - Parameters:
/// - date: start date of the list
/// - numberOfDays: a number of dates
/// - includingDate: a date which should be included in the list
///
/// - Returns: a list of formatted dates
func selectableCommitDates(startingWith date:Date, numberOfDays:Int, includingDate:Date? ) -> [CommitDateTuple] {
guard let range = Calendar.current.dateRange(startDate: date.day(), steps: numberOfDays-1) else {
NSLog("couldn't create a date range for startDate \(date) with days")
return []
}
var tuples = [CommitDateTuple]()
tuples.append(dateAsTuple(date: nil, type: .noCommitDate))
tuples.append(contentsOf: range.map { dateAsTuple(date: $0, type: .explicitCommitDate) })
tuples.append(dateAsTuple(date: nil, type: .userDefinedCommitDate))
if let includingDate = includingDate {
let tuple = tuples.first { $0.date?.compare(includingDate.day()) == .orderedSame }
if tuple == nil {
tuples.insert(dateAsTuple(date: includingDate.day(), type: .explicitCommitDate), at: 1)
}
}
return tuples
}
}
| 5b1f5281063cc2973330e11f7e843e96 | 32.590361 | 117 | 0.626255 | false | false | false | false |
Webtrekk/webtrekk-ios-sdk | refs/heads/master | Source/Internal/Utility/NSRange.swift | mit | 1 | import Foundation
internal extension NSRange {
init(forString string: String) {
self.init(range: string.startIndex ..< string.endIndex, inString: string)
}
init(range: Range<String.Index>?, inString string: String) {
if let range = range {
let location = NSRange.locationForIndex(range.lowerBound, inString: string)
let endLocation = NSRange.locationForIndex(range.upperBound, inString: string)
self.init(location: location, length: location.distance(to: endLocation))
} else {
self.init(location: NSNotFound, length: 0)
}
}
func endIndexInString(_ string: String) -> String.Index? {
return NSRange.indexForLocation(NSMaxRange(self), inString: string)
}
fileprivate static func indexForLocation(_ location: Int, inString string: String) -> String.Index? {
if location == NSNotFound {
return nil
}
return string.utf16.index(string.utf16.startIndex, offsetBy: location, limitedBy: string.utf16.endIndex)?.samePosition(in: string)
}
private static func locationForIndex(_ index: String.Index, inString string: String) -> Int {
guard let toPosition = index.samePosition(in: string.utf16) else {return -1}
return string.utf16.distance(from: string.utf16.startIndex, to: toPosition)
}
func rangeInString(_ string: String) -> Range<String.Index>? {
if let startIndex = startIndexInString(string),
let endIndex = endIndexInString(string) {
return startIndex ..< endIndex
}
return nil
}
func startIndexInString(_ string: String) -> String.Index? {
return NSRange.indexForLocation(location, inString: string)
}
}
| 75e3be51d8b9fbb4e2fe3181514d9e86 | 32.22449 | 138 | 0.713145 | false | false | false | false |
BenziAhamed/Nevergrid | refs/heads/master | NeverGrid/Source/TargetAction.swift | isc | 1 | //
// TargetAction.swift
// OnGettingThere
//
// Created by Benzi on 06/08/14.
// Copyright (c) 2014 Benzi Ahamed. All rights reserved.
//
// http://oleb.net/blog/2014/07/swift-instance-methods-curried-functions/
import Foundation
protocol TargetAction {
func performAction()
}
class Callback<T: AnyObject> : TargetAction {
weak var target: T?
let action: (T) -> () -> ()
init(_ target:T, _ action:(T) -> () -> ()) {
self.target = target
self.action = action
}
func performAction() -> () {
if let t = target {
action(t)()
}
}
}
//struct EventArgs { }
//
//protocol EventHandler {
// func handleEvent(sender:AnyObject, args:EventArgs)
//}
//
//struct EventHandlerCallback<T:AnyObject> : EventHandler {
// weak var target: T?
// let action: (T) -> (AnyObject,EventArgs) -> ()
//
// init(_ target:T, _ action:(T) -> (AnyObject,EventArgs) -> ()) {
// self.target = target
// self.action = action
// }
//
// func handleEvent(sender:AnyObject, args:EventArgs) -> () {
// if let t = target {
// action(t)(sender, args)
// }
// }
//}
| fa393cbdd3f87c68a62b7ceb732b0559 | 20.962963 | 73 | 0.554806 | false | false | false | false |
JGiola/swift | refs/heads/main | test/decl/protocol/special/coding/enum_codable_simple_conditional.swift | apache-2.0 | 13 | // RUN: %target-typecheck-verify-swift -verify-ignore-unknown -swift-version 4
enum Conditional<T> {
case a(x: T, y: T?)
case b(z: [T])
func foo() {
// They should receive a synthesized CodingKeys enum.
let _ = Conditional.CodingKeys.self
let _ = Conditional.ACodingKeys.self
// The enum should have a case for each of the cases.
let _ = Conditional.CodingKeys.a
let _ = Conditional.CodingKeys.b
// The enum should have a case for each of the parameters.
let _ = Conditional.ACodingKeys.x
let _ = Conditional.ACodingKeys.y
let _ = Conditional.BCodingKeys.z
}
}
extension Conditional: Codable where T: Codable { // expected-note 4{{where 'T' = 'Nonconforming'}}
}
// They should receive synthesized init(from:) and an encode(to:).
let _ = Conditional<Int>.init(from:)
let _ = Conditional<Int>.encode(to:)
// but only for Codable parameters.
struct Nonconforming {}
let _ = Conditional<Nonconforming>.init(from:) // expected-error {{referencing initializer 'init(from:)' on 'Conditional' requires that 'Nonconforming' conform to 'Encodable'}}
// expected-error@-1 {{referencing initializer 'init(from:)' on 'Conditional' requires that 'Nonconforming' conform to 'Decodable'}}
let _ = Conditional<Nonconforming>.encode(to:) // expected-error {{referencing instance method 'encode(to:)' on 'Conditional' requires that 'Nonconforming' conform to 'Encodable'}}
// expected-error@-1 {{referencing instance method 'encode(to:)' on 'Conditional' requires that 'Nonconforming' conform to 'Decodable'}}
// The synthesized CodingKeys type should not be accessible from outside the
// enum.
let _ = Conditional<Int>.CodingKeys.self // expected-error {{'CodingKeys' is inaccessible due to 'private' protection level}}
let _ = Conditional<Int>.ACodingKeys.self // expected-error {{'ACodingKeys' is inaccessible due to 'private' protection level}}
let _ = Conditional<Int>.BCodingKeys.self // expected-error {{'BCodingKeys' is inaccessible due to 'private' protection level}}
| cce495f8e1c4d3ef3281f9e96f6ea821 | 47.02381 | 180 | 0.722856 | false | false | false | false |
qinting513/SwiftNote | refs/heads/master | youtube/YouTube/Model/VideoItem.swift | apache-2.0 | 1 | //
// Video.swift
// YouTube
//
// Created by Haik Aslanyan on 6/27/16.
// Copyright © 2016 Haik Aslanyan. All rights reserved.
//
import Foundation
import UIKit
class VideoItem {
//MARK: Properties
let tumbnail: UIImage
let title: String
let views: Int
let channel: Channel
let duration: Int
//MARK: Download the list of items
class func getVideosList(fromURL: URL, completition: @escaping ([[String : AnyObject]]) -> (Void)) {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
var items = [[String : AnyObject]]()
URLSession.shared.dataTask(with: fromURL) { (data, response, error) in
if error != nil {
showNotification()
} else{
do{
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers)
items = json as! [[String : AnyObject]]
} catch _ {
showNotification()
}
completition(items)
}
}.resume()
}
//MARK: single item download
class func object(at: Int, fromList: Array<[String : AnyObject]>, completiotion: @escaping ((VideoItem, Int) -> Void)) {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
DispatchQueue.global(qos: .userInteractive).async(execute: {
let item = fromList[at]
let title = item["title"] as! String
let tumbnail = UIImage.contentOfURL(link: item["thumbnail_image_name"] as! String)
let views = item["number_of_views"] as! Int
let duration = item["duration"] as! Int
let channelDic = item["channel"] as! [String : String]
let channelPic = UIImage.contentOfURL(link: channelDic["profile_image_name"]!)
let channelName = channelDic["name"]!
let channel = Channel.init(name: channelName, image: channelPic)
let video = VideoItem.init(title: title, tumbnail: tumbnail, views: views, duration: duration, channel: channel)
completiotion(video, at)
})
}
//MARK: Inits
init(title: String, tumbnail: UIImage, views: Int, duration: Int, channel: Channel) {
self.title = title
self.views = views
self.tumbnail = tumbnail
self.channel = channel
self.duration = duration
}
}
| 9ab33ecd7952625fde249ccbccd5b523 | 35.58209 | 125 | 0.586291 | false | false | false | false |
MYLILUYANG/DouYuZB | refs/heads/master | DouYuZB/DouYuZB/Class/Home/View/PageTitleView.swift | mit | 1 | //
// PageTitleView.swift
// DouYuZB
//
// Created by liluyang on 17/2/13.
// Copyright © 2017年 liluyang. All rights reserved.
//
import UIKit
private let kScrollLineH : CGFloat = 2
class PageTitleView: UIView {
//定义属性
fileprivate var titles : [String]
//懒加载属性
fileprivate lazy var scrollView : UIScrollView = {
let scrollView = UIScrollView()
scrollView.showsHorizontalScrollIndicator = false
scrollView.scrollsToTop = false
scrollView.bounces = false
return scrollView
}()
fileprivate lazy var titleLabels : [UILabel] = [UILabel]()
fileprivate lazy var scrollLine : UIView = {
let scrollLine = UIView()
scrollLine.backgroundColor = UIColor.orange
return scrollLine
}()
//MARK - 自定义构造函数
init(frame: CGRect, titles:[String]) {
self.titles = titles
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension PageTitleView
{
fileprivate func setupUI(){
addSubview(scrollView)
//添加title对应的label
scrollView.frame = bounds;
setupTitleLabe()//添加titlelabel
setupBottonLineAndScrollLine()//添加底部线条
}
fileprivate func setupTitleLabe(){
let labelY : CGFloat = 0;
let labelW : CGFloat = frame.width / CGFloat(titles.count);
let labelH : CGFloat = frame.height - kScrollLineH;
for(index, title) in titles.enumerated(){
//创建label
let label = UILabel()
//设置label
label.text = title
label.tag = index
label.font = UIFont.systemFont(ofSize: 14.0)
label.textColor = UIColor.darkGray
label.textAlignment = .center
//设置label 的frame
let labelX : CGFloat = labelW * CGFloat(index);
label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH)
scrollView.addSubview(label)
titleLabels .append(label)
}
}
fileprivate func setupBottonLineAndScrollLine(){
//添加底部线条
let bottomLine = UIView()
bottomLine.backgroundColor = UIColor.lightGray
let lineH : CGFloat = 0.5
bottomLine.frame = CGRect(x: 0, y: frame.height - lineH, width: kScreenW, height: lineH)
addSubview(bottomLine)
//添加scrollline 获取第一个label
scrollView.addSubview(scrollLine)
guard let firstLabel = titleLabels.first else {return}
firstLabel.textColor = UIColor.orange
scrollLine.frame = CGRect(x: 0, y: frame.height - kScrollLineH, width: firstLabel.frame.size.width, height: kScrollLineH)
}
}
| ae06d26f6ea64a7befe6ac99bbc82d75 | 22.520661 | 129 | 0.599789 | false | false | false | false |
SeaHub/ImgTagging | refs/heads/master | ImgTagger/ImgTagger/NameChangingViewController.swift | gpl-3.0 | 1 | //
// NameChangingViewController.swift
// ImgTagger
//
// Created by SeaHub on 2017/6/30.
// Copyright © 2017年 SeaCluster. All rights reserved.
//
import UIKit
import NVActivityIndicatorView
import PopupDialog
class NameChangingViewController: UIViewController {
@IBOutlet weak var maskView: UIView!
@IBOutlet weak var nameTextField: UITextField!
private var indicator: NVActivityIndicatorView! = NVActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 100, height: 100), type: .ballScaleRippleMultiple, color: .white, padding: nil)
override func viewDidLoad() {
super.viewDidLoad()
self.configureIndicator()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
private func indicatorStartAnimating() {
UIView.animate(withDuration: 0.5) {
self.maskView.alpha = 0.5
}
}
private func indicatorStopAnimating() {
UIView.animate(withDuration: 0.5) {
self.maskView.alpha = 0
self.indicator.stopAnimating()
}
}
private func configureIndicator() {
self.indicator.center = CGPoint(x: self.view.bounds.width / 2, y: self.view.bounds.height / 2)
self.maskView.addSubview(self.indicator)
self.indicator.startAnimating()
}
private func showErrorAlert() {
let alert = PopupDialog(title: "Tips", message: "An error occured, please retry later!", image: nil)
let cancelButton = CancelButton(title: "OK") { }
alert.addButtons([cancelButton])
self.present(alert, animated: true, completion: nil)
}
@IBAction func commitButtonClicked(_ sender: Any) {
if let name = self.nameTextField.text {
self.indicatorStopAnimating()
APIManager.modifyInfo(token: ImgTaggerUtil.userToken!, name: name, avatarImage: nil, success: {
self.indicatorStopAnimating()
let alert = PopupDialog(title: "Tips", message: "Change successfully", image: nil)
let cancelButton = DefaultButton(title: "OK") {
self.navigationController?.popToRootViewController(animated: true)
}
alert.addButtons([cancelButton])
self.present(alert, animated: true, completion: nil)
}, failure: { (error) in
self.indicatorStopAnimating()
debugPrint(error.localizedDescription)
self.showErrorAlert()
})
}
}
@IBAction func backButtonClicked(_ sender: Any) {
self.navigationController?.popToRootViewController(animated: true)
}
// MARK: - Keyboard Related
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
}
| 63bfeebfe7db068b8bc88e2c67aa86af | 33.771084 | 190 | 0.623008 | false | false | false | false |
queueit/QueueIT.iOS.Sdk | refs/heads/master | QueueItSDK/StatusDTO.swift | lgpl-3.0 | 1 | import Foundation
class StatusDTO {
var eventDetails: EventDTO?
var redirectDto: RedirectDTO?
var widgets: [WidgetDTO]?
var nextCallMSec: Int
var rejectDto: RejectDTO?
init(_ eventDetails: EventDTO?, _ redirectDto: RedirectDTO?, _ widgets: [WidgetDTO]?, _ nextCallMSec: Int, _ rejectDto: RejectDTO?) {
self.eventDetails = eventDetails
self.redirectDto = redirectDto
self.widgets = widgets
self.nextCallMSec = nextCallMSec
self.rejectDto = rejectDto
}
}
| 6385ddd13083ea6a4bcb5cfb63da2f6a | 30 | 137 | 0.669829 | false | false | false | false |
gnachman/iTerm2 | refs/heads/master | iTermFileProvider/ItemCreator.swift | gpl-2.0 | 2 | //
// ItemCreator.swift
// FileProvider
//
// Created by George Nachman on 6/10/22.
//
import Foundation
import FileProvider
import FileProviderService
actor ItemCreator {
struct Request: CustomDebugStringConvertible {
let itemTemplate: NSFileProviderItem
let fields: NSFileProviderItemFields
let contents: URL?
let options: NSFileProviderCreateItemOptions
let request: NSFileProviderRequest
let progress = Progress()
var debugDescription: String {
return "<ItemCreator.Request template=\(itemTemplate.terseDescription) fields=\(fields.description) contents=\(contents.descriptionOrNil) options=\(options.description) request=\(request.description)>"
}
}
struct Item {
let item: NSFileProviderItem
let fields: NSFileProviderItemFields
let shouldFetchContent: Bool
}
private let domain: NSFileProviderDomain
private let manager: NSFileProviderManager
private let remoteService: RemoteService
init(domain: NSFileProviderDomain, remoteService: RemoteService) {
self.domain = domain
self.remoteService = remoteService
manager = NSFileProviderManager(for: domain)!
}
func create(_ request: Request) async throws -> Item {
try await logging("create(\(request))") {
guard let file = RemoteFile(template: request.itemTemplate,
fields: request.fields) else {
// There isn't an appropriate exception for when we don't support a file
// type (e.g., aliases).
throw NSFileProviderError(.noSuchItem)
}
let data: Data
if request.fields.contains(.contents), let url = request.contents {
data = try Data(contentsOf: url, options: .alwaysMapped)
log("content=\(data.stringOrHex)")
} else {
log("No content - using empty data just in case")
data = Data()
}
switch file.kind {
case .symlink(let target):
log("Create symlink")
_ = try await remoteService.ln(
source: await rebaseLocalFile(manager, path: target),
file: file)
case .folder:
log("Create folder")
try await remoteService.mkdir(file)
case .file(_):
log("Create file")
request.progress.totalUnitCount = Int64(data.count)
try await remoteService.create(file, content: data)
request.progress.completedUnitCount = Int64(data.count)
case .host:
log("Create host")
throw NSFileProviderError(.noSuchItem) // no appropriate error exists
}
return Item(item: await FileProviderItem(file, manager: manager),
fields: [],
shouldFetchContent: false)
}
}
}
extension RemoteFile {
init?(template: NSFileProviderItem,
fields: NSFileProviderItemFields) {
guard let kind = Self.kind(template, fields) else {
return nil
}
self.init(kind: kind,
absolutePath: Self.path(template),
permissions: Self.permissions(template, fields),
ctime: Self.ctime(template, fields),
mtime: Self.mtime(template, fields))
}
private static func ctime(_ template: NSFileProviderItem,
_ fields: NSFileProviderItemFields) -> Date {
if fields.contains(.creationDate),
case let creationDate?? = template.creationDate {
return creationDate
}
return Date()
}
private static func mtime(_ template: NSFileProviderItem,
_ fields: NSFileProviderItemFields) -> Date {
if fields.contains(.contentModificationDate),
case let modifiationDate?? = template.contentModificationDate {
return modifiationDate
}
return Date()
}
private static func permissions(_ template: NSFileProviderItem,
_ fields: NSFileProviderItemFields) -> Permissions {
if fields.contains(.fileSystemFlags), let flags = template.fileSystemFlags {
return Permissions(fileSystemFlags: flags)
}
return Permissions(r: true, w: true, x: true)
}
private static func path(_ template: NSFileProviderItem) -> String {
var url = URL(fileURLWithPath: template.parentItemIdentifier.rawValue)
url.appendPathComponent(template.filename)
return url.path
}
private static func kind(_ template: NSFileProviderItem,
_ fields: NSFileProviderItemFields) -> Kind? {
switch template.contentType {
case .folder?:
return .folder
case .symbolicLink?:
if fields.contains(.contents),
case let target?? = template.symlinkTargetPath {
return .symlink(target)
}
log("symlink without target not allowed")
return nil
case .aliasFile?:
log("aliases not supported")
return nil
default:
return .file(FileInfo(size: nil))
}
}
}
extension RemoteFile.Permissions {
init(fileSystemFlags flags: NSFileProviderFileSystemFlags) {
self.init(r: flags.contains(.userReadable),
w: flags.contains(.userWritable),
x: flags.contains(.userExecutable))
}
}
| b9cba7a66acd6e4d96f9ba852599ea0d | 34.465839 | 213 | 0.585289 | false | false | false | false |
sendyhalim/iYomu | refs/heads/master | Yomu/Screens/MangaList/MangaRealm.swift | mit | 1 | //
// MangaRealm.swift
// Yomu
//
// Created by Sendy Halim on 5/30/17.
// Copyright © 2017 Sendy Halim. All rights reserved.
//
import Foundation
import RealmSwift
/// Represents Manga object for `Realm` database
class MangaRealm: Object {
@objc dynamic var id: String = ""
@objc dynamic var slug: String = ""
@objc dynamic var title: String = ""
@objc dynamic var author: String = ""
@objc dynamic var imageEndpoint: String = ""
@objc dynamic var releasedYear: Int = 0
@objc dynamic var commaSeparatedCategories: String = ""
@objc dynamic var plot: String = ""
@objc dynamic var position: Int = MangaPosition.undefined.rawValue
override static func primaryKey() -> String? {
return "id"
}
/// Convert the given `Manga` struct to `MangaRealm` object
///
/// - parameter manga: `Manga`
///
/// - returns: `MangaRealm`
static func from(manga: Manga) -> MangaRealm {
let mangaRealm = MangaRealm()
mangaRealm.id = manga.id!
mangaRealm.slug = manga.slug
mangaRealm.title = manga.title
mangaRealm.author = manga.author
mangaRealm.imageEndpoint = manga.image.endpoint
mangaRealm.releasedYear = manga.releasedYear ?? 0
mangaRealm.commaSeparatedCategories = manga.categories.joined(separator: ",")
mangaRealm.position = manga.position
mangaRealm.plot = manga.plot
return mangaRealm
}
/// Convert the given `MangaRealm` object to `Manga` struct
///
/// - parameter mangaRealm: `MangaRealm`
///
/// - returns: `Manga`
static func mangaFrom(mangaRealm: MangaRealm) -> Manga {
let categories = mangaRealm
.commaSeparatedCategories
.split {
$0 == ","
}
.map(String.init)
return Manga(
position: mangaRealm.position,
id: mangaRealm.id,
slug: mangaRealm.slug,
title: mangaRealm.title,
author: mangaRealm.author,
image: ImageUrl(endpoint: mangaRealm.imageEndpoint),
releasedYear: mangaRealm.releasedYear,
plot: mangaRealm.plot,
categories: categories
)
}
}
| 19a70f9683c04bb442deb8a2abbe5094 | 26.77027 | 81 | 0.665693 | false | false | false | false |
maranathApp/GojiiFramework | refs/heads/master | GojiiFrameWork/UILabelExtensions.swift | mit | 1 | //
// CGFloatExtensions.swift
// GojiiFrameWork
//
// Created by Stency Mboumba on 01/06/2017.
// Copyright © 2017 Stency Mboumba. All rights reserved.
//
import UIKit
// MARK: - extension UILabel Initilizers
public extension UILabel {
/* --------------------------------------------------------------------------- */
// MARK: - Initilizers ( init )
/* --------------------------------------------------------------------------- */
/**
Initializes and returns a newly allocated view object with the specified frame rectangle.
- parameter frame: CGRect
- parameter text: String
- parameter textColor: UIColor
- parameter textAlignment: NSTextAlignment
- parameter font: UIFont
- returns: UILabel
*/
public convenience init (
frame: CGRect,
text: String,
textColor: UIColor,
textAlignment: NSTextAlignment,
font: UIFont) {
self.init(frame: frame)
self.text = text
self.textColor = textColor
self.textAlignment = textAlignment
self.font = font
self.numberOfLines = 0
}
/**
Initializes and returns a newly allocated view object with the specified frame rectangle.
- parameter x: CGFloat
- parameter y: CGFloat
- parameter width: CGFloat
- parameter height: CGFloat
- parameter text: String
- parameter textColor: UIColor
- parameter textAlignment: NSTextAlignment
- parameter font: UIFont
- returns: UILabel
*/
public convenience init (
x: CGFloat,
y: CGFloat,
width: CGFloat,
height: CGFloat,
text: String,
textColor: UIColor,
textAlignment: NSTextAlignment,
font: UIFont) {
self.init(frame: CGRect (x: x, y: y, width: width, height: height))
self.text = text
self.textColor = textColor
self.textAlignment = textAlignment
self.font = font
self.numberOfLines = 0
}
/**
Initializes and returns a newly allocated view object with the specified frame rectangle.
- parameter frame: CGRect
- parameter attributedText: NSAttributedString
- parameter textAlignment: NSTextAlignment
- returns: UILabel
*/
public convenience init (
frame: CGRect,
attributedText: NSAttributedString,
textAlignment: NSTextAlignment) {
self.init(frame: frame)
self.attributedText = attributedText
self.textAlignment = textAlignment
self.numberOfLines = 0
}
/**
Initializes and returns a newly allocated view object with the specified frame rectangle.
- parameter x: CGFloat
- parameter y: CGFloat
- parameter width: CGFloat
- parameter height: CGFloat
- parameter attributedText: NSAttributedString
- parameter textAlignment: NSTextAlignment
- returns: UILabel
*/
public convenience init (
x: CGFloat,
y: CGFloat,
width: CGFloat,
height: CGFloat,
attributedText: NSAttributedString,
textAlignment: NSTextAlignment) {
self.init(frame: CGRect (x: x, y: y, width: width, height: height))
self.attributedText = attributedText
self.textAlignment = textAlignment
self.numberOfLines = 0
}
/* --------------------------------------------------------------------------- */
// MARK: - Size
/* --------------------------------------------------------------------------- */
/**
Resize height of contraint of UILabel by new size text set, and number of line wanted
- parameter numberOfLine: Int / Number of numberOfLines
- parameter heightConstraint: NSLayoutConstraint
*/
public func resizeHeightToFit(numberOfLine:Int,heightConstraint: NSLayoutConstraint) {
let attributes = [NSFontAttributeName : font!]
self.numberOfLines = numberOfLine
self.lineBreakMode = NSLineBreakMode.byWordWrapping
let rect = text!.boundingRect(with: CGSize(width: frame.size.width,height: CGFloat.greatestFiniteMagnitude), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: attributes , context: nil)
heightConstraint.constant = rect.height
setNeedsLayout()
}
/**
Get new Size for text
- returns: CGSize
@available(*, deprecated=9.0)
public func getHeightByTextForView() -> CGRect {
let label:UILabel = UILabel(frame: CGRectMake(0, 0, self.width, CGFloat.max))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.ByWordWrapping
label.font = font
label.text = text
label.sizeToFit()
return label.frame
}*/
/**
Get Estimated Size
- parameter width: CGFloat
- parameter height: CGFloat
- returns: CGSize
*/
public func getEstimatedSize(width: CGFloat = CGFloat.greatestFiniteMagnitude, height: CGFloat = CGFloat.greatestFiniteMagnitude) -> CGSize {
return sizeThatFits(CGSize(width: width, height: height))
}
/**
Get Estimated Height
- returns: CGFloat
*/
public func getEstimatedHeight() -> CGFloat {
return sizeThatFits(CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)).height
}
/**
Get Estimated Width
- returns: CGFloat
*/
public func getEstimatedWidth() -> CGFloat {
return sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude, height: height)).width
}
/**
Size to fit Height
*/
public func sizeToFitHeight() {
self.height = getEstimatedHeight()
}
/**
Size to fit Width
*/
public func sizeToFitWidth() {
self.width = getEstimatedWidth()
}
/**
Size to fit Size
*/
public func sizeToFitSize() {
self.sizeToFitWidth()
self.sizeToFitHeight()
sizeToFit()
}
/* --------------------------------------------------------------------------- */
// MARK: - UILabel → Font
/* --------------------------------------------------------------------------- */
/// Font Size
public var fontSize:CGFloat {
get {
return self.font.pointSize
}
set {
self.font = UIFont(name: self.font.fontName, size: newValue)
}
}
/// Font Name
public var fontName:String {
get {
return self.font.fontName
}
set {
self.font = UIFont(name: newValue, size: self.font.pointSize)
}
}
/* --------------------------------------------------------------------------- */
// MARK: - UILabel → Animation
/* --------------------------------------------------------------------------- */
/**
Set Text With animation
- parameter text: String?
- parameter duration: NSTimeInterval?
*/
public func setTextAnimation(text: String?, duration: TimeInterval?) {
UIView.transition(with: self, duration: duration ?? 0.3, options: .transitionCrossDissolve, animations: { () -> Void in
self.text = text
}, completion: nil)
}
}
| a27338f2267e42cb547a38944d2f7480 | 29.696 | 211 | 0.530623 | false | false | false | false |
bigL055/Routable | refs/heads/master | Example/Pods/SPKit/Sources/Foundation/String+UIKit.swift | mit | 1 | //
// SPKit
//
// Copyright (c) 2017 linhay - https://github.com/linhay
//
// 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
import UIKit
// MARK: - 文本区域
public extension String{
/// 获取字符串的Bounds
///
/// - Parameters:
/// - font: 字体大小
/// - size: 字符串长宽限制
/// - Returns: 字符串的Bounds
public func bounds(font: UIFont,size: CGSize) -> CGRect {
if self.isEmpty { return CGRect.zero }
let attributes = [NSAttributedStringKey.font: font]
let option = NSStringDrawingOptions.usesLineFragmentOrigin
let rect = self.boundingRect(with: size, options: option, attributes: attributes, context: nil)
return rect
}
/// 获取字符串的Bounds
///
/// - parameter font: 字体大小
/// - parameter size: 字符串长宽限制
/// - parameter margins: 头尾间距
/// - parameter space: 内部间距
///
/// - returns: 字符串的Bounds
public func size(with font: UIFont,
size: CGSize,
margins: CGFloat = 0,
space: CGFloat = 0) -> CGSize {
if self.isEmpty { return CGSize.zero }
var bound = self.bounds(font: font, size: size)
let rows = self.rows(font: font, width: size.width)
bound.size.height += margins * 2
bound.size.height += space * (rows - 1)
return bound.size
}
/// 文本行数
///
/// - Parameters:
/// - font: 字体
/// - width: 最大宽度
/// - Returns: 行数
public func rows(font: UIFont,width: CGFloat) -> CGFloat {
if self.isEmpty { return 0 }
// 获取单行时候的内容的size
let singleSize = (self as NSString).size(withAttributes: [NSAttributedStringKey.font:font])
// 获取多行时候,文字的size
let textSize = self.bounds(font: font, size: CGSize(width: width, height: CGFloat(MAXFLOAT))).size
// 返回计算的行数
return ceil(textSize.height / singleSize.height);
}
}
| 5a6d363c9d505214dd613283d41e521d | 34.443038 | 102 | 0.668929 | false | false | false | false |
barankaraoguzzz/FastOnBoarding | refs/heads/master | FOView/Classes/FOView.swift | mit | 1 | //
// FOView.swift
// FastOnBoarding_Example
//
// Created by Baran on 4.04.2018.
// Copyright © 2018 CocoaPods. All rights reserved.
//
import UIKit
public class FOView: UIView {
//Mark: -Private Veriable
private var _imageView : UIImageView?
private var _pageControl : UIPageControl?
private var foAnimate = FOAnimation()
//Mark: -Public Veriable
public var foImages : [UIImage]?
public var foDiriction = animateDirection.horizantal
public var isPageControlEnable = true
public var animateType = AnimationStyle.alignedFlip
open var isPageControl : Bool = true {
didSet {
if self.isPageControl {
_pageControl?.isHidden = false
} else {
_pageControl?.isHidden = true
}
}
}
//Mark: -Delegate
public weak var delegate: FODelegate?
override init(frame: CGRect) {
super.init(frame: frame)
commonInıt()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInıt()
}
override public func layoutSubviews() {
setViewFrame()
}
private func commonInıt(){
_imageView = UIImageView()
_pageControl = UIPageControl()
}
public func startOnboarding(){
addSwipe()
}
private func setViewFrame(){
_imageView?.frame = self.frame
_imageView?.contentMode = .scaleAspectFill
_imageView?.clipsToBounds = true
print(isPageControl)
self.addSubview(_imageView!)
//Mark: - ***************************************
if isPageControlEnable {
_pageControl?.frame = CGRect(x: 0, y: self.frame.height - 30, width: self.frame.width, height: 30)
_pageControl?.backgroundColor = UIColor.black.withAlphaComponent(0.4)
_pageControl?.tintColor = UIColor.gray
_pageControl?.currentPageIndicatorTintColor = UIColor.white
self.addSubview(_pageControl!)
}
}
fileprivate func addSwipe(){
self.isUserInteractionEnabled = true
_imageView?.image = foImages![0]
_pageControl?.numberOfPages = (foImages?.count)!
switch foDiriction {
case .horizantal:
//Mark: -Right swipe add
let gestureRight = UISwipeGestureRecognizer(target: self, action: #selector(directionHorizantal(gesture:)))
gestureRight.direction = .right
self.addGestureRecognizer(gestureRight)
//Mark: -Left swipe add
let gestureLeft = UISwipeGestureRecognizer(target: self, action: #selector(directionHorizantal(gesture:)))
gestureRight.direction = .left
self.addGestureRecognizer(gestureLeft)
case .vertical:
//Mark: -Down swipe add
let gestureDown = UISwipeGestureRecognizer(target: self, action: #selector(directionVertical(gesture:)))
gestureDown.direction = .down
self.addGestureRecognizer(gestureDown)
//Mark: -Up swipe add
let gestureUp = UISwipeGestureRecognizer(target: self, action: #selector(directionVertical(gesture:)))
gestureUp.direction = .up
self.addGestureRecognizer(gestureUp)
}
}
@objc fileprivate func directionHorizantal(gesture :UIGestureRecognizer){
if let swipeGesture = gesture as? UISwipeGestureRecognizer {
switch swipeGesture.direction {
case UISwipeGestureRecognizerDirection.right:
if (_pageControl?.currentPage)! > 0{
foAnimate.addAnimation(animateType, view: self, subTypeStyle: .right)
_pageControl?.currentPage -= 1
_imageView?.image = foImages?[(_pageControl?.currentPage)!]
}
case UISwipeGestureRecognizerDirection.left:
if (_pageControl?.currentPage)! < (foImages?.count)! - 1{
foAnimate.addAnimation(animateType, view: self, subTypeStyle: .left)
_pageControl?.currentPage += 1
_imageView?.image = foImages?[(_pageControl?.currentPage)!]
}
default:break
}
if delegate != nil {
delegate?.FOnboarding(self, getCountPageControl: (_pageControl?.currentPage)!)
}
}
}
@objc fileprivate func directionVertical(gesture :UIGestureRecognizer){
if let swipeGesture = gesture as? UISwipeGestureRecognizer {
switch swipeGesture.direction {
case UISwipeGestureRecognizerDirection.down:
print("down")
if (_pageControl?.currentPage)! > 0{
foAnimate.addAnimation(animateType, view: self, subTypeStyle: .down)
_pageControl?.currentPage -= 1
_imageView?.image = foImages?[(_pageControl?.currentPage)!]
}
case UISwipeGestureRecognizerDirection.up:
print("Up")
if (_pageControl?.currentPage)! < (foImages?.count)! - 1{
foAnimate.addAnimation(animateType, view: self, subTypeStyle: .up)
_pageControl?.currentPage += 1
_imageView?.image = foImages?[(_pageControl?.currentPage)!]
}
default:break
}
if delegate != nil {
delegate?.FOnboarding(self, getCountPageControl: (_pageControl?.currentPage)!)
}
}
}
}
| bcebb447a033ef7ed115da575d092c97 | 34.288344 | 119 | 0.57041 | false | false | false | false |
colemancda/json-swift | refs/heads/master | src/JSValue.ErrorHandling.swift | mit | 4 | //
// JSValue.ErrorHandling.swift
// JSON
//
// Created by David Owens II on 8/11/14.
// Copyright (c) 2014 David Owens II. All rights reserved.
//
extension JSValue {
/// A type that holds the error code and standard error message for the various types of failures
/// a `JSValue` can have.
public struct ErrorMessage {
/// The numeric value of the error number.
public let code: Int
/// The default message describing the error.
public let message: String
}
/// All of the error codes and standard error messages when parsing JSON.
public struct ErrorCode {
private init() {}
/// A integer that is outside of the safe range was attempted to be set.
public static let InvalidIntegerValue = ErrorMessage(
code:1,
message: "The specified number is not valid. Valid numbers are within the range: [\(JSValue.MinimumSafeInt), \(JSValue.MaximumSafeInt)]")
/// Error when attempting to access an element from a `JSValue` backed by a dictionary and there is no
/// value stored at the specified key.
public static let KeyNotFound = ErrorMessage(
code: 2,
message: "The specified key cannot be found.")
/// Error when attempting to index into a `JSValue` that is not backed by a dictionary or array.
public static let IndexingIntoUnsupportedType = ErrorMessage(
code: 3,
message: "Indexing is only supported on arrays and dictionaries."
)
/// Error when attempting to access an element from a `JSValue` backed by an array and the index is
/// out of range.
public static let IndexOutOfRange = ErrorMessage(
code: 4,
message: "The specified index is out of range of the bounds for the array.")
/// Error when a parsing error occurs.
public static let ParsingError = ErrorMessage(
code: 5,
message: "The JSON string being parsed was invalid.")
}
}
| 18343006c1270d6b999d2282ff3e333c | 38.45283 | 149 | 0.626495 | false | false | false | false |
meetkei/KxUI | refs/heads/master | KxUI/Color/UIColor+Hex.swift | mit | 1 | //
// Copyright (c) 2016 Keun young Kim <app@meetkei.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
public extension UIColor {
////////////////////////////////////////////////////////////////////////////////////////////////
// MARK: - Initializing a UIColor Object
/**
Initializes and returns a color object using the hexadecimal color string.
- Parameter hexString: the hexadecimal color string.
- Returns: An initialized color object. If *hexString* is not a valid hexadecimal color string, returns a color object whose grayscale value is 1.0 and whose alpha value is 1.0.
*/
convenience init(hexString: String) {
var red: CGFloat = 1.0
var green: CGFloat = 1.0
var blue: CGFloat = 1.0
var alpha: CGFloat = 1.0
if let color = hexString.parseHexColorString() {
color.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
}
self.init(red:red, green:green, blue:blue, alpha:alpha)
}
var rgbHexString: String {
return toHexString(includeAlpha: false)
}
var rgbaHexString: String {
return toHexString(includeAlpha: true)
}
private func toHexString(includeAlpha: Bool) -> String {
var normalizedR: CGFloat = 0
var normalizedG: CGFloat = 0
var normalizedB: CGFloat = 0
var normalizedA: CGFloat = 0
getRed(&normalizedR, green: &normalizedG, blue: &normalizedB, alpha: &normalizedA)
let r = Int(normalizedR * 255)
let g = Int(normalizedG * 255)
let b = Int(normalizedB * 255)
let a = Int(normalizedA * 255)
if includeAlpha {
return String(format: "#%02X%02X%02X%02X", r, g, b, a)
}
return String(format: "#%02X%02X%02X", r, g, b)
}
}
| eee786b77e0019512141e55e27dbef9e | 37.324675 | 182 | 0.631311 | false | false | false | false |
ssh88/ImageCacheable | refs/heads/master | ImageCacheable/Classes/ImageCacheable.swift | mit | 1 | //
// ImageCacheable.swift
// ImageCacheable
//
// Created by Shabeer Hussain on 23/11/2016.
// Copyright © 2016 Desert Monkey. All rights reserved.
//
import Foundation
import UIKit
protocol ImageCacheable {
/**
Retrieves an image from the local file system. If the image does not exist it will save it
*/
func localImage(forKey key: String, from remoteUrl: URL, completion:@escaping ((UIImage?, String) -> Void))
/**
Retrieves an image from the in memory cache. These images are not persisted across sessions
*/
func inMemoryImage(forKey key: String, from url: URL, completion:@escaping ((UIImage?, String) -> Void))
/**
Folder name. Defaults to "ImageCacheable" unless dedicated cache object declares new name
*/
var imageFolderName: String? {get}
/**
Cache object, only initialized by the conforming object if calling
inMemoryImage(forKey:from:completion:)
*/
var inMemoryImageCache: NSCache<AnyObject, UIImage>? {get}
}
extension ImageCacheable {
//both properties have default values initialized on get
var imageFolderName: String? { return "ImageCacheable" }
var inMemoryImageCache: NSCache<AnyObject, UIImage>? { return NSCache<AnyObject, UIImage>() }
//MARK:- Image Fetching
func localImage(forKey key: String, from remoteUrl: URL, completion:@escaping ((UIImage?, String) -> Void)) {
//create the file path
let documentsDir = imageDirectoryURL().path
var filePathString = "\(documentsDir)/\(key)"
//get the file extension
if let fileExtension = fileExtension(for: remoteUrl) {
filePathString.append(fileExtension)
}
//next create the localURL
let localURL = URL(fileURLWithPath: filePathString)
//checks if the image should be saved locally
let imageExistsLocally = self.fileExists(at: filePathString)
//creates the data url from where to fetch, can be local or remote
let dataURL = imageExistsLocally ? localURL : remoteUrl
//finally fetch the image, pass in the localURL if we need to save it locally
self.fetchImage(from: dataURL, saveTo: (imageExistsLocally ? nil : localURL)) { image in
//grab main thread, as its more than likley this will serve UI layers
DispatchQueue.main.sync {
completion(image, key)
}
}
}
func inMemoryImage(forKey key: String, from url: URL, completion:@escaping ((UIImage?, String) -> Void)) {
guard let inMemoryImageCache = inMemoryImageCache else {
fatalError("ERROR: in Memory Image Cache must be set in order to use in-memory image cache")
}
if let cachedImage = inMemoryImageCache.object(forKey: key as AnyObject) {
completion(cachedImage, key)
} else {
fetchImage(from: url, saveTo: nil, completion: { (image) in
if let image = image {
inMemoryImageCache.setObject(image, forKey: key as AnyObject)
}
completion(image, key)
})
}
}
/**
Creates the UIImage from either local or remote url. If remote, will save to disk
*/
private func fetchImage(from url: URL,
saveTo localURL: URL?,
session: URLSession = URLSession.shared,
completion:@escaping ((UIImage?) -> Void)) {
session.dataTask(with: url) { (imageData, response, error) in
do {
guard
let imageData = imageData,
let image = UIImage(data: imageData)
else {
completion(nil)
return
}
//save if the localURL exists
if let localURL = localURL {
try imageData.write(to: localURL, options: .atomic)
}
completion(image)
} catch {
debugPrint(error.localizedDescription)
completion(nil)
}
}.resume()
}
//MARK:- Cache Management
/**
Deletes the image files on disk
*/
internal func clearLocalCache(success: (Bool) -> Void) {
let fileManager = FileManager.default
let imageDirectory = imageDirectoryURL()
if fileManager.isDeletableFile(atPath: imageDirectory.path) {
do {
try fileManager.removeItem(atPath: imageDirectory.path)
success(true)
} catch {
debugPrint(error.localizedDescription)
success(false)
}
}
success(true)
}
/**
Clears the in memory image cache
*/
internal func clearInMemoryCache(success: (Bool) -> Void) {
guard let inMemoryImageCache = inMemoryImageCache else {
success (false)
return
}
inMemoryImageCache.removeAllObjects()
success (true)
}
/*
TODO: need to handle the success/failure options better before implementing
a clear function that handles both caches
/**
Clears both the in-memory and disk image cache
*/
internal func clearCache(success: (Bool) -> Void) {
clearInMemoryCache { (_) in
clearLocalCache { (_) in
success(true)
}
}
}
*/
//MARK:- File Management
internal func fileExtension(for url: URL) -> String? {
let components = URLComponents(url: url, resolvingAgainstBaseURL: true)
guard let fileExtension = components?.url?.pathComponents.last?.components(separatedBy: ".").last else {
return nil
}
return ".\(fileExtension)"
}
internal func fileExists(at path: String) -> Bool {
return FileManager.default.fileExists(atPath: path)
}
/**
Returns the image folder directory
*/
internal func imageDirectoryURL() -> URL {
guard let imageFolderName = imageFolderName else {
fatalError("ERROR: Image Folder Name must be set in order to use local file storage image cache")
}
//get a ref to the sandbox documents folder
let documentsPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
//next create a file path to the new documents folder (uses the protcols imagefolderName)
let imageFolderPath = documentsPath.appendingPathComponent(imageFolderName)
//next we check if the folder needs to be creaded
let fileManager = FileManager.default
var directoryExists : ObjCBool = false
if fileManager.fileExists(atPath: imageFolderPath.path, isDirectory:&directoryExists) {
if directoryExists.boolValue {
//if it already exists, return it
return imageFolderPath
}
} else {
// otherwise if it doesnt exist, we create and return it
do {
try FileManager.default.createDirectory(atPath: imageFolderPath.path, withIntermediateDirectories: true, attributes: nil)
} catch {
debugPrint(error.localizedDescription)
}
}
return imageFolderPath
}
}
| 7529dc9931305b86a16b56e5df41e669 | 33.242152 | 137 | 0.581456 | false | false | false | false |
mikelikespie/swiftled | refs/heads/master | src/main/swift/OPC/ClientConnection.swift | mit | 1 | //
// ClientConnection.swift
// SwiftledMobile
//
// Created by Michael Lewis on 12/29/15.
// Copyright © 2015 Lolrus Industries. All rights reserved.
//
import Foundation
import Dispatch
import RxSwift
private let headerSize = 4
private let broadcastChannel: UInt8 = 0
enum OpcCommand : UInt8 {
case setPixels = 0
case customCommand = 255
}
/// A way to reuse by applying an element type over ourselves. This is how a "ClientConnection" is represented
public protocol ValueSink : class {
/// Usually a pixel format or something
associatedtype Element
/// The function we pass in is called inine which should return an element at each index
}
public enum ConnectionMode {
case rgb8 // use for standard OPC protocol
case rgbaRaw // APA protocol for used in go-led-spi. Color conversion will probably be slower
}
extension ConnectionMode {
var bytesPerPixel: Int {
switch self {
case .rgb8: return 3
case .rgbaRaw: return 4
}
}
var headerCommand: OpcCommand {
switch self {
case .rgb8: return .setPixels
case .rgbaRaw: return .customCommand
}
}
}
public final class ClientConnection : Collection {
public typealias Element = RGBFloat
public typealias Index = Int
private var pixelBuffer: [UInt8]
private let workQueue = DispatchQueue(label: "connection work queue", attributes: [])
private var channel: DispatchIO
private var ledCount: Int
private var start: TimeInterval
private let mode: ConnectionMode
private let bytesPerPixel: Int
public init(fd: Int32, ledCount: Int, mode: ConnectionMode) {
self.mode = mode
bytesPerPixel = mode.bytesPerPixel
self.pixelBuffer = [UInt8](repeating: 0, count: headerSize + ledCount * bytesPerPixel)
// Only support 1 channel for now
let channel = broadcastChannel
pixelBuffer[0] = channel
pixelBuffer[1] = mode.headerCommand.rawValue
pixelBuffer[2] = UInt8(truncatingBitPattern: UInt(self.pixelBuffer.count - headerSize) >> 8)
pixelBuffer[3] = UInt8(truncatingBitPattern: UInt(self.pixelBuffer.count - headerSize) >> 0)
self.start = Date.timeIntervalSinceReferenceDate
self.ledCount = ledCount
self.channel = DispatchIO(type: DispatchIO.StreamType.stream, fileDescriptor: fd, queue: workQueue, cleanupHandler: { _ in })
// self.channel.setLimit(lowWater: 0)
// self.channel.setLimit(highWater: Int.max)
self.channel.setInterval(interval: .seconds(0), flags: DispatchIO.IntervalFlags.strictInterval)
}
public func apply<C: ColorConvertible>( _ fn: (_ index: Int, _ now: TimeInterval) -> C) {
let timeOffset = Date.timeIntervalSinceReferenceDate - start
applyOverRange(0..<ledCount, iterations: 4) { rng in
for idx in rng {
self[idx] = fn(idx, timeOffset).rgbFloat
}
}
}
public var startIndex: Int {
return 0
}
public var endIndex: Int {
return self.ledCount
}
public func index(after i: Index) -> Index {
return i + 1
}
public subscript(index: Int) -> RGBFloat {
get {
let baseOffset = headerSize + index * bytesPerPixel
switch mode {
case .rgb8:
return RGB8(
r: pixelBuffer[baseOffset],
g: pixelBuffer[baseOffset + 1],
b: pixelBuffer[baseOffset + 2]
).rgbFloat
case .rgbaRaw:
return RGBARaw(
r: pixelBuffer[baseOffset],
g: pixelBuffer[baseOffset + 1],
b: pixelBuffer[baseOffset + 2],
a: pixelBuffer[baseOffset + 3]
).rgbFloat
}
}
set {
let baseOffset = headerSize + index * bytesPerPixel
switch mode {
case .rgb8:
let color = newValue.rgb8
pixelBuffer[baseOffset] = color.r
pixelBuffer[baseOffset + 1] = color.g
pixelBuffer[baseOffset + 2] = color.b
case .rgbaRaw:
let color = newValue.rawColor
pixelBuffer[baseOffset] = color.r
pixelBuffer[baseOffset + 1] = color.g
pixelBuffer[baseOffset + 2] = color.b
pixelBuffer[baseOffset + 3] = color.a
}
}
}
public func flush() -> Observable<Void> {
let dispatchData: DispatchData = self.pixelBuffer.withUnsafeBufferPointer {
#if os(Linux)
return DispatchData(bytes: $0)
#else
return DispatchData(bytesNoCopy: $0, deallocator: DispatchData.Deallocator.custom(nil, {}))
#endif
}
let subject = PublishSubject<Void>()
self
.channel
.write(
offset: 0,
data: dispatchData,
queue: self.workQueue
) { done, data, error in
guard error == 0 else {
subject.onError(Error.errorFromStatusCode(error)!)
return
}
if done {
subject.onNext()
subject.onCompleted()
}
}
// self.channel.barrier {
// _ = self.channel.fileDescriptor;
// }
return subject
}
deinit {
NSLog("Deiniting")
}
}
public func applyOverRange(_ fullBounds: CountableRange<Int>, iterations: Int = 16, fn: (CountableRange<Int>) -> ()) {
let chunkSize = ((fullBounds.count - 1) / iterations) + 1
let splitBounds = (0..<iterations).map { idx in
(fullBounds.lowerBound + chunkSize * idx)..<min((fullBounds.lowerBound + chunkSize * (idx + 1)), fullBounds.upperBound)
}
DispatchQueue.concurrentPerform(iterations: iterations) { idx in
let bounds = splitBounds[idx]
fn(bounds)
}
}
| 5c3902d57ba81d2a6354b7b7b9c78aed | 29.765854 | 133 | 0.562391 | false | false | false | false |
wireapp/wire-ios | refs/heads/develop | Wire-iOS/Sources/UserInterface/StartUI/Common/SectionControllers/Suggestions/DirectorySectionController.swift | gpl-3.0 | 1 | //
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import WireDataModel
import UIKit
import WireSyncEngine
final class DirectorySectionController: SearchSectionController {
var suggestions: [ZMSearchUser] = []
weak var delegate: SearchSectionControllerDelegate?
var token: AnyObject?
weak var collectionView: UICollectionView?
override var isHidden: Bool {
return self.suggestions.isEmpty
}
override var sectionTitle: String {
return "peoplepicker.header.directory".localized
}
override func prepareForUse(in collectionView: UICollectionView?) {
super.prepareForUse(in: collectionView)
collectionView?.register(UserCell.self, forCellWithReuseIdentifier: UserCell.zm_reuseIdentifier)
self.token = UserChangeInfo.add(searchUserObserver: self, in: ZMUserSession.shared()!)
self.collectionView = collectionView
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return suggestions.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let user = suggestions[indexPath.row]
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: UserCell.zm_reuseIdentifier, for: indexPath) as! UserCell
cell.configure(with: user, selfUser: ZMUser.selfUser())
cell.showSeparator = (suggestions.count - 1) != indexPath.row
cell.userTypeIconView.isHidden = true
cell.accessoryIconView.isHidden = true
cell.connectButton.isHidden = !user.canBeUnblocked
if user.canBeUnblocked {
cell.accessibilityHint = L10n.Accessibility.ContactsList.PendingConnection.hint
}
cell.connectButton.tag = indexPath.row
cell.connectButton.addTarget(self, action: #selector(connect(_:)), for: .touchUpInside)
return cell
}
@objc func connect(_ sender: AnyObject) {
guard let button = sender as? UIButton else { return }
let indexPath = IndexPath(row: button.tag, section: 0)
let user = suggestions[indexPath.row]
if user.isBlocked {
user.accept { [weak self] error in
guard
let strongSelf = self,
let error = error as? UpdateConnectionError
else {
return
}
self?.delegate?.searchSectionController(strongSelf, wantsToDisplayError: error)
}
} else {
user.connect { [weak self] error in
guard
let strongSelf = self,
let error = error as? ConnectToUserError
else {
return
}
self?.delegate?.searchSectionController(strongSelf, wantsToDisplayError: error)
}
}
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let user = suggestions[indexPath.row]
delegate?.searchSectionController(self, didSelectUser: user, at: indexPath)
}
}
extension DirectorySectionController: ZMUserObserver {
func userDidChange(_ changeInfo: UserChangeInfo) {
guard changeInfo.connectionStateChanged else { return }
collectionView?.reloadData()
}
}
| 09d8b7cd9be6ddee6b6f0f71b616d2b3 | 33.957265 | 132 | 0.671149 | false | false | false | false |
BasqueVoIPMafia/cordova-plugin-iosrtc | refs/heads/master | src/PluginRTCTypes.swift | mit | 3 | struct PluginRTCTypes {
static let signalingStates = [
RTCSignalingState.stable.rawValue: "stable",
RTCSignalingState.haveLocalOffer.rawValue: "have-local-offer",
RTCSignalingState.haveLocalPrAnswer.rawValue: "have-local-pranswer",
RTCSignalingState.haveRemoteOffer.rawValue: "have-remote-offer",
RTCSignalingState.haveRemotePrAnswer.rawValue: "have-remote-pranswer",
RTCSignalingState.closed.rawValue: "closed"
]
static let iceGatheringStates = [
RTCIceGatheringState.new.rawValue: "new",
RTCIceGatheringState.gathering.rawValue: "gathering",
RTCIceGatheringState.complete.rawValue: "complete"
]
static let iceConnectionStates = [
RTCIceConnectionState.new.rawValue: "new",
RTCIceConnectionState.checking.rawValue: "checking",
RTCIceConnectionState.connected.rawValue: "connected",
RTCIceConnectionState.completed.rawValue: "completed",
RTCIceConnectionState.failed.rawValue: "failed",
RTCIceConnectionState.disconnected.rawValue: "disconnected",
RTCIceConnectionState.closed.rawValue: "closed"
]
static let dataChannelStates = [
RTCDataChannelState.connecting.rawValue: "connecting",
RTCDataChannelState.open.rawValue: "open",
RTCDataChannelState.closing.rawValue: "closing",
RTCDataChannelState.closed.rawValue: "closed"
]
static let mediaStreamTrackStates = [
RTCMediaStreamTrackState.live.rawValue: "live",
RTCMediaStreamTrackState.ended.rawValue: "ended"
]
}
| 16323e85605ce131b90d2f480c5c77a9 | 38.410256 | 72 | 0.738452 | false | false | false | false |
NinjaIshere/GKGraphKit | refs/heads/master | GKGraphKit/GKManagedEntity.swift | agpl-3.0 | 1 | /**
* Copyright (C) 2015 GraphKit, Inc. <http://graphkit.io> and other GraphKit contributors.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program located at the root of the software package
* in a file called LICENSE. If not, see <http://www.gnu.org/licenses/>.
*
* GKManagedEntity
*
* Represents an Entity Model Object in the persistent layer.
*/
import CoreData
@objc(GKManagedEntity)
internal class GKManagedEntity: GKManagedNode {
@NSManaged internal var actionSubjectSet: NSSet
@NSManaged internal var actionObjectSet: NSSet
@NSManaged internal var bondSubjectSet: NSSet
@NSManaged internal var bondObjectSet: NSSet
/**
* entityDescription
* Class method returning an NSEntityDescription Object for this Model Object.
* @return NSEntityDescription!
*/
class func entityDescription() -> NSEntityDescription! {
let graph: GKGraph = GKGraph()
return NSEntityDescription.entityForName(GKGraphUtility.entityDescriptionName, inManagedObjectContext: graph.managedObjectContext)
}
/**
* init
* Initializes the Model Object with e a given type.
* @param type: String!
*/
convenience internal init(type: String!) {
let graph: GKGraph = GKGraph()
let entitiDescription: NSEntityDescription! = NSEntityDescription.entityForName(GKGraphUtility.entityDescriptionName, inManagedObjectContext: graph.managedObjectContext)
self.init(entity: entitiDescription, managedObjectContext: graph.managedObjectContext)
nodeClass = "GKEntity"
self.type = type
actionSubjectSet = NSSet()
actionObjectSet = NSSet()
bondSubjectSet = NSSet()
bondObjectSet = NSSet()
}
/**
* properties[ ]
* Allows for Dictionary style coding, which maps to the internal properties Dictionary.
* @param name: String!
* get Returns the property name value.
* set Value for the property name.
*/
override internal subscript(name: String) -> AnyObject? {
get {
for node in propertySet {
let property: GKEntityProperty = node as GKEntityProperty
if name == property.name {
return property.value
}
}
return nil
}
set(value) {
for node in propertySet {
let property: GKEntityProperty = node as GKEntityProperty
if name == property.name {
if nil == value {
propertySet.removeObject(property)
managedObjectContext!.deleteObject(property)
} else {
property.value = value!
}
return
}
}
if nil != value {
var property: GKEntityProperty = GKEntityProperty(name: name, value: value, managedObjectContext: managedObjectContext)
property.node = self
propertySet.addObject(property)
}
}
}
/**
* addGroup
* Adds a Group name to the list of Groups if it does not exist.
* @param name: String!
* @return Bool of the result, true if added, false otherwise.
*/
override internal func addGroup(name: String!) -> Bool {
if !hasGroup(name) {
var group: GKEntityGroup = GKEntityGroup(name: name, managedObjectContext: managedObjectContext!)
group.node = self
groupSet.addObject(group)
return true
}
return false
}
/**
* hasGroup
* Checks whether the Node is a part of the Group name passed or not.
* @param name: String!
* @return Bool of the result, true if is a part, false otherwise.
*/
override internal func hasGroup(name: String!) -> Bool {
for node in groupSet {
let group: GKEntityGroup = node as GKEntityGroup
if name == group.name {
return true
}
}
return false
}
/**
* removeGroup
* Removes a Group name from the list of Groups if it exists.
* @param name: String!
* @return Bool of the result, true if exists, false otherwise.
*/
override internal func removeGroup(name: String!) -> Bool {
for node in groupSet {
let group: GKEntityGroup = node as GKEntityGroup
if name == group.name {
groupSet.removeObject(group)
managedObjectContext!.deleteObject(group)
return true
}
}
return false
}
/**
* delete
* Marks the Model Object to be deleted from the Graph.
*/
internal func delete() {
var nodes: NSMutableSet = actionSubjectSet as NSMutableSet
for node in nodes {
nodes.removeObject(node)
}
nodes = actionObjectSet as NSMutableSet
for node in nodes {
nodes.removeObject(node)
}
nodes = propertySet as NSMutableSet
for node in nodes {
nodes.removeObject(node)
managedObjectContext!.deleteObject(node as GKEntityProperty)
}
nodes = groupSet as NSMutableSet
for node in nodes {
nodes.removeObject(node)
managedObjectContext!.deleteObject(node as GKEntityGroup)
}
managedObjectContext!.deleteObject(self)
}
}
/**
* An extension used to handle the many-to-many relationship with Actions.
*/
extension GKManagedEntity {
/**
* addActionSubjectSetObject
* Adds the Action to the actionSubjectSet for the Entity.
* @param value: GKManagedAction
*/
func addActionSubjectSetObject(value: GKManagedAction) {
let nodes: NSMutableSet = actionSubjectSet as NSMutableSet
nodes.addObject(value)
}
/**
* removeActionSubjectSetObject
* Removes the Action to the actionSubjectSet for the Entity.
* @param value: GKManagedAction
*/
func removeActionSubjectSetObject(value: GKManagedAction) {
let nodes: NSMutableSet = actionSubjectSet as NSMutableSet
nodes.removeObject(value)
}
/**
* addActionObjectSetObject
* Adds the Action to the actionObjectSet for the Entity.
* @param value: GKManagedAction
*/
func addActionObjectSetObject(value: GKManagedAction) {
let nodes: NSMutableSet = actionObjectSet as NSMutableSet
nodes.addObject(value)
}
/**
* removeActionObjectSetObject
* Removes the Action to the actionObjectSet for the Entity.
* @param value: GKManagedAction
*/
func removeActionObjectSetObject(value: GKManagedAction) {
let nodes: NSMutableSet = actionObjectSet as NSMutableSet
nodes.removeObject(value)
}
}
/**
* An extension used to handle the many-to-many relationship with Bonds.
*/
extension GKManagedEntity {
/**
* addBondSubjectSetObject
* Adds the Bond to the bondSubjectSet for the Entity.
* @param value: GKManagedBond
*/
func addBondSubjectSetObject(value: GKManagedBond) {
let nodes: NSMutableSet = bondSubjectSet as NSMutableSet
nodes.addObject(value)
}
/**
* removeBondSubjectSetObject
* Removes the Bond to the bondSubjectSet for the Entity.
* @param value: GKManagedBond
*/
func removeBondSubjectSetObject(value: GKManagedBond) {
let nodes: NSMutableSet = bondSubjectSet as NSMutableSet
nodes.removeObject(value)
}
/**
* addBondObjectSetObject
* Adds the Bond to the bondObjectSet for the Entity.
* @param value: GKManagedBond
*/
func addBondObjectSetObject(value: GKManagedBond) {
let nodes: NSMutableSet = bondObjectSet as NSMutableSet
nodes.addObject(value)
}
/**
* removeBondObjectSetObject
* Removes the Bond to the bondObjectSet for the Entity.
* @param value: GKManagedBond
*/
func removeBondObjectSetObject(value: GKManagedBond) {
let nodes: NSMutableSet = bondObjectSet as NSMutableSet
nodes.removeObject(value)
}
} | 03e7c058fbb800126a42b7d95a9a8200 | 32.162879 | 177 | 0.636052 | false | false | false | false |
shridharmalimca/LocationTracking | refs/heads/master | LocationTracking/LocationTracking/CoreDataService.swift | apache-2.0 | 3 |
import CoreData
protocol CoreDataServiceProtocol:class {
var errorHandler: (Error) -> Void {get set}
var persistentContainer: NSPersistentContainer {get}
var mainContext: NSManagedObjectContext {get}
var backgroundContext: NSManagedObjectContext {get}
func performBackgroundTask(_ block: @escaping (NSManagedObjectContext) -> Void)
func performForegroundTask(_ block: @escaping (NSManagedObjectContext) -> Void)
}
final class CoreDataService: CoreDataServiceProtocol {
static let shared = CoreDataService()
var errorHandler: (Error) -> Void = {_ in }
lazy var persistentContainer: NSPersistentContainer = {
let container = PersistentContainer(name: "LocationTracking")
if let fileLocation = container.persistentStoreDescriptions[0].url?.absoluteString {
print("Core Database file location : \n\t \(fileLocation).")
}
container.loadPersistentStores(completionHandler: { [weak self](storeDescription, error) in
if let error = error {
self?.errorHandler(error)
}
})
return container
}()
lazy var mainContext: NSManagedObjectContext = {
return self.persistentContainer.viewContext
}()
lazy var backgroundContext: NSManagedObjectContext = {
return self.persistentContainer.newBackgroundContext()
}()
func performForegroundTask(_ block: @escaping (NSManagedObjectContext) -> Void) {
self.mainContext.perform {
block(self.mainContext)
}
}
func performBackgroundTask(_ block: @escaping (NSManagedObjectContext) -> Void) {
self.persistentContainer.performBackgroundTask(block)
}
func saveContext() {
let backgrounndContext = backgroundContext
if backgrounndContext.hasChanges {
do {
try backgrounndContext.save()
} catch let error as NSError {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
}
}
}
| fe3e22d7dab996b75586f238bcebde98 | 33.262295 | 99 | 0.646411 | false | false | false | false |
haranicle/AlcatrazTour | refs/heads/master | AlcatrazTour/PluginTableViewController.swift | mit | 1 | //
// PluginListMainViewController
// AlcatrazTour
//
// Copyright (c) 2015年 haranicle. All rights reserved.
//
import UIKit
import Realm
let PluginCellReuseIdentifier = "Cell"
enum Modes:Int {
case Popularity = 0
case Stars = 1
case Update = 2
case New = 3
func toIcon() -> String {
switch self {
case Modes.Popularity: return "\u{f004}"
case Modes.Stars: return "\u{f005}"
case Modes.Update: return "\u{f021}"
case Modes.New: return "\u{f135}"
default: return ""
}
}
func toString() -> String {
switch self {
case Modes.Popularity: return "Popularity"
case Modes.Stars: return "Stars"
case Modes.Update: return "Update"
case Modes.New: return "New"
default: return ""
}
}
func propertyName() -> String {
switch self {
case Modes.Popularity: return "score"
case Modes.Stars: return "starGazersCount"
case Modes.Update: return "updatedAt"
case Modes.New: return "createdAt"
default: return ""
}
}
}
class PluginTableViewController: UITableViewController, UISearchResultsUpdating, UISearchControllerDelegate {
@IBOutlet weak var settingsButton: UIBarButtonItem!
var githubClient = GithubClient()
var currentMode = Modes.Popularity
let segments = [Modes.Popularity, Modes.Stars, Modes.Update, Modes.New]
override func viewDidLoad() {
super.viewDidLoad()
registerTableViewCellNib(self.tableView)
// settings button
let settingsAttributes = [NSFontAttributeName:UIFont(name: "FontAwesome", size: 24)!]
settingsButton.setTitleTextAttributes(settingsAttributes, forState: UIControlState.Normal)
settingsButton.title = "\u{f013}"
// notification center
NSNotificationCenter.defaultCenter().addObserver(self, selector: "onApplicationDidBecomeActive:", name: UIApplicationDidBecomeActiveNotification, object: nil)
// segmented control
let attributes = [NSFontAttributeName:UIFont(name: "FontAwesome", size: 10)!]
segmentedControl.setTitleTextAttributes(attributes, forState: UIControlState.Normal)
// search controller
configureSearchController()
// hide search bar
if githubClient.isSignedIn() {
tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0), atScrollPosition: UITableViewScrollPosition.Top, animated: false)
}
for i in 0 ..< segments.count {
let mode = segments[i]
segmentedControl.setTitle("\(mode.toIcon()) \(mode.toString())", forSegmentAtIndex: i)
}
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
override func viewWillAppear(animated: Bool) {
navigationController?.toolbarHidden = true
}
func onApplicationDidBecomeActive(notification:NSNotification) {
if !githubClient.isSignedIn() {
showSignInAlert()
}
}
// MARK: - Search Controller
let searchResultTableViewController = UITableViewController()
var searchController:UISearchController?
func configureSearchController() {
searchController = UISearchController(searchResultsController: searchResultTableViewController)
searchController!.searchResultsUpdater = self
searchController!.delegate = self
searchController!.searchBar.sizeToFit()
tableView.tableHeaderView = searchController!.searchBar
searchResultTableViewController.tableView.delegate = self
searchResultTableViewController.tableView.dataSource = self
registerTableViewCellNib(searchResultTableViewController.tableView)
searchResultTableViewController.tableView.tableHeaderView = nil
// https://developer.apple.com/library/ios/samplecode/TableSearch_UISearchController/Introduction/Intro.html
// Search is now just presenting a view controller. As such, normal view controller
// presentation semantics apply. Namely that presentation will walk up the view controller
// hierarchy until it finds the root view controller or one that defines a presentation context.
definesPresentationContext = true // know where you want UISearchController to be displayed
}
// MARK: - UISearchResultsUpdating
func updateSearchResultsForSearchController(searchController: UISearchController) {
let searchText = searchController.searchBar.text
// TODO: Must be tested here!!
searchResults = Plugin.objectsWhere("name contains[c] '\(searchText)' OR note contains[c] '\(searchText)'").sortedResultsUsingProperty(currentMode.propertyName(), ascending: false)
searchResultTableViewController.tableView.reloadData()
}
// MARK: - Realm
var searchResults:RLMResults?
var popularityResults = Plugin.allObjects().sortedResultsUsingProperty(Modes.Popularity.propertyName(), ascending: false)
var starsResults = Plugin.allObjects().sortedResultsUsingProperty(Modes.Stars.propertyName(), ascending: false)
var updateResults = Plugin.allObjects().sortedResultsUsingProperty(Modes.Update.propertyName(), ascending: false)
var newResults = Plugin.allObjects().sortedResultsUsingProperty(Modes.New.propertyName(), ascending: false)
func currentResult()->RLMResults {
if searchController!.active {
return searchResults!
}
switch currentMode {
case Modes.Popularity: return popularityResults
case Modes.Stars: return starsResults
case Modes.Update: return updateResults
case Modes.New: return newResults
}
}
// MARK: - UI Parts
@IBOutlet weak var segmentedControl: UISegmentedControl!
// MARK: - Action
@IBAction func onSegmentChanged(sender: UISegmentedControl) {
currentMode = Modes(rawValue: sender.selectedSegmentIndex)!
tableView.reloadData()
tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0), atScrollPosition: UITableViewScrollPosition.Top, animated: false)
}
@IBAction func onRefreshPushed(sender: AnyObject) {
if !githubClient.isSignedIn() {
showSignInAlert()
return
}
if !tableView.decelerating {
self.reloadAllPlugins()
}
}
// MARK: - Sign in
var signInAlert:UIAlertController?
func showSignInAlert() {
signInAlert = UIAlertController(title: "Sign in", message: "Please, sign in github to get repository data.", preferredStyle: UIAlertControllerStyle.Alert)
signInAlert!.addAction(UIAlertAction(title: "Sign in", style: UIAlertActionStyle.Default,
handler: {[weak self] action in
self?.signIn()
self?.signInAlert?.dismissViewControllerAnimated(true, completion: nil)
}))
presentViewController(signInAlert!, animated: true, completion: nil)
}
func signIn() {
githubClient.requestOAuth({[weak self] in
self?.signInAlert?.dismissViewControllerAnimated(true, completion: nil)
self?.reloadAllPlugins()
}, onFailed: {[weak self] error in
// login failed. quit app.
let errorAlert = UIAlertController(title: "Error", message: error.description, preferredStyle: UIAlertControllerStyle.Alert)
errorAlert.addAction(UIAlertAction(title: "Quit app", style: UIAlertActionStyle.Default, handler:{action in exit(0)} ))
self?.presentViewController(errorAlert, animated: true, completion: nil)
})
}
// MARK: - Reload data
func reloadAllPlugins() {
autoreleasepool{
self.githubClient.reloadAllPlugins({[weak self] (error:NSError?) in
if let err = error {
self?.showErrorAlert(err)
}
self?.tableView.reloadData()
})
}
}
// MARK: - Table View Data Source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return Int(currentResult().count)
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let plugin = currentResult()[UInt(indexPath.row)] as! Plugin
let cell = tableView.dequeueReusableCellWithIdentifier(PluginCellReuseIdentifier) as! PluginTableViewCell
configureCell(cell, plugin: plugin, indexPath: indexPath)
return cell
}
// MARK: - TableView Delegate
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let selectedPlugin = currentResult()[UInt(indexPath.row)] as! Plugin
let webViewController = PluginDetailWebViewController(plugin: selectedPlugin)
navigationController?.pushViewController(webViewController, animated: true)
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 80
}
// MARK: - UISearchControllerDelegate
func didDismissSearchController(searchController: UISearchController) {
tableView.reloadData()
}
// MARK: - Cell
func configureCell(cell:PluginTableViewCell, plugin:Plugin, indexPath:NSIndexPath) {
cell.rankingLabel.text = "\(indexPath.row + 1)"
cell.titleLabel.text = plugin.name
cell.noteLabel.text = plugin.note
cell.avaterImageView.sd_setImageWithURL(NSURL(string: plugin.avaterUrl))
cell.statusLabel.text = "\(Modes.Popularity.toIcon()) \(plugin.scoreAsString()) \(Modes.Stars.toIcon()) \(plugin.starGazersCount) \(Modes.Update.toIcon()) \(plugin.updatedAtAsString()) \(Modes.New.toIcon()) \(plugin.createdAtAsString())"
}
func registerTableViewCellNib(tableView:UITableView) {
let nib = UINib(nibName: "PluginTableViewCell", bundle: nil)
tableView.registerNib(nib, forCellReuseIdentifier: PluginCellReuseIdentifier)
}
// MARK: - Error
func showErrorAlert(error:NSError) {
let alert = UIAlertController(title: "Error", message: error.description, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
// MARK: - Segue
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "settings" {
let settingsNavigationController = segue.destinationViewController as! UINavigationController
let settingTableViewController = settingsNavigationController.childViewControllers[0] as! SettingsTableViewController
settingTableViewController.githubClient = githubClient
}
}
} | 56b7dc6d2209efe98e97fb2a763440fa | 38.197917 | 245 | 0.670712 | false | false | false | false |
JonahStarling/GlanceiOS | refs/heads/master | Glance/Friend.swift | mit | 1 | //
// Friend.swift
// Glance
//
// Created by Jonah Starling on 4/14/16.
// Copyright © 2016 In The Belly. All rights reserved.
//
import Foundation
class Friend {
var friendType: String
var userName: String
var userId: String
var userHandle: String
var userPic: String
// Default Initializer
init() {
self.friendType = ""
self.userName = "User"
self.userId = ""
self.userHandle = "@User"
self.userPic = ""
}
// Full Initializer
init(friendType: String, userName: String, userId: String, userHandle: String, userPic: String) {
self.friendType = friendType
if (userName == "") {
self.userName = userHandle
} else {
self.userName = userName
}
self.userId = userId
self.userHandle = "@"+userHandle
self.userPic = userPic
}
// Get Functions
func getFriendType() -> String { return self.friendType }
func getUserName() -> String { return self.userName }
func getUserId() -> String { return self.userId }
func getUserHandle() -> String { return self.userHandle }
func getUserPic() -> String { return self.userPic }
// Set Functions
func setFriendType(friendType: String) { self.friendType = friendType }
func setUserName(userName: String) { self.userName = userName }
func setUserId(userId: String) { self.userId = userId }
func setUserHandle(userHandle: String) { self.userHandle = userHandle }
func setUserPic(userPic: String) { self.userPic = userPic }
} | 034f4d01a8969358391f85c7abdfc87e | 29 | 101 | 0.621775 | false | false | false | false |
dongdongSwift/guoke | refs/heads/master | gouke/果壳/Protocol.swift | mit | 1 | //
// Protocol.swift
// 果壳
//
// Created by qianfeng on 2016/10/25.
// Copyright © 2016年 张冬. All rights reserved.
//
import UIKit
import MJRefresh
enum BarButtonPosition {
case left
case right
}
protocol addRefreshProtocol:NSObjectProtocol {
func addRefresh(header:(()->())?,footer:(()->())?)
}
protocol NavigationProtocol:NSObjectProtocol {
func addTitle(title:String)
func addBarButton(title:String?,imageName:String?,bgImageName:String?,postion:BarButtonPosition,select:Selector)
}
extension addRefreshProtocol where Self:UITableViewController{
func addRefresh(header:(()->())?=nil,footer:(()->())?=nil){
if header != nil{
tableView.mj_header=MJRefreshNormalHeader(refreshingBlock: header)
}
if footer != nil{
tableView.mj_footer=MJRefreshAutoNormalFooter(refreshingBlock: footer)
}
}
}
extension NavigationProtocol where Self:UIViewController{
func addTitle(title:String){
let label=UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 44))
label.text=title
label.font=UIFont.boldSystemFontOfSize(20)
label.textColor=UIColor.whiteColor()
label.textAlignment = .Center
navigationItem.titleView=label
}
func addBarButton(title:String?=nil,imageName:String?=nil,bgImageName:String?=nil,postion:BarButtonPosition,select:Selector){
let button=UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 44))
if title != nil{
button.setTitle(title, forState: .Normal)
}
if imageName != nil {
button.setImage(UIImage(named: imageName!), forState: .Normal)
}
if bgImageName != nil{
button.setBackgroundImage(UIImage(named:bgImageName!) , forState: .Normal)
}
button.setTitleColor(UIColor.blackColor(), forState: .Normal)
button.setTitleColor(UIColor.grayColor(), forState: .Highlighted)
button.addTarget(self, action: select, forControlEvents: .TouchUpInside)
let barButtonItem=UIBarButtonItem(customView: button)
if postion == .left {
if navigationItem.leftBarButtonItems != nil{
navigationItem.leftBarButtonItems=navigationItem.leftBarButtonItems!+[barButtonItem]
}else{
navigationItem.leftBarButtonItems=[barButtonItem]
}
}else{
if navigationItem.rightBarButtonItems != nil{
navigationItem.rightBarButtonItems=navigationItem.rightBarButtonItems!+[barButtonItem]
}else{
navigationItem.rightBarButtonItems=[barButtonItem]
}
}
}
}
| a3e2790d40ea7ba4ce18d9817eefab74 | 34.328947 | 129 | 0.652142 | false | false | false | false |
zjjzmw1/SwiftCodeFragments | refs/heads/master | SwiftCodeFragments/AnimationResource/TransitionFirstPushViewController.swift | mit | 1 | //
// TransitionFirstPushViewController.swift
// SwiftCodeFragments
//
// Created by zhangmingwei on 2017/2/6.
// Copyright © 2017年 SpeedX. All rights reserved.
// 转场动画最简单的方法 第一页 push方式
import UIKit
class TransitionFirstPushViewController: UIViewController,UIViewControllerTransitioningDelegate,UINavigationControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.lightGray
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.pushAction()
}
// 转场动画开始
func pushAction() -> Void {
let vc = TransitionSecondPushViewController()
self.navigationController?.delegate = self
self.navigationController?.pushViewController(vc, animated: true)
}
// push 动画
func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
switch operation {
case .pop:
let animation = TransitionAnimation()
animation.isIn = false
return animation
case .push:
let animation = TransitionAnimation()
animation.isIn = true
return animation
default:
return nil
}
}
}
| 4bbfe4eadcddf9859eea0cc32f51650e | 31.170213 | 246 | 0.640873 | false | false | false | false |
Vostro162/VaporTelegram | refs/heads/master | Sources/App/MethodsAble.swift | mit | 1 | import Foundation
/*
*
* The Bot API supports basic formatting for messages. You can use bold and italic text, as well as inline links and pre-formatted code in your bots' messages.
* Telegram clients will render them accordingly. You can use either markdown-style or HTML-style formatting.
*
*/
public enum ParseMode: String {
case markdown = "markdown"
case html = "html"
}
/*
* Type of action to broadcast. Choose one, depending on what the user is about to receive:
* typing for text messages, upload_photo for photos, record_video or upload_video for videos, record_audio or upload_audio for audio files, upload_document for general files,
* find_location for location data, record_video_note or upload_video_note for video notes.
*
*/
public enum ChatAction: String {
case typing = "typing"
case uploadPhoto = "upload_photo"
case recordVideo = "record_video"
case uploadVideo = "upload_video"
case recordAudio = "record_audio"
case uploadAudio = "upload_audio"
case uploadDocument = "upload_document"
case findLocation = "find_location"
}
public protocol MethodsAble {
//func setWebhook(url: URL, certificate: InputFile, maxConnections: Int, )
/*
*
* -------------------------------------------------- Send --------------------------------------------------
*
*/
// Use this method to send text messages. On success, the sent Message is returned.
func sendMessage(chatId: ChatId, text: String, disableWebPagePreview: Bool, disableNotification: Bool, parseMode: ParseMode?, replyToMessageId: MessageId?, replyMarkup: ReplyMarkup?) throws -> Message
// Use this method to send photos. On success, the sent Message is returned.
func sendPhoto(chatId: ChatId, photo: InputFile, fileName: String, disableNotification: Bool, caption: String?, replyToMessageId: MessageId?, replyMarkup: ReplyMarkup?) throws -> Message
func sendPhoto(chatId: ChatId, photo: URL, disableNotification: Bool, caption: String?, replyToMessageId: MessageId?, replyMarkup: ReplyMarkup?) throws -> Message
/*
* Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .mp3 format.
* On success, the sent Message is returned. Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future.
* For sending voice messages, use the sendVoice method instead.
*/
func sendAudio(chatId: ChatId, audio: InputFile, fileName: String, disableNotification: Bool, caption: String?, duration: Int?, performer: String?, title: String?, replyToMessageId: MessageId?, replyMarkup: ReplyMarkup?) throws -> Message
func sendAudio(chatId: ChatId, audio: URL, disableNotification: Bool, caption: String?, duration: Int?, performer: String?, title: String?, replyToMessageId: MessageId?, replyMarkup: ReplyMarkup?) throws -> Message
// Use this method to send general files. On success, the sent Message is returned. Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future.
func sendDocument(chatId: ChatId, document: InputFile, fileName: String, disableNotification: Bool, caption: String?, replyToMessageId: MessageId?, replyMarkup: ReplyMarkup?) throws -> Message
func sendDocument(chatId: ChatId, document: URL, disableNotification: Bool, caption: String?, replyToMessageId: MessageId?, replyMarkup: ReplyMarkup?) throws -> Message
// Use this method to send .webp stickers. On success, the sent Message is returned
func sendSticker(chatId: ChatId, sticker: InputFile, fileName: String, disableNotification: Bool, replyToMessageId: MessageId?, replyMarkup: ReplyMarkup?) throws -> Message
func sendSticker(chatId: ChatId, sticker: URL, disableNotification: Bool, replyToMessageId: MessageId?, replyMarkup: ReplyMarkup?) throws -> Message
/*
* Use this method to send video files, Telegram clients support mp4 videos (other formats may be sent as Document).
* On success, the sent Message is returned. Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future.
*
*/
func sendVideo(chatId: ChatId, video: InputFile, fileName: String, disableNotification: Bool, replyToMessageId: MessageId?, duration: Int?, width: Int?, height: Int?, caption: String?, replyMarkup: ReplyMarkup?) throws -> Message
func sendVideo(chatId: ChatId, video: URL, disableNotification: Bool, replyToMessageId: MessageId?, duration: Int?, width: Int?, height: Int?, caption: String?, replyMarkup: ReplyMarkup?) throws -> Message
/*
* Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message.
* For this to work, your audio must be in an .ogg file encoded with OPUS (other formats may be sent as Audio or Document).
* On success, the sent Message is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future.
*
*/
func sendVoice(chatId: ChatId, voice: InputFile, fileName: String, disableNotification: Bool, caption: String?, duration: Int?, replyToMessageId: MessageId?, replyMarkup: ReplyMarkup?) throws -> Message
func sendVoice(chatId: ChatId, voice: URL, disableNotification: Bool, caption: String?, duration: Int?, replyToMessageId: MessageId?, replyMarkup: ReplyMarkup?) throws -> Message
// Use this method to send point on the map. On success, the sent Message is returned.
func sendLocation(chatId: ChatId, latitude: Float, longitude: Float, disableNotification: Bool, replyToMessageId: MessageId?, replyMarkup: ReplyMarkup?) throws -> Message
// Use this method to send information about a venue. On success, the sent Message is returned.
func sendVenue(chatId: ChatId, latitude: Float, longitude: Float, title: String, address: String, disableNotification: Bool, foursquareId: FoursquareId?, replyToMessageId: MessageId?, replyMarkup: ReplyMarkup?) throws -> Message
// Use this method to send phone contacts. On success, the sent Message is returned.
func sendContact(chatId: ChatId, phoneNumber: String, firstName: String, lastName: String, disableNotification: Bool, replyToMessageId: MessageId?, replyMarkup: ReplyMarkup?) throws -> Message
/*
* Use this method when you need to tell the user that something is happening on the bot's side.
* The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status). Returns True on success.
*
* Example:
* The ImageBot needs some time to process a request and upload the image. Instead of sending a text message along the lines of “Retrieving image, please wait…”,
* the bot may use sendChatAction with action = upload_photo.
* The user will see a “sending photo” status for the bot.
*
*/
func sendChatAction(chatId: ChatId, action: ChatAction) throws -> Bool
/*
*
* -------------------------------------------------- Get--------------------------------------------------
*
*/
// A simple method for testing your bot's auth token. Requires no parameters. Returns basic information about the bot in form of a User object.
func getMe() throws -> User
// Use this method to get a list of profile pictures for a user. Returns a UserProfilePhotos object.
func getUserProfilePhotos(userId: UserId, offset: Int, limit: Int) throws -> UserProfilePhotos
/*
* Use this method to get basic info about a file and prepare it for downloading. For the moment, bots can download files of up to 20MB in size.
* On success, a File object is returned. The file can then be downloaded via the link https://api.telegram.org/file/bot<token>/<file_path>, where <file_path> is taken from the response.
* It is guaranteed that the link will be valid for at least 1 hour. When the link expires, a new one can be requested by calling getFile again.
*
* Note: This function may not preserve the original file name and MIME type. You should save the file's MIME type and name (if available) when the File object is received.
*/
func getFile(fileId: FileId) throws -> File
/*
*
* Use this method to get up to date information about the chat (current name of the user for one-on-one conversations, current username of a user, group or channel, etc.).
* Returns a Chat object on success.
*
*/
func getChat(chatId: ChatId) throws -> Chat
/*
*
* Use this method to get a list of administrators in a chat. On success, returns an Array of ChatMember objects that contains information about all chat administrators except other bots.
* If the chat is a group or a supergroup and no administrators were appointed, only the creator will be returned.
*
*/
func getChatAdministrators(chatId: ChatId) throws -> [ChatMember]
// Use this method to get the number of members in a chat. Returns Int on success.
func getChatMembersCount(chatId: ChatId) throws -> Int
// Use this method to get information about a member of a chat. Returns a ChatMember object on success.
func getChatMember(chatId: ChatId, userId: UserId) throws -> ChatMember
/*
*
* -------------------------------------------------- Manage --------------------------------------------------
*
*/
/*
*
* Use this method to kick a user from a group, a supergroup or a channel.
* In the case of supergroups and channels, the user will not be able to return to the group on their own using invite links, etc. ,
* unless unbanned first. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success.
*
*/
func kickChatMember(chatId: ChatId, userId: UserId) throws -> Bool
// Use this method to forward messages of any kind. On success, the sent Message is returned.
func forwardMessage(chatId: ChatId, fromChatId: ChatId, messageId: MessageId, disableNotification: Bool) throws -> Message
// Use this method for your bot to leave a group, supergroup or channel. Returns True on success.
func leaveChat(chatId: ChatId, userId: UserId) throws -> Bool
/*
*
* Use this method to unban a previously kicked user in a supergroup or channel.
* The user will not return to the group or channel automatically, but will be able to join via link, etc. The bot must be an administrator for this to work. Returns True on success.
*
*/
func unbanChatMember(chatId: ChatId, userId: UserId) throws -> Bool
/*
*
* Use this method to send answers to callback queries sent from inline keyboards.
* The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. On success, True is returned.
*
* Alternatively, the user can be redirected to the specified Game URL.
* For this option to work, you must first create a game for your bot via @Botfather and accept the terms.
* Otherwise, you may use links like t.me/your_bot?start=XXXX that open your bot with a parameter.
*
*/
func answerCallbackQuery(callbackQueryId: CallbackQueryId, showAlert: Bool, text: String?, url: URL?, cacheTime: Int?) throws -> Bool
/*
*
* -------------------------------------------------- Edit --------------------------------------------------
*
*/
/*
* Use this method to edit text and game messages sent by the bot or via the bot (for inline bots).
* On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.
*
*/
func editMessageText(chatId: ChatId, messageId: MessageId, text: String, disableWebPagePreview: Bool, parseMode: ParseMode?, replyMarkup: ReplyMarkup?) throws -> Message
func editMessageText(inlineMessageId: InlineMessageId, text: String, disableWebPagePreview: Bool, parseMode: ParseMode?, replyMarkup: ReplyMarkup?) throws -> Message
/*
* Use this method to edit captions of messages sent by the bot or via the bot (for inline bots).
* On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.
*
*/
func editMessageCaption(chatId: ChatId, messageId: MessageId, caption: String, replyMarkup: ReplyMarkup?) throws -> Message
func editMessageCaption(inlineMessageId: InlineMessageId, caption: String, replyMarkup: ReplyMarkup?) throws -> Message
/*
* Use this method to edit only the reply markup of messages sent by the bot or via the bot (for inline bots).
* On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.
*
*/
func editMessageReplyMarkup(chatId: ChatId, messageId: MessageId, replyMarkup: ReplyMarkup?) throws -> Message
func editMessageReplyMarkup(inlineMessageId: InlineMessageId, replyMarkup: ReplyMarkup?) throws -> Message
/*
*
* Use this method to delete a message, including service messages, with the following limitations:
* - A message can only be deleted if it was sent less than 48 hours ago.
* - Bots can delete outgoing messages in groups and supergroups.
* - Bots granted can_post_messages permissions can delete outgoing messages in channels.
* - If the bot is an administrator of a group, it can delete any message there.
* - If the bot has can_delete_messages permission in a supergroup or a channel, it can delete any message there.
* Returns True on success.
*
*/
func deleteMessage(chatId: ChatId, messageId: MessageId) throws -> Bool
/*
*
* -------------------------------------------------- Inline --------------------------------------------------
*
*/
func inlineQuery(id: String, from: User, query: String, offset: String, location: Location?) throws -> Bool
//func answerInlineQuery(inlineQueryId: String, results:
}
| b6e9c2ebfc66b285bd0b800e07f32b0e | 56.491935 | 242 | 0.687754 | false | false | false | false |
fespinoza/linked-ideas-osx | refs/heads/master | Playground-macOS.playground/Pages/Hello World.xcplaygroundpage/Contents.swift | mit | 1 | import Cocoa
NSImage.init(contentsOfFile: "tutorial-00.jpg")
//NSImage.init(byReferencingFile: "tutorial-00")
// images on macos
let fileURL = Bundle.main.url(forResource: "tutorial-00", withExtension: "jpg")
let image = NSImage.init(contentsOf: fileURL!)
let imageView = NSImageView(frame: CGRect(x: 0, y: 0, width: 800, height: 600))
imageView.image = image
imageView.frame
import PlaygroundSupport
PlaygroundPage.current.liveView = imageView
| fd8d91d41bd7f6cd21803cf7fee2137f | 24.111111 | 79 | 0.763274 | false | false | false | false |
kaishin/ImageScout | refs/heads/master | Tests/ImageScoutTests/ScoutTests.swift | mit | 1 | import XCTest
import ImageScout
private final class BundleToken {}
private let expectationTimeOut: TimeInterval = 5
class ImageScoutTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func url(forResource name: String, extension ext: String) -> URL {
let bundle = Bundle(for: BundleToken.self)
return bundle.url(forResource: name, withExtension: ext)!
}
func testScoutingJPEG() {
let scout = ImageScout()
let expectation = self.expectation(description: "Scout JPEG images")
let imagePath = url(forResource: "scout", extension: "jpg")
scout.scoutImage(atURL: imagePath) { (error, size, type) -> () in
expectation.fulfill()
XCTAssertEqual(size, CGSize(width: 500, height: 375), "Image size should be 500 by 375")
XCTAssertEqual(type, ScoutedImageType.jpeg, "Image type should be JPEG")
XCTAssertNil(error, "Error should be nil")
}
waitForExpectations(timeout: expectationTimeOut, handler: .none)
}
func testScoutingPNG() {
let scout = ImageScout()
let expectation = self.expectation(description: "Scount PNG images")
let imagePath = url(forResource: "scout", extension: "png")
scout.scoutImage(atURL: imagePath) { (error, size, type) -> () in
expectation.fulfill()
XCTAssertEqual(size, CGSize(width: 500, height: 375), "Image size should be 500 by 375")
XCTAssertEqual(type, ScoutedImageType.png, "Image type should be PNG")
XCTAssertNil(error, "Error should be nil")
}
waitForExpectations(timeout: expectationTimeOut, handler: .none)
}
func testScoutingGIF() {
let scout = ImageScout()
let expectation = self.expectation(description: "Scout GIF images")
let imagePath = url(forResource: "scout", extension: "gif")
scout.scoutImage(atURL: imagePath) { (error, size, type) -> () in
expectation.fulfill()
XCTAssertEqual(size, CGSize(width: 500, height: 375), "Image size should be 500 by 375")
XCTAssertEqual(type, ScoutedImageType.gif, "Image type should be GIF")
XCTAssertNil(error, "Error should be nil")
}
waitForExpectations(timeout: expectationTimeOut, handler: nil)
}
func testScoutingUnsupported() {
let scout = ImageScout()
let expectation = self.expectation(description: "Ignore unsupported formats")
let imagePath = url(forResource: "scout", extension: "bmp")
scout.scoutImage(atURL: imagePath) { (error, size, type) -> () in
expectation.fulfill()
XCTAssertEqual(size, CGSize.zero, "Image size should be 0 by 0")
XCTAssertEqual(type, ScoutedImageType.unsupported ,"Image type should be Unsupported")
XCTAssertNotNil(error, "Error should not be nil")
XCTAssertEqual(error!.code, 102, "Error should describe failure reason")
}
waitForExpectations(timeout: expectationTimeOut, handler: nil)
}
}
| 391c645ef72e1f1e190aa9198c31329b | 34.609756 | 94 | 0.694178 | false | true | false | false |
madhusamuel/PlacesExplorer | refs/heads/master | PlacesExplorer/Networking/URLConstructor.swift | epl-1.0 | 1 | //
// URLConstructor.swift
// PlacesExplorer
//
// Created by Madhu Samuel on 5/11/2015.
// Copyright © 2015 Madhu. All rights reserved.
//
import Foundation
class URLConstructor {
var endPoint: String!
var webservice: String!
var clientId: String!
var clientSecret: String!
var dataURLString: String!
//Example: https://api.foursquare.com/v2/venues/search?client_id=45OD3KD2OAX3IDGYPJ3FVXQX5VYIGWV5JDQGM1MDBGJEWFJF&client_secret=E3G1JPJWTJF4XISJA5C5DYVKQLEXSOQGBLPWPLADBZFBTO2R&v=20130815&ll=-37.8136,144.9631
var urlString: String {
get {
var interURLString = endPoint + webservice
if let localClientId = clientId {
interURLString = interURLString + "?" + "client_id=" + localClientId + "&" + "client_secret=" + clientSecret
}
if let localDataURLString = dataURLString {
if let localClientId = clientId {
interURLString = interURLString + "&" + dataURLString
} else {
interURLString = interURLString + "?" + dataURLString
}
}
return interURLString
}
}
var url: NSURL {
get {
return NSURL(string: urlString)!
}
}
} | a6956c01855afcaf0a32b67e9c63ecf1 | 27.723404 | 212 | 0.573017 | false | false | false | false |
zyuanming/EffectDesignerX | refs/heads/master | EffectDesignerX/Model/BindingModel.swift | mit | 1 | //
// BindingEmitterCellModel.swift
// EffectDesignerX
//
// Created by Zhang Yuanming on 11/30/16.
// Copyright © 2016 Zhang Yuanming. All rights reserved.
//
import Foundation
class BindingModel: NSObject {
dynamic var emitterShape: String = ""
dynamic var emitterMode: String = ""
dynamic var renderMode: String = ""
dynamic var preservesDepth: CGFloat = 0
dynamic var width: CGFloat = 0
dynamic var height: CGFloat = 0
dynamic var birthRate: CGFloat = 0
dynamic var lifetime: CGFloat = 0
dynamic var lifetimeRange: CGFloat = 0
dynamic var velocity: CGFloat = 0
dynamic var velocityRange: CGFloat = 0
dynamic var emissionLatitude: CGFloat = 0
dynamic var emissionLongitude: CGFloat = 0
dynamic var emissionRange: CGFloat = 0
dynamic var xAcceleration: CGFloat = 0
dynamic var yAcceleration: CGFloat = 0
dynamic var zAcceleration: CGFloat = 0
dynamic var contents: String = ""
dynamic var contentsRect: String = ""
dynamic var name: String = ""
dynamic var color: NSColor = NSColor.white
dynamic var redRange: CGFloat = 0
dynamic var redSpeed: CGFloat = 0
dynamic var greenRange: CGFloat = 0
dynamic var greenSpeed: CGFloat = 0
dynamic var blueRange: CGFloat = 0
dynamic var blueSpeed: CGFloat = 0
dynamic var alpha: CGFloat = 0
dynamic var alphaRange: CGFloat = 0
dynamic var alphaSpeed: CGFloat = 0
dynamic var scale: CGFloat = 0
dynamic var scaleRange: CGFloat = 0
dynamic var scaleSpeed: CGFloat = 0
dynamic var spin: CGFloat = 0
dynamic var spinRange: CGFloat = 0
dynamic var contentsImage: NSImage?
func update(from effectModel: EmitterCellModel) {
self.birthRate = effectModel.birthRate
self.lifetime = effectModel.lifetime
self.lifetimeRange = effectModel.lifetimeRange
self.velocity = effectModel.velocity
self.velocityRange = effectModel.velocityRange
self.emissionRange = effectModel.emissionRange
self.emissionLongitude = effectModel.emissionLongitude
self.emissionLatitude = effectModel.emissionLatitude
self.xAcceleration = effectModel.xAcceleration
self.yAcceleration = effectModel.yAcceleration
self.zAcceleration = effectModel.zAcceleration
self.contents = effectModel.contents
self.contentsRect = effectModel.contentsRect
self.name = effectModel.name
self.color = effectModel.color
self.redRange = effectModel.redRange
self.redSpeed = effectModel.redSpeed
self.greenRange = effectModel.greenRange
self.greenSpeed = effectModel.greenSpeed
self.blueRange = effectModel.blueRange
self.blueSpeed = effectModel.blueSpeed
self.alpha = effectModel.alpha
self.alphaRange = effectModel.alphaRange
self.alphaSpeed = effectModel.alphaSpeed
self.scale = effectModel.scale
self.scaleRange = effectModel.scaleRange
self.scaleSpeed = effectModel.scaleSpeed
self.spin = effectModel.spin
self.spinRange = effectModel.spinRange
self.contentsImage = effectModel.contentsImage
}
func allPropertyNames() -> [String] {
return Mirror(reflecting: self).children.flatMap({ $0.label })
}
}
| f06d31d16590eae27765a0e6140e5934 | 36.954023 | 70 | 0.699576 | false | false | false | false |
ianyh/Highball | refs/heads/master | Highball/AccountsService.swift | mit | 1 | //
// AccountsService.swift
// Highball
//
// Created by Ian Ynda-Hummel on 12/16/14.
// Copyright (c) 2014 ianynda. All rights reserved.
//
import OAuthSwift
import RealmSwift
import SwiftyJSON
import TMTumblrSDK
import UIKit
public struct AccountsService {
private static let lastAccountNameKey = "HILastAccountKey"
public private(set) static var account: Account!
public static func accounts() -> [Account] {
guard let realm = try? Realm() else {
return []
}
return realm.objects(AccountObject).map { $0 }
}
public static func lastAccount() -> Account? {
let userDefaults = NSUserDefaults.standardUserDefaults()
guard let accountName = userDefaults.stringForKey(lastAccountNameKey) else {
return nil
}
guard let realm = try? Realm() else {
return nil
}
guard let account = realm.objectForPrimaryKey(AccountObject.self, key: accountName) else {
return nil
}
return account
}
public static func start(fromViewController viewController: UIViewController, completion: (Account) -> ()) {
if let lastAccount = lastAccount() {
loginToAccount(lastAccount, completion: completion)
return
}
guard let firstAccount = accounts().first else {
authenticateNewAccount(fromViewController: viewController) { account in
if let account = account {
self.loginToAccount(account, completion: completion)
} else {
self.start(fromViewController: viewController, completion: completion)
}
}
return
}
loginToAccount(firstAccount, completion: completion)
}
public static func loginToAccount(account: Account, completion: (Account) -> ()) {
self.account = account
TMAPIClient.sharedInstance().OAuthToken = account.token
TMAPIClient.sharedInstance().OAuthTokenSecret = account.tokenSecret
dispatch_async(dispatch_get_main_queue()) {
completion(account)
}
}
public static func authenticateNewAccount(fromViewController viewController: UIViewController, completion: (account: Account?) -> ()) {
let oauth = OAuth1Swift(
consumerKey: TMAPIClient.sharedInstance().OAuthConsumerKey,
consumerSecret: TMAPIClient.sharedInstance().OAuthConsumerSecret,
requestTokenUrl: "https://www.tumblr.com/oauth/request_token",
authorizeUrl: "https://www.tumblr.com/oauth/authorize",
accessTokenUrl: "https://www.tumblr.com/oauth/access_token"
)
let currentAccount: Account? = account
account = nil
TMAPIClient.sharedInstance().OAuthToken = nil
TMAPIClient.sharedInstance().OAuthTokenSecret = nil
oauth.authorize_url_handler = SafariURLHandler(viewController: viewController)
oauth.authorizeWithCallbackURL(
NSURL(string: "highball://oauth-callback")!,
success: { (credential, response, parameters) in
TMAPIClient.sharedInstance().OAuthToken = credential.oauth_token
TMAPIClient.sharedInstance().OAuthTokenSecret = credential.oauth_token_secret
TMAPIClient.sharedInstance().userInfo { response, error in
var account: Account?
defer {
completion(account: account)
}
if let error = error {
print(error)
return
}
let json = JSON(response)
guard let blogsJSON = json["user"]["blogs"].array else {
return
}
let blogs = blogsJSON.map { blogJSON -> UserBlogObject in
let blog = UserBlogObject()
blog.name = blogJSON["name"].stringValue
blog.url = blogJSON["url"].stringValue
blog.title = blogJSON["title"].stringValue
blog.isPrimary = blogJSON["primary"].boolValue
return blog
}
let accountObject = AccountObject()
accountObject.name = json["name"].stringValue
accountObject.token = TMAPIClient.sharedInstance().OAuthToken
accountObject.tokenSecret = TMAPIClient.sharedInstance().OAuthTokenSecret
accountObject.blogObjects.appendContentsOf(blogs)
guard let realm = try? Realm() else {
return
}
do {
try realm.write {
realm.add(accountObject, update: true)
}
} catch {
print(error)
return
}
account = accountObject
self.account = currentAccount
TMAPIClient.sharedInstance().OAuthToken = currentAccount?.token
TMAPIClient.sharedInstance().OAuthTokenSecret = currentAccount?.tokenSecret
}
},
failure: { (error) in
print(error)
}
)
}
public static func deleteAccount(account: Account, fromViewController viewController: UIViewController, completion: (changedAccount: Bool) -> ()) {
if self.account == account {
self.account = nil
start(fromViewController: viewController) { _ in
completion(changedAccount: true)
}
}
dispatch_async(dispatch_get_main_queue()) {
completion(changedAccount: false)
}
}
}
| fc928ec2b14e915c261a53ae4af0c429 | 26.16185 | 148 | 0.709087 | false | false | false | false |
drmohundro/Quick | refs/heads/master | Quick/QuickTests/FunctionalTests.swift | mit | 2 | //
// FunctionalTests.swift
// QuickTests
//
// Created by Brian Ivan Gesiak on 6/5/14.
// Copyright (c) 2014 Brian Ivan Gesiak. All rights reserved.
//
import Quick
import Nimble
var dinosaursExtinct = false
var mankindExtinct = false
class FunctionalSharedExamples: QuickSharedExampleGroups {
override class func sharedExampleGroups() {
sharedExamples("something living after dinosaurs are extinct") {
it("no longer deals with dinosaurs") {
expect(dinosaursExtinct).to(beTruthy())
}
}
sharedExamples("an optimistic person") { (sharedExampleContext: SharedExampleContext) in
var person: Person!
beforeEach {
person = sharedExampleContext()["person"] as Person
}
it("is happy") {
expect(person.isHappy).to(beTruthy())
}
it("is a dreamer") {
expect(person.hopes).to(contain("winning the lottery"))
}
}
}
}
class PersonSpec: QuickSpec {
override func spec() {
describe("Person") {
var person: Person! = nil
beforeSuite {
assert(!dinosaursExtinct, "nothing goes extinct twice")
dinosaursExtinct = true
}
afterSuite {
assert(!mankindExtinct, "tests shouldn't run after the apocalypse")
mankindExtinct = true
}
beforeEach { person = Person() }
afterEach { person = nil }
itBehavesLike("something living after dinosaurs are extinct")
itBehavesLike("an optimistic person") { ["person": person] }
it("gets hungry") {
person!.eatChineseFood()
expect{person.isHungry}.toEventually(beTruthy())
}
it("will never be satisfied") {
expect{person.isSatisfied}.toEventuallyNot(beTruthy())
}
it("🔥🔥それでも俺たちは🔥🔥") {
expect{person.isSatisfied}.toEventuallyNot(beTruthy())
}
pending("but one day") {
it("will never want for anything") {
expect{person.isSatisfied}.toEventually(beTruthy())
}
}
it("does not live with dinosaurs") {
expect(dinosaursExtinct).to(beTruthy())
expect(mankindExtinct).notTo(beTruthy())
}
describe("greeting") {
context("when the person is unhappy") {
beforeEach { person.isHappy = false }
it("is lukewarm") {
expect(person.greeting).to(equal("Oh, hi."))
expect(person.greeting).notTo(equal("Hello!"))
}
}
context("when the person is happy") {
beforeEach { person!.isHappy = true }
it("is enthusiastic") {
expect(person.greeting).to(equal("Hello!"))
expect(person.greeting).notTo(equal("Oh, hi."))
}
}
}
}
}
}
class PoetSpec: QuickSpec {
override func spec() {
describe("Poet") {
// FIXME: Radar worthy? `var poet: Poet?` results in build error:
// "Could not find member 'greeting'"
var poet: Person! = nil
beforeEach { poet = Poet() }
describe("greeting") {
context("when the poet is unhappy") {
beforeEach { poet.isHappy = false }
it("is dramatic") {
expect(poet.greeting).to(equal("Woe is me!"))
}
}
context("when the poet is happy") {
beforeEach { poet.isHappy = true }
it("is joyous") {
expect(poet.greeting).to(equal("Oh, joyous day!"))
}
}
}
}
}
}
| a0ed80ab3389e5ed029a767f5f319df8 | 30.282443 | 96 | 0.487555 | false | false | false | false |
imex94/KCLTech-iOS-2015 | refs/heads/master | session102/Challenge1.playground/Contents.swift | mit | 1 | //: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
// Naive Prime function
func naivePrime(number: Int) -> Bool {
for i in 2...Int(sqrt(Double(number))) {
if (number % i == 0) {
return false
}
}
return true
}
naivePrime(5)
// Extended Prime function
func isPrime(number: Int) -> Bool {
let until = sqrt(Double(number))
guard number >= 2 else {
return false
}
guard until >= 2 else {
return true
}
for i in 2...Int(until) {
if (number % i == 0) {
return false
}
}
return true
}
isPrime(2)
// Alternative Prime functin
func altPrime(number: Int) -> Bool {
switch number {
case let n where n < 2: return false
case 2, 3: return true
default: break
}
for i in 2...Int(sqrt(Double(number))) {
if (number % i == 0) {
return false
}
}
return true
}
altPrime(5)
| e247360f4d9d33aaccd4803110c90af3 | 14.716418 | 52 | 0.510921 | false | false | false | false |
nekrich/GlobalMessageService-iOS | refs/heads/master | Source/Core/CoreData/GMSInboxAlphaName+Extension.swift | apache-2.0 | 1 | //
// GMSInboxAlphaName+Extension.swift
// GlobalMessageService
//
// Created by Vitalii Budnik on 2/25/16.
// Copyright © 2016 Global Message Services Worldwide. All rights reserved.
//
import Foundation
import CoreData
extension GMSInboxAlphaName: NSManagedObjectSearchable {
// swiftlint:disable line_length
/**
Search and creates (if needed) `GMSInboxFetchedDate` object for passed date
- parameter alphaName: `String` with Alpha name
- parameter managedObjectContext: `NSManagedObjectContext` in what to search. (optional. Default value:
`GlobalMessageServiceCoreDataHelper.managedObjectContext`)
- returns: `self` if found, or successfully created, `nil` otherwise
*/
internal static func getInboxAlphaName(
alphaName name: String?,
inManagedObjectContext managedObjectContext: NSManagedObjectContext? = GlobalMessageServiceCoreDataHelper.managedObjectContext)
-> GMSInboxAlphaName? // swiftlint:disable:this opnening_brace
{
// swiftlint:enable line_length
let aplhaNameString = name ?? unknownAlphaNameString
let predicate = NSPredicate(format: "title == %@", aplhaNameString)
guard let aplhaName = GMSInboxAlphaName.findObject(
withPredicate: predicate,
inManagedObjectContext: managedObjectContext) as? GMSInboxAlphaName
else // swiftlint:disable:this opnening_brace
{
return .None
}
aplhaName.title = aplhaNameString
return aplhaName
}
/**
Unlocalized default string for unknown alpha-name in remote push-notification
*/
internal static var unknownAlphaNameString: String {
return "_UNKNOWN_ALPHA_NAME_"
}
}
| bec1d82212dfd4b1ac332e19d9d9fc20 | 30.54717 | 131 | 0.73445 | false | false | false | false |