repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
leannenorthrop/markdown-swift
|
Markdown/HtmlRenderer.swift
|
1
|
8652
|
//
// HtmlRenderer.swift
// Markdown
//
// Created by Leanne Northrop on 22/06/2015.
// Copyright (c) 2015 Leanne Northrop. All rights reserved.
//
import Foundation
public class HtmlRenderer: Renderer {
public override init() { super.init() }
public func toHTML(source : [AnyObject]) -> String {
var src : [AnyObject]? = source
var input = self.toHTMLTree(&src, preprocessTreeNode: nil)
return self.renderHTML(input, includeRoot: true)
}
public func toHTMLTree(input: String, dialectName : String, options : AnyObject) -> [AnyObject] {
let md = Markdown(dialectName: dialectName)
var result : [AnyObject]? = md.parse(input)
return self.toHTMLTree(&result, preprocessTreeNode: nil)
}
public func toHTMLTree(inout input : [AnyObject]?,
preprocessTreeNode : (([AnyObject],[String:Ref]) -> [AnyObject])!) -> [AnyObject] {
// Convert the MD tree to an HTML tree
// remove references from the tree
var refs : [String:Ref]
var i = input!
refs = i[1] as! [String:Ref]
var html = convert_tree_to_html(&input, refs: refs, preprocessTreeNode: preprocessTreeNode)
//todomerge_text_nodes(html)
return html
}
func extract_attr(jsonml : [AnyObject]) -> [String:AnyObject]? {
if jsonml.count > 1 {
if let attrs = jsonml[1] as? [String:AnyObject] {
return jsonml[1] as? [String:AnyObject]
} else {
return nil
}
} else {
return nil
}
}
func convert_tree_to_html(inout tree : [AnyObject]?,
refs : [String:Ref],
preprocessTreeNode : (([AnyObject],[String:Ref]) -> [AnyObject])!) -> [AnyObject] {
if tree == nil {
return []
}
// shallow clone
var jsonml : [AnyObject] = []
if preprocessTreeNode != nil {
jsonml = preprocessTreeNode(tree!, refs)
} else {
jsonml = tree!
}
var attrs : [String:AnyObject]? = extract_attr(jsonml)
// convert this node
if !(jsonml[0] is String) {
if jsonml[0] is [AnyObject] {
var subtree : [AnyObject]? = jsonml[0] as? [AnyObject]
return convert_tree_to_html(&subtree, refs: refs, preprocessTreeNode: preprocessTreeNode)
} else {
return []
}
}
var nodeName : String = jsonml[0] as! String
switch nodeName {
case "header":
jsonml[0] = "h" + ((attrs?["level"])! as! String)
attrs?.removeValueForKey("level")
case "bulletlist":
jsonml[0] = "ul"
case "numberlist":
jsonml[0] = "ol"
case "listitem":
jsonml[0] = "li"
case "para":
jsonml[0] = "p"
case "markdown":
jsonml[0] = "body"
if attrs != nil {
attrs?.removeValueForKey("refs")
}
case "code_block":
jsonml[0] = "pre"
var j = attrs != nil ? 2 : 1
var code : [AnyObject] = ["code"]
code.extend(jsonml[j...jsonml.count-j])
jsonml[j] = code
case "uchen_block":
jsonml[0] = "p"
var j = attrs != nil ? 2 : 1
var uchen : [AnyObject] = ["uchen"]
uchen.extend(jsonml[j...jsonml.count-j])
jsonml[j] = uchen
case "uchen":
jsonml[0] = "span"
case "inlinecode":
jsonml[0] = "code"
case "img":
println("img")
//todo jsonml[1].src = jsonml[ 1 ].href;
//delete jsonml[ 1 ].href;
case "linebreak":
jsonml[0] = "br"
case "link":
jsonml[0] = "a"
case "link_ref":
jsonml[0] = "a"
if attrs != nil {
var attributes : [String:AnyObject] = attrs!
var key = attributes["ref"] as? String
if key != nil {
// grab this ref and clean up the attribute node
var ref = refs[key!]
// if the reference exists, make the link
if ref != nil {
attrs!.removeValueForKey("ref")
// add in the href if present
attrs!["href"] = ref!.href
// get rid of the unneeded original text
attrs!.removeValueForKey("original")
jsonml[1] = attrs!
} else {
return (attributes.indexForKey("original") != nil) ? [attributes["original"]!] : []
}
}
}
case "img_ref":
jsonml[0] = "img"
if attrs != nil {
var attributes : [String:AnyObject] = attrs!
var key = attributes["ref"] as? String
if key != nil {
// grab this ref and clean up the attribute node
var ref = refs[key!]
// if the reference exists, make the link
if ref != nil {
attrs!.removeValueForKey("ref")
// add in the href if present
attrs!["href"] = ref!.href
// get rid of the unneeded original text
attrs!.removeValueForKey("original")
jsonml[1] = attrs!
} else {
return (attributes.indexForKey("original") != nil) ? [attributes["original"]!] : []
}
}
}
default:
println("convert_to_html encountered unsupported element " + nodeName)
}
// convert all the children
var l = 1
// deal with the attribute node, if it exists
if attrs != nil {
var attributes = attrs!
// if there are keys, skip over it
for (key,value) in attributes {
l = 2
break
}
}
// if there aren't, remove it
//if l == 1 {
// jsonml.removeAtIndex(1)
//}
for l; l < jsonml.count; ++l {
if (jsonml[l] is [AnyObject]) {
var node : [AnyObject]? = jsonml[l] as! [AnyObject]
jsonml[l] = convert_tree_to_html(&node, refs: refs, preprocessTreeNode: preprocessTreeNode)
}
}
return jsonml
}
func renderHTML(var jsonml : [AnyObject], includeRoot : Bool) -> String {
var content : [String] = []
if includeRoot {
content.append("<!DOCTYPE html>")
content.append("<html>")
content.append("<head>")
content.append("<meta charset=\"UTF-8\">")
content.append("<title>Markdown</title>")
content.append("</head>")
content.append(super.render_tree(jsonml))
content.append("</html>")
} else {
// remove tag
jsonml.removeAtIndex(0)
if var objArray = jsonml[0] as? [AnyObject] {
// remove attributes
objArray.removeAtIndex(0)
}
while jsonml.count > 0 {
var v : AnyObject? = jsonml.removeAtIndex(0)
if v is String {
content.append(super.render_tree(v as! String))
} else if v is [AnyObject] {
let arr : [AnyObject] = v as! [AnyObject]
content.append(super.render_tree(arr))
} else {
println("HTML renderer found a " + v!.type)
}
}
}
var joiner = "\n\n"
var joined = joiner.join(content)
return joined
}
}
|
gpl-2.0
|
7c9ffcd499319cce2354da8213376115
| 35.665254 | 113 | 0.435391 | 4.838926 | false | false | false | false |
biohazardlover/ByTrain
|
ByTrain/DataManager.swift
|
1
|
3426
|
import UIKit
private let _defaultManager = DataManager()
let FavoriteStationsKey = "com.studiopp.ByTrain.FavoriteStations"
let FromStationKey = "com.studiopp.ByTrain.FromStation"
let ToStationKey = "com.studiopp.ByTrain.ToStation"
let CookiesKey = "com.studiopp.ByTrain.Cookies"
class DataManager: NSObject {
class func defaultManager() -> DataManager {
return _defaultManager
}
func storeCookies() {
// var cookieProperties = [[NSObject: AnyObject]]()
//
// if let cookies = HTTPCookieStorage.shared.cookies {
// for cookie in cookies {
// if let properties = cookie.properties {
// cookieProperties.append(properties)
// }
// }
// }
//
// UserDefaults.standard.set(cookieProperties, forKey: CookiesKey)
}
func configureCookies() {
// if let cookiesProperties = UserDefaults.standard.dictionary(forKey: CookiesKey) {
// for cookieProperties in cookiesProperties {
// if let cookie = HTTPCookie(properties: cookieProperties) {
// HTTPCookieStorage.shared.setCookie(cookie)
// }
// }
// }
}
func clearCookies() {
if let cookies = HTTPCookieStorage.shared.cookies {
for cookie in cookies {
HTTPCookieStorage.shared.deleteCookie(cookie)
}
}
}
func addFavoriteStation(_ station: Station) {
var favoriteStations = self.favoriteStations() ?? []
if let index = favoriteStations.index(of: station) {
favoriteStations.remove(at: index)
}
favoriteStations.insert(station, at: 0)
let favoriteStationsData = NSKeyedArchiver.archivedData(withPropertyListReadableList: favoriteStations)
UserDefaults.standard.set(favoriteStationsData, forKey: FavoriteStationsKey)
}
func favoriteStations() -> [Station]? {
if let favoriteStationsData = UserDefaults.standard.data(forKey: FavoriteStationsKey) {
if let favoriteStations: [Station] = NSKeyedUnarchiver.unarchivePropertyListReadableList(with: favoriteStationsData) {
return favoriteStations
}
}
return nil
}
func saveFromStation(_ fromStation: Station) {
let fromStationData = NSKeyedArchiver.archivedData(withPropertyListReadable: fromStation)
UserDefaults.standard.set(fromStationData, forKey: FromStationKey)
}
func fromStation() -> Station? {
if let fromStationData = UserDefaults.standard.data(forKey: FromStationKey) {
if let fromStation: Station = NSKeyedUnarchiver.unarchivePropertyListReadable(with: fromStationData) {
return fromStation
}
}
return nil
}
func saveToStation(_ toStation: Station) {
let toStationData = NSKeyedArchiver.archivedData(withPropertyListReadable: toStation)
UserDefaults.standard.set(toStationData, forKey: ToStationKey)
}
func toStation() -> Station? {
if let toStationData = UserDefaults.standard.data(forKey: ToStationKey) {
if let toStation: Station = NSKeyedUnarchiver.unarchivePropertyListReadable(with: toStationData) {
return toStation
}
}
return nil
}
}
|
mit
|
015b805a6db3de8378ee35382b1f0fb2
| 34.319588 | 130 | 0.631057 | 4.965217 | false | true | false | false |
tsolomko/SWCompression
|
Sources/Common/Extensions.swift
|
1
|
1533
|
// Copyright (c) 2022 Timofey Solomko
// Licensed under MIT License
//
// See LICENSE for license information
import Foundation
extension UnsignedInteger {
@inlinable @inline(__always)
func toInt() -> Int {
return Int(truncatingIfNeeded: self)
}
}
extension Int {
@inlinable @inline(__always)
func toUInt8() -> UInt8 {
return UInt8(truncatingIfNeeded: UInt(self))
}
@inlinable @inline(__always)
func roundTo512() -> Int {
if self >= Int.max - 510 {
return Int.max
} else {
return (self + 511) & (~511)
}
}
/// Returns an integer with reversed order of bits.
func reversed(bits count: Int) -> Int {
var a = 1 << 0
var b = 1 << (count - 1)
var z = 0
for i in Swift.stride(from: count - 1, to: -1, by: -2) {
z |= (self >> i) & a
z |= (self << i) & b
a <<= 1
b >>= 1
}
return z
}
}
extension Date {
private static let ntfsReferenceDate = DateComponents(calendar: Calendar(identifier: .iso8601),
timeZone: TimeZone(abbreviation: "UTC"),
year: 1601, month: 1, day: 1,
hour: 0, minute: 0, second: 0).date!
init(_ ntfsTime: UInt64) {
self.init(timeInterval: TimeInterval(ntfsTime) / 10_000_000, since: .ntfsReferenceDate)
}
}
|
mit
|
119ae7cd82106ff4db3371c5fdbb9f6d
| 24.55 | 99 | 0.493151 | 4.234807 | false | false | false | false |
crescentflare/SmartMockServer
|
MockLibIOS/SmartMockLib/Classes/model/SmartMockResponse.swift
|
1
|
549
|
//
// SmartMockResponse.swift
// SmartMockServer Pod
//
// Main library model: a mocked response object
//
public class SmartMockResponse {
// --
// MARK: Members
// --
public var headers = SmartMockHeaders.makeFromHeaders(nil)
public var body = SmartMockResponseBody.makeFromString("")
public var mimeType = ""
public var code = 0
// --
// MARK: Helper
// --
public func setStringBody(_ body: String) {
self.body = SmartMockResponseBody.makeFromString(body)
}
}
|
mit
|
125d2696208542fec8d61520d78b36fa
| 18.607143 | 62 | 0.6102 | 4.255814 | false | false | false | false |
ZhangMingNan/MenSao
|
MenSao/Class/Trends/RecommendController.swift
|
1
|
3192
|
//
// RecommendController.swift
// MenSao
//
// Created by 张明楠 on 16/2/2.
// Copyright © 2016年 张明楠. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
import MJRefresh
class RecommendController: MingCascadeController {
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "我的关注"
settingRefresh()
Alamofire.request(.GET, "http://api.budejie.com/api/api_open.php", parameters: ["a": "category","c": "subscribe"])
.responseJSON { response in
if let data = response.result.value {
let json = JSON(data)
let list = json["list"].arrayValue
//print(list.count)
var temp:[CascadeModel] = []
list.forEach({ (item) -> () in
let ca = CascadeModel()
ca.id = item["id"].intValue
ca.name = item["name"].stringValue
ca.count = item["count"].intValue
temp.append(ca)
})
self.data = temp
}
}
}
func settingRefresh(){
self.secondaryTable?.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: { () -> Void in
print(">>")
})
self.secondaryTable?.mj_footer.hidden = true
}
override func secondaryTableReload(index: Int) {
//当刷新次级表格没有数据的时候隐藏底部
self.secondaryTable?.mj_footer.hidden = self.data[index].sub.count == 0
}
override func secondaryCellHeight()->CGFloat{
return 60
}
override func secondaryCell(sub:SubscribeModel) -> UITableViewCell {
let cell = SubscribeCell(style: UITableViewCellStyle.Default, reuseIdentifier: "subCell")
cell.subscribe = sub
return cell
}
override func mainCellOnClick(id: Int) {
super.mainCellOnClick(id)
var ca:CascadeModel? = nil
self.data.forEach({ (cascade) -> () in
if cascade.id == id {
ca = cascade
}
})
if ca?.sub.count == 0 {
//网络延迟时清空残留数据
self.secondaryTable?.reloadData()
Alamofire.request(.GET, "http://api.budejie.com/api/api_open.php", parameters: ["a": "list","c": "subscribe","category_id":id])
.responseJSON { response in
if let data = response.result.value {
let json = JSON(data)
let list = json["list"].arrayValue
var temp:[SubscribeModel] = []
list.forEach({ (item) -> () in
temp.append(SubscribeModel(item: item))
})
ca?.sub = temp
self.secondaryTable?.reloadData()
//结束刷新
self.secondaryTable?.mj_footer.endRefreshing()
}
}
}else {
self.secondaryTable?.reloadData()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
|
apache-2.0
|
5900ef07fb9faa53319556823ad2d253
| 27.46789 | 135 | 0.524976 | 4.61756 | false | false | false | false |
CryptoKitten/CryptoEssentials
|
Sources/ECB.swift
|
1
|
2035
|
// Originally based on CryptoSwift by Marcin Krzyżanowski <[email protected]>
// Copyright (C) 2014 Marcin Krzyżanowski <[email protected]>
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
//
// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
// - This notice may not be removed or altered from any source or binary distribution.
final public class ECB: BlockMode {
public static let options: BlockModeOptions = [.paddingRequired]
public static let blockType = InputBlockType.decrypt
public static func makeDecryptionIterator(iv: [UInt8], cipherOperation: @escaping CipherBlockOperation, inputGenerator: AnyIterator<[UInt8]>) -> AnyIterator<[UInt8]> {
return AnyIterator {
guard let plaintext = inputGenerator.next(),
let encrypted = cipherOperation(plaintext)
else {
return nil
}
return encrypted
}
}
public static func makeEncryptionIterator(iv: [UInt8], cipherOperation: @escaping CipherBlockOperation, inputGenerator: AnyIterator<[UInt8]>) -> AnyIterator<[UInt8]> {
return AnyIterator {
guard let plaintext = inputGenerator.next(),
let encrypted = cipherOperation(plaintext)
else {
return nil
}
return encrypted
}
}
}
|
mit
|
d9e815d5622ce0e2e8b7601c4a548841
| 49.825 | 216 | 0.684211 | 5.280519 | false | false | false | false |
r14r/fork_swift_intro-playgrounds
|
06-Strings.playground/section-1.swift
|
2
|
1689
|
// Playground - noun: a place where people can play
import Cocoa
// Saw basics of string literals before. Reminder:
let message = "My name is \"Bennett\"";
let interpolatedString = "2 + 2 = \(2+2)"
var str = "Hello, playground"
// Unicode strings
let dollarSign = "\x24"
let blackHeart = "\u2665"
let sparklingHeart = "\U0001F496"
// Initializing empty string
var emptyString = ""
var anotherEmptyString = String()
// Testing for empty string
emptyString.isEmpty
sparklingHeart.isEmpty
// Mutability
let first = "Bennett"
let last = "Smith"
let fullName = first + " " + last
var properName = "Mr. "
properName += fullName
// Strings are value types. Their values are copied, not shared.
var s1 = "Hello"
var s2 = s1
s2 = "Goodbye"
s1
s2
// Elements of string are of type Character. Can iterate them.
for char in "Dog!🐶" {
println(char)
}
// Counting characters in a string.
// - full unicode string - each character can take a different size
// - use global countElements function
countElements(properName)
countElements(sparklingHeart)
// Concatenation
//
// Examples above. Either use + or += to concatenate.
// Works with Character type too.
// String Equality
first == "Bennett"
first != "Henry"
first.hasPrefix("ben")
first.hasPrefix("Ben")
first.hasSuffix("tt")
// Case conversion
first.uppercaseString
first.lowercaseString
// Accessing individual Unicode code units or scalars
println("")
let dogString = "Dog!🐶"
for codeUnit in dogString.utf8 {
println("\(codeUnit)")
}
println("")
for codeUnit in dogString.utf16 {
println("\(codeUnit)")
}
println("")
for scalar in dogString.unicodeScalars {
println("\(scalar.value)")
}
|
mit
|
4c2bcf2f37ced1829507aa5081910f9b
| 17.096774 | 69 | 0.7041 | 3.543158 | false | false | false | false |
findmybusnj/findmybusnj-swift
|
findmybusnjUITests/ETABusTimeTableControllerUITests.swift
|
1
|
3740
|
//
// findmybusnjUITests.swift
// findmybusnjUITests
//
// Created by David Aghassi on 9/28/15.
// Copyright © 2015 David Aghassi. All rights reserved.
//
import XCTest
class ETABusTimeTableControllerUITests: XCTestCase {
let app = XCUIApplication()
var tableUnderTest: XCUIElement {
return app.tables["ETABusTimeTable"]
}
override func setUp() {
super.setUp()
setupSnapshot(app)
continueAfterFailure = false
app.launch()
XCTAssertTrue(app.tables["ETABusTimeTable"].tableRows.count == 0, "Table should initialize with with no rows")
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func test_Assert_Save_Favorite_Exists() {
XCTAssert(app.buttons["saveFavorite"].exists, "Save button should exist")
}
/**
Asserts that the app has text hinting user to navigate to begin
*/
func test_Assert_Background_Hint_Exists_On_Empty_Table() {
XCTAssert(app.staticTexts["Please tap on \"Find\" to get started"].exists,
"Background hint information is missing.")
}
func test_Assert_Search_Button_Exists() {
XCTAssert(app.buttons["Search"].exists, "Find button should exist")
}
/**
Tests that user is notified if trying to save when no search data is present
*/
func test_Assert_Warning_On_Empty_Save() {
let saveButton = app.navigationBars["findmybusnj.ETABusTimeTable"].buttons["saveFavorite"]
let saveAlert = app.alerts["No stop to save"]
XCTAssertTrue(saveButton.exists)
saveButton.doubleTap()
// TODO - Figure out why a doubleTap() is needed over a tap()
let exists = NSPredicate(format: "exists == true")
expectation(for: exists, evaluatedWith: saveAlert, handler: nil)
waitForExpectations(timeout: 5, handler: nil)
XCTAssertTrue(saveAlert.exists)
saveAlert.buttons["Done"].tap()
}
/**
Checks that reload will not crash when there is no data
*/
func test_EmptyListRefreshes() {
app.tabBars.buttons["Times"].tap()
let table = app.navigationBars["findmybusnj.ETABusTimeTable"]
XCTAssertTrue(app.tables.cells.count == 0)
let start = table.coordinate(withNormalizedOffset: CGVector(dx: 10, dy: 8))
let end = table.coordinate(withNormalizedOffset: CGVector(dx: 10, dy: 16))
start.press(forDuration: 0, thenDragTo: end)
XCTAssertTrue(app.tables.cells.count == 0)
}
func test_screenshot_CaptureMultipleStops() {
app.tabBars.buttons["Times"].tap()
XCTAssertTrue(app.tables.cells.count == 0)
XCUIApplication().navigationBars["findmybusnj.ETABusTimeTable"].buttons["Search"].tap()
let stopNumberTextField = XCUIApplication().textFields["Stop Number"]
stopNumberTextField.tap()
stopNumberTextField.typeText("26229")
app.buttons["Search"].tap()
XCTAssertTrue(app.tables.cells.count == 4, "Table did not populate with proper number of rows. \n" +
"Expected: 4 \n" + "Actual: \(app.tables.cells.count)")
sleep(2)
snapshot("multipleStops")
}
func test_screenshot_CaptureSave() {
app.tabBars.buttons["Times"].tap()
XCTAssertTrue(app.tables.cells.count == 0)
app.navigationBars["findmybusnj.ETABusTimeTable"].buttons["Search"].tap()
let stopNumberTextField = XCUIApplication().textFields["Stop Number"]
stopNumberTextField.tap()
stopNumberTextField.typeText("26229")
app.buttons["Search"].tap()
XCTAssertTrue(app.tables.cells.count == 4, "Table did not populate with proper number of rows. \n" +
"Expected: 4 \n" + "Actual: \(app.tables.cells.count)")
sleep(2)
app.navigationBars["26229"].buttons["saveFavorite"].tap()
snapshot("saveFavorite")
}
}
|
gpl-3.0
|
f478c6902f6d60a997e07d85c191f4d0
| 30.957265 | 114 | 0.698048 | 3.956614 | false | true | false | false |
Tsaude/GustieMenu
|
iOS/GustieMenu/View/StationTableViewCell.swift
|
1
|
706
|
//
// BookTableViewCell.swift
// Book-Q
//
// Created by Tucker Saude on 8/26/16.
// Copyright © 2016 Tucker Saude. All rights reserved.
//
import UIKit
class StationTableViewCell: UITableViewCell {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var indicatorImageView: UIImageView!
var station: StationViewModel? {
didSet {
if let station = station {
nameLabel.text = station.name
indicatorImageView.image = UIImage(named: station.isShowingMenuItems ? "indicator_up" : "indicator")
} else {
nameLabel?.text = ""
indicatorImageView?.image = nil
}
}
}
}
|
mit
|
464d26f5875950e3bf50e8e99413cafc
| 24.178571 | 116 | 0.594326 | 4.490446 | false | false | false | false |
kean/Nuke
|
Tests/NukeTests/ImageProcessorsTests/RoundedCornersTests.swift
|
1
|
6763
|
// The MIT License (MIT)
//
// Copyright (c) 2015-2022 Alexander Grebenyuk (github.com/kean).
import XCTest
@testable import Nuke
#if !os(macOS)
import UIKit
#endif
class ImageProcessorsRoundedCornersTests: XCTestCase {
func _testThatCornerRadiusIsAdded() throws {
// Given
let input = Test.image(named: "fixture-tiny.jpeg")
let processor = ImageProcessors.RoundedCorners(radius: 12, unit: .pixels)
// When
let output = try XCTUnwrap(processor.process(input), "Failed to process an image")
// Then
let expected = Test.image(named: "s-rounded-corners.png")
XCTAssertEqualImages(output, expected)
XCTAssertEqual(output.sizeInPixels, CGSize(width: 200, height: 150))
}
func _testThatBorderIsAdded() throws {
// Given
let input = Test.image(named: "fixture-tiny.jpeg")
let border = ImageProcessingOptions.Border(color: .red, width: 4, unit: .pixels)
let processor = ImageProcessors.RoundedCorners(radius: 12, unit: .pixels, border: border)
// When
let output = try XCTUnwrap(processor.process(input), "Failed to process an image")
// Then
let expected = Test.image(named: "s-rounded-corners-border.png")
XCTAssertEqualImages(output, expected)
}
func testExtendedColorSpaceSupport() throws {
// Given
let input = Test.image(named: "image-p3", extension: "jpg")
let processor = ImageProcessors.RoundedCorners(radius: 12, unit: .pixels)
// When
let output = try XCTUnwrap(processor.process(input), "Failed to process an image")
// Then image is resized but isn't cropped
let colorSpace = try XCTUnwrap(output.cgImage?.colorSpace)
#if os(iOS) || os(tvOS) || os(macOS)
XCTAssertTrue(colorSpace.isWideGamutRGB)
#elseif os(watchOS)
XCTAssertFalse(colorSpace.isWideGamutRGB)
#endif
}
@MainActor
func testEqualIdentifiers() {
XCTAssertEqual(
ImageProcessors.RoundedCorners(radius: 16).identifier,
ImageProcessors.RoundedCorners(radius: 16).identifier
)
XCTAssertEqual(
ImageProcessors.RoundedCorners(radius: 16, unit: .pixels).identifier,
ImageProcessors.RoundedCorners(radius: 16 / Screen.scale, unit: .points).identifier
)
XCTAssertEqual(
ImageProcessors.RoundedCorners(radius: 16, unit: .pixels, border: .init(color: .red)).identifier,
ImageProcessors.RoundedCorners(radius: 16, unit: .pixels, border: .init(color: .red)).identifier
)
}
@MainActor
func testNotEqualIdentifiers() {
XCTAssertNotEqual(
ImageProcessors.RoundedCorners(radius: 16).identifier,
ImageProcessors.RoundedCorners(radius: 8).identifier
)
if Screen.scale == 1 {
XCTAssertEqual(
ImageProcessors.RoundedCorners(radius: 16, unit: .pixels, border: .init(color: .red)).identifier,
ImageProcessors.RoundedCorners(radius: 16, unit: .points, border: .init(color: .red)).identifier
)
XCTAssertNotEqual(
ImageProcessors.RoundedCorners(radius: 32, unit: .pixels, border: .init(color: .red)).identifier,
ImageProcessors.RoundedCorners(radius: 16, unit: .points, border: .init(color: .red)).identifier
)
} else {
XCTAssertNotEqual(
ImageProcessors.RoundedCorners(radius: 16, unit: .pixels, border: .init(color: .red)).identifier,
ImageProcessors.RoundedCorners(radius: 16, unit: .points, border: .init(color: .red)).identifier
)
}
XCTAssertNotEqual(
ImageProcessors.RoundedCorners(radius: 16, unit: .pixels, border: .init(color: .red)).identifier,
ImageProcessors.RoundedCorners(radius: 16, unit: .pixels, border: .init(color: .blue)).identifier
)
}
@MainActor
func testEqualHashableIdentifiers() {
XCTAssertEqual(
ImageProcessors.RoundedCorners(radius: 16).hashableIdentifier,
ImageProcessors.RoundedCorners(radius: 16).hashableIdentifier
)
XCTAssertEqual(
ImageProcessors.RoundedCorners(radius: 16, unit: .pixels).hashableIdentifier,
ImageProcessors.RoundedCorners(radius: 16 / Screen.scale, unit: .points).hashableIdentifier
)
XCTAssertEqual(
ImageProcessors.RoundedCorners(radius: 16, unit: .pixels, border: .init(color: .red)).hashableIdentifier,
ImageProcessors.RoundedCorners(radius: 16, unit: .pixels, border: .init(color: .red)).hashableIdentifier
)
}
@MainActor
func testNotEqualHashableIdentifiers() {
XCTAssertNotEqual(
ImageProcessors.RoundedCorners(radius: 16).hashableIdentifier,
ImageProcessors.RoundedCorners(radius: 8).hashableIdentifier
)
if Screen.scale == 1 {
XCTAssertEqual(
ImageProcessors.RoundedCorners(radius: 16, unit: .pixels, border: .init(color: .red)).hashableIdentifier,
ImageProcessors.RoundedCorners(radius: 16, unit: .points, border: .init(color: .red)).hashableIdentifier
)
XCTAssertNotEqual(
ImageProcessors.RoundedCorners(radius: 32, unit: .pixels, border: .init(color: .red)).hashableIdentifier,
ImageProcessors.RoundedCorners(radius: 16, unit: .points, border: .init(color: .red)).hashableIdentifier
)
} else {
XCTAssertNotEqual(
ImageProcessors.RoundedCorners(radius: 16, unit: .pixels, border: .init(color: .red)).hashableIdentifier,
ImageProcessors.RoundedCorners(radius: 16, unit: .points, border: .init(color: .red)).hashableIdentifier
)
}
XCTAssertNotEqual(
ImageProcessors.RoundedCorners(radius: 16, unit: .pixels, border: .init(color: .red)).hashableIdentifier,
ImageProcessors.RoundedCorners(radius: 16, unit: .pixels, border: .init(color: .blue)).hashableIdentifier
)
}
func testDescription() {
// Given
let processor = ImageProcessors.RoundedCorners(radius: 16, unit: .pixels)
// Then
XCTAssertEqual(processor.description, "RoundedCorners(radius: 16.0 pixels, border: nil)")
}
func testDescriptionWithBorder() {
// Given
let processor = ImageProcessors.RoundedCorners(radius: 16, unit: .pixels, border: .init(color: .red, width: 2, unit: .pixels))
// Then
XCTAssertEqual(processor.description, "RoundedCorners(radius: 16.0 pixels, border: Border(color: #FF0000, width: 2.0 pixels))")
}
}
|
mit
|
8b58180322522caf66c692c3c423b277
| 41.26875 | 135 | 0.644536 | 4.613233 | false | true | false | false |
jkolb/midnightbacon
|
MidnightBacon/Modules/Submit/TableViewCellPresenter.swift
|
1
|
4318
|
//
// TableViewCellPresenter.swift
// MidnightBacon
//
// Copyright (c) 2015 Justin Kolb - http://franticapparatus.net
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
protocol TableCellPresenter {
func registerCellClassForTableView(tableView: UITableView)
func cellForRowInTableView(tableView: UITableView, atIndexPath indexPath: NSIndexPath, withValue value: Any) -> UITableViewCell
func heightForRowInTableView(tableView: UITableView, atIndexPath indexPath: NSIndexPath, withValue value: Any) -> CGFloat
func selectRowInTableView(tableView: UITableView, atIndexPath indexPath: NSIndexPath, withValue value: Any)
func deselectRowInTableView(tableView: UITableView, atIndexPath indexPath: NSIndexPath, withValue value: Any)
}
class TableViewCellPresenter<ValueType, CellType: UITableViewCell, ContextType: AnyObject> : TableCellPresenter {
let reuseIdentifier: String
private weak var context: ContextType?
var present: ((ContextType, ValueType, CellType, NSIndexPath) -> ())?
var select: ((ContextType, ValueType, CellType, NSIndexPath) -> ())?
var deselect: ((ContextType, ValueType, CellType?, NSIndexPath) -> ())?
private var sizingCell: CellType!
init(context: ContextType, reuseIdentifier: String) {
self.context = context
self.reuseIdentifier = reuseIdentifier
}
func registerCellClassForTableView(tableView: UITableView) {
tableView.registerClass(CellType.self, forCellReuseIdentifier: reuseIdentifier)
}
func cellForRowInTableView(tableView: UITableView, atIndexPath indexPath: NSIndexPath, withValue value: Any) -> UITableViewCell {
let typedCell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CellType
let typedValue = value as! ValueType
if let strongContext = context {
present?(strongContext, typedValue, typedCell, indexPath)
}
return typedCell
}
func heightForRowInTableView(tableView: UITableView, atIndexPath indexPath: NSIndexPath, withValue value: Any) -> CGFloat {
if sizingCell == nil {
sizingCell = CellType()
}
let typedValue = value as! ValueType
if let strongContext = context {
present?(strongContext, typedValue, sizingCell, indexPath)
}
let fitSize = CGSize(width: tableView.bounds.width, height: 10_000.00)
let sizeThatFits = sizingCell.sizeThatFits(fitSize)
return sizeThatFits.height
}
func selectRowInTableView(tableView: UITableView, atIndexPath indexPath: NSIndexPath, withValue value: Any) {
let typedCell = tableView.cellForRowAtIndexPath(indexPath) as! CellType
let typedValue = value as! ValueType
if let strongContext = context {
select?(strongContext, typedValue, typedCell, indexPath)
}
}
func deselectRowInTableView(tableView: UITableView, atIndexPath indexPath: NSIndexPath, withValue value: Any) {
let typedCell = tableView.cellForRowAtIndexPath(indexPath) as? CellType
let typedValue = value as! ValueType
if let strongContext = context {
deselect?(strongContext, typedValue, typedCell, indexPath)
}
}
}
|
mit
|
0c20273f4d15bfe338d886c4bef92fc1
| 46.450549 | 133 | 0.727883 | 5.233939 | false | false | false | false |
zaczh/AutoPagingFlowLayout
|
AutoPagingFlowLayout/Layouts/WKAutomaticPagingFlowLayout.swift
|
1
|
5073
|
//
// WKAutomaticPagingFlowLayout.swift
// WKChatViewControllerDemo
//
// Created by hooge on 16/4/6.
// Copyright © 2016年 hoowang. All rights reserved.
//
import UIKit
open class WKAutomaticPagingFlowLayout: UICollectionViewFlowLayout {
var pageContentInsets:UIEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
fileprivate var interitemSpacing: CGFloat = 0
fileprivate var lineSpacing: CGFloat = 0
}
extension WKAutomaticPagingFlowLayout{
fileprivate func numberOfItems() ->(Int){
guard let collectionView = collectionView else {
return 0
}
// only support one section
let section = 0
let numberOfItems = collectionView.numberOfItems(inSection: section)
return numberOfItems
}
fileprivate var collectionViewSize: CGSize {
guard let collectionView = collectionView else {
return CGSize.zero
}
return collectionView.bounds.size
}
//一行有多少列
fileprivate func colsPerPage() -> (Int){
assert(itemSize.width > 0, "item width must be greater than 0!")
let cols = Int((collectionViewSize.width - self.pageContentInsets.left - self.pageContentInsets.right + self.minimumInteritemSpacing)/(self.minimumInteritemSpacing + itemSize.width))
assert(cols > 0, "width - pageContentInsets.left - pageContentInsets.right + minimumInteritemSpacing <= 0")
self.interitemSpacing = (collectionViewSize.width - self.pageContentInsets.left - self.pageContentInsets.right - CGFloat(cols) * itemSize.width)/(CGFloat(cols) - 1)
return cols
}
// 一页有多少行
fileprivate func rowsPerPage() -> (Int){
assert(itemSize.height > 0, "item height must be greater than 0!")
let rows = Int((collectionViewSize.height - self.pageContentInsets.top - self.pageContentInsets.bottom + self.minimumLineSpacing)/(self.minimumLineSpacing + itemSize.height))
assert(rows > 0, "height - pageContentInsets.top - pageContentInsets.bottom + minimumLineSpacing <= 0")
self.lineSpacing = (collectionViewSize.height - self.pageContentInsets.top - self.pageContentInsets.bottom - CGFloat(rows) * itemSize.height)/(CGFloat(rows) - 1)
return rows
}
// 一页的总数
fileprivate func numberOfItemsPerPage() -> (Int){
return colsPerPage() * rowsPerPage()
}
// item frame 计算
fileprivate func calcItemFrameWithIndexPath(_ indexPath:IndexPath) ->(CGRect){
let index = indexPath.row
let page = floor( CGFloat(index) / CGFloat(self.numberOfItemsPerPage()))
let row = floor( CGFloat(index % self.numberOfItemsPerPage()) / CGFloat(self.colsPerPage()))
let n = index % self.colsPerPage()
var x:CGFloat = 0.0;
var y:CGFloat = 0.0;
var width:CGFloat = 0.0;
var height:CGFloat = 0.0;
x = page * self.collectionViewSize.width + self.pageContentInsets.left + CGFloat(n) * (self.itemSize.width + self.interitemSpacing)
y = self.pageContentInsets.top + row * (self.itemSize.height + self.lineSpacing)
width = self.itemSize.width
height = self.itemSize.height
return CGRect(x: x, y: y, width: width, height: height)
}
}
// MARK: - 重写父类方法
extension WKAutomaticPagingFlowLayout{
override open func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
let attributes = UICollectionViewLayoutAttributes(forCellWith:indexPath)
attributes.frame = calcItemFrameWithIndexPath(indexPath)
return attributes
}
override open func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
guard self.numberOfItems() > 0 else {
return super.layoutAttributesForElements(in: rect)
}
var attributeArray = [UICollectionViewLayoutAttributes]()
for i in 0 ..< self.numberOfItems() {
let attributes =
layoutAttributesForItem(at: IndexPath(row: i, section: 0))
if rect.intersects((attributes?.frame)!) {
attributeArray.append(attributes!)
}
}
return attributeArray
}
override open func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
if (collectionView!.bounds.size.equalTo(newBounds.size)) {
return false
}
else {
return true
}
}
open override var collectionViewContentSize : (CGSize){
let items:CGFloat = CGFloat(numberOfItems())
guard items > 0 else {
return CGSize.zero
}
let perPageItems:CGFloat = CGFloat(numberOfItemsPerPage())
var width:CGFloat = 0.0
var height:CGFloat = 0.0
width = ceil(items / perPageItems) * collectionViewSize.width
height = collectionViewSize.height
return CGSize(width: width, height: height)
}
}
|
mit
|
eb47d4611a7c101469cc63a3a4f0514c
| 36.185185 | 190 | 0.655179 | 4.873786 | false | false | false | false |
GreatfeatServices/gf-mobile-app
|
olivin-esguerra/ios-exam/Pods/RxSwift/RxSwift/AnyObserver.swift
|
54
|
2181
|
//
// AnyObserver.swift
// RxSwift
//
// Created by Krunoslav Zaher on 2/28/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
/// A type-erased `ObserverType`.
///
/// Forwards operations to an arbitrary underlying observer with the same `Element` type, hiding the specifics of the underlying observer type.
public struct AnyObserver<Element> : ObserverType {
/// The type of elements in sequence that observer can observe.
public typealias E = Element
/// Anonymous event handler type.
public typealias EventHandler = (Event<Element>) -> Void
private let observer: EventHandler
/// Construct an instance whose `on(event)` calls `eventHandler(event)`
///
/// - parameter eventHandler: Event handler that observes sequences events.
public init(eventHandler: @escaping EventHandler) {
self.observer = eventHandler
}
/// Construct an instance whose `on(event)` calls `observer.on(event)`
///
/// - parameter observer: Observer that receives sequence events.
public init<O : ObserverType>(_ observer: O) where O.E == Element {
self.observer = observer.on
}
/// Send `event` to this observer.
///
/// - parameter event: Event instance.
public func on(_ event: Event<Element>) {
return self.observer(event)
}
/// Erases type of observer and returns canonical observer.
///
/// - returns: type erased observer.
public func asObserver() -> AnyObserver<E> {
return self
}
}
extension ObserverType {
/// Erases type of observer and returns canonical observer.
///
/// - returns: type erased observer.
public func asObserver() -> AnyObserver<E> {
return AnyObserver(self)
}
/// Transforms observer of type R to type E using custom transform method.
/// Each event sent to result observer is transformed and sent to `self`.
///
/// - returns: observer that transforms events.
public func mapObserver<R>(_ transform: @escaping (R) throws -> E) -> AnyObserver<R> {
return AnyObserver { e in
self.on(e.map(transform))
}
}
}
|
apache-2.0
|
830c9620deb2d5608a6de52ae4fa8cd8
| 30.594203 | 143 | 0.651835 | 4.589474 | false | false | false | false |
NunoAlexandre/broccoli_mobile
|
ios/Carthage/Checkouts/Eureka/Source/Validations/RuleEqualsToRow.swift
|
3
|
2076
|
// RuleRequire.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public struct RuleEqualsToRow<T: Equatable>: RuleType {
public init(form: Form, tag: String, msg: String = "Fields don't match!"){
self.validationError = ValidationError(msg: msg)
self.form = form
self.tag = tag
self.row = nil;
}
public init(row: RowOf<T>, msg: String = "Fields don't match!"){
self.validationError = ValidationError(msg: msg)
self.form = nil
self.tag = nil
self.row = row
}
public var id: String?
public var validationError: ValidationError
public var form: Form?
public var tag: String?
public var row: RowOf<T>?
public func isValid(value: T?) -> ValidationError? {
let rowAux: RowOf<T> = row ?? form!.rowBy(tag: tag!)!
return rowAux.value == value ? nil : validationError
}
}
|
mit
|
d267da028fe988fbcf933ded9b4f2ea4
| 38.169811 | 80 | 0.692197 | 4.298137 | false | false | false | false |
BalestraPatrick/Tweetometer
|
Carthage/Checkouts/Swifter/Sources/SwifterTrends.swift
|
2
|
2630
|
//
// SwifterTrends.swift
// Swifter
//
// Created by Matt Donnelly on 21/06/2014.
// Copyright (c) 2014 Matt Donnelly. All rights reserved.
//
import Foundation
public extension Swifter {
/**
GET trends/place
Returns the top 10 trending topics for a specific WOEID, if trending information is available for it.
The response is an array of "trend" objects that encode the name of the trending topic, the query parameter that can be used to search for the topic on Twitter Search, and the Twitter Search URL.
This information is cached for 5 minutes. Requesting more frequently than that will not return any more data, and will count against your rate limit usage.
*/
public func getTrendsPlace(with woeid: String,
excludeHashtags: Bool = false,
success: SuccessHandler? = nil, failure: FailureHandler? = nil) {
let path = "trends/place.json"
var parameters = [String: Any]()
parameters["id"] = woeid
parameters["exclude"] = excludeHashtags ? "hashtags" : nil
self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in
success?(json)
}, failure: failure)
}
/**
GET trends/available
Returns the locations that Twitter has trending topic information for.
The response is an array of "locations" that encode the location's WOEID and some other human-readable information such as a canonical name and country the location belongs in.
A WOEID is a Yahoo! Where On Earth ID.
*/
public func getAvailableTrends(success: SuccessHandler? = nil,
failure: FailureHandler? = nil) {
let path = "trends/available.json"
self.getJSON(path: path, baseURL: .api, parameters: [:], success: { json, _ in
success?(json)
}, failure: failure)
}
/**
GET trends/closest
Returns the locations that Twitter has trending topic information for, closest to a specified location.
The response is an array of "locations" that encode the location's WOEID and some other human-readable information such as a canonical name and country the location belongs in.
A WOEID is a Yahoo! Where On Earth ID.
*/
public func getClosestTrends(for coordinate: (lat: Double, long: Double),
success: SuccessHandler? = nil,
failure: FailureHandler? = nil) {
let path = "trends/closest.json"
let parameters = ["lat": coordinate.lat, "long": coordinate.long]
self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in
success?(json)
}, failure: failure)
}
}
|
mit
|
62618856fbe1591ed8ef270fdf670fbf
| 35.527778 | 199 | 0.679087 | 4.201278 | false | false | false | false |
dreamsxin/swift
|
test/Sema/editor_placeholders.swift
|
7
|
1428
|
// RUN: %target-parse-verify-swift
func foo(_ x: Int) -> Int {}
func foo(_ x: Float) -> Float {}
var v = foo(<#T##x: Float##Float#>) // expected-error {{editor placeholder}}
v = "" // expected-error {{cannot assign value of type 'String' to type 'Float'}}
if (true) {
<#code#> // expected-error {{editor placeholder}}
}
foo(<#T##x: Undeclared##Undeclared#>) // expected-error {{editor placeholder}} expected-error {{use of undeclared type 'Undeclared'}}
func f(_ n: Int) {}
let a1 = <#T#> // expected-error{{editor placeholder in source file}}
f(a1) // expected-error{{cannot convert value of type '()' to expected argument type 'Int'}}
let a2 = <#T##Int#> // expected-error{{editor placeholder in source file}}
f(a2)
<#T#> // expected-error{{editor placeholder in source file}}
// FIXME: <rdar://problem/22432828> Lexer yields "editor placeholder in source file" error twice when placeholder is first token
_ = <#T##Int#> // expected-error {{editor placeholder in source file}}
f(<#T#> + 1) // expected-error{{editor placeholder in source file}}
f(<#T##Int#>) // expected-error{{editor placeholder in source file}}
f(<#T##String#>) // expected-error{{editor placeholder in source file}} expected-error{{cannot convert value of type 'String' to expected argument type 'Int'}}
for x in <#T#> { // expected-error{{editor placeholder in source file}} expected-error{{type '()' does not conform to protocol 'Sequence'}}
}
|
apache-2.0
|
34fefcdc177d7e0284f4f3486e938f72
| 46.6 | 159 | 0.679972 | 3.689922 | false | false | false | false |
ainopara/Stage1st-Reader
|
Stage1st/Vendors/ActivityItemProvider.swift
|
1
|
1821
|
//
// ActivityItemProvider.swift
// Stage1st
//
// Created by Zheng Li on 10/6/16.
// Copyright © 2016 Renaissance. All rights reserved.
//
import UIKit
extension UIActivity.ActivityType {
static let weibo = UIActivity.ActivityType("com.sina.weibo.ShareExtension")
static let moke2 = UIActivity.ActivityType("com.moke.moke-2.Share")
static let jidian = UIActivity.ActivityType("me.imtx.NewLime.NewLimeShare")
static let tweetBot4 = UIActivity.ActivityType("com.tapbots.Tweetbot4.shareextension")
}
class ContentTextActivityItemProvider: UIActivityItemProvider {
let title: String
let urlString: String
override var item: Any {
guard let activityType = self.activityType else {
return "\(title) \(urlString)"
}
switch activityType {
case .weibo:
return UIImage() // Weibo official iOS client only support share image.
case .postToWeibo, .moke2, .jidian:
return "\(self.title) #Stage1st Reader# \(urlString)"
case .postToTwitter, .tweetBot4:
return "\(self.title) #Stage1st \(urlString)"
default:
return "\(title) \(urlString)"
}
}
init(title: String, urlString: String) {
self.title = title
self.urlString = urlString
super.init(placeholderItem: "")
}
}
class ContentImageActivityItemProvider: UIActivityItemProvider {
weak var view: UIView?
let rect: CGRect
override var item: Any {
var image: UIImage?
DispatchQueue.main.sync {
image = view?.s1_screenShot()?.s1_crop(to: rect)
}
return image ?? UIImage()
}
init(view: UIView, cropTo rect: CGRect) {
self.view = view
self.rect = rect
super.init(placeholderItem: UIImage())
}
}
|
bsd-3-clause
|
3a4a49e5ff76dd117a5f339e0003fd03
| 27.888889 | 90 | 0.636264 | 4.212963 | false | false | false | false |
tehprofessor/SwiftyFORM
|
Source/Cells/DatePickerCell.swift
|
1
|
6562
|
// MIT license. Copyright (c) 2014 SwiftyFORM. All rights reserved.
import UIKit
public struct DatePickerCellModel {
var title: String = ""
var toolbarMode: ToolbarMode = .Simple
var datePickerMode: UIDatePickerMode = .DateAndTime
var locale: NSLocale? = nil // default is [NSLocale currentLocale]. setting nil returns to default
var minimumDate: NSDate? = nil // specify min/max date range. default is nil. When min > max, the values are ignored. Ignored in countdown timer mode
var maximumDate: NSDate? = nil // default is nil
var valueDidChange: NSDate -> Void = { (date: NSDate) in
DLog("date \(date)")
}
}
public class DatePickerCell: UITableViewCell, SelectRowDelegate {
public let model: DatePickerCellModel
public init(model: DatePickerCellModel) {
/*
Known problem: UIDatePickerModeCountDownTimer is buggy and therefore not supported
UIDatePicker has a bug in it when used in UIDatePickerModeCountDownTimer mode. The picker does not fire the target-action
associated with the UIControlEventValueChanged event the first time the user changes the value by scrolling the wheels.
It works fine for subsequent changes.
http://stackoverflow.com/questions/20181980/uidatepicker-bug-uicontroleventvaluechanged-after-hitting-minimum-internal
http://stackoverflow.com/questions/19251803/objective-c-uidatepicker-uicontroleventvaluechanged-only-fired-on-second-select
Possible work around: Continuously poll for changes.
*/
assert(model.datePickerMode != .CountDownTimer, "CountDownTimer is not supported")
self.model = model
super.init(style: .Value1, reuseIdentifier: nil)
selectionStyle = .Default
textLabel?.text = model.title
updateValue()
assignDefaultColors()
}
public required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func assignDefaultColors() {
textLabel?.textColor = UIColor.blackColor()
detailTextLabel?.textColor = UIColor.grayColor()
}
public func assignTintColors() {
let color = self.tintColor
DLog("assigning tint color: \(color)")
textLabel?.textColor = color
detailTextLabel?.textColor = color
}
public func resolveLocale() -> NSLocale {
return model.locale ?? NSLocale.currentLocale()
}
public lazy var datePicker: UIDatePicker = {
let instance = UIDatePicker()
instance.datePickerMode = self.model.datePickerMode
instance.minimumDate = self.model.minimumDate
instance.maximumDate = self.model.maximumDate
instance.addTarget(self, action: "valueChanged", forControlEvents: .ValueChanged)
instance.locale = self.resolveLocale()
return instance
}()
public lazy var toolbar: SimpleToolbar = {
let instance = SimpleToolbar()
weak var weakSelf = self
instance.jumpToPrevious = {
if let cell = weakSelf {
cell.gotoPrevious()
}
}
instance.jumpToNext = {
if let cell = weakSelf {
cell.gotoNext()
}
}
instance.dismissKeyboard = {
if let cell = weakSelf {
cell.dismissKeyboard()
}
}
return instance
}()
public func updateToolbarButtons() {
if model.toolbarMode == .Simple {
toolbar.updateButtonConfiguration(self)
}
}
public func gotoPrevious() {
DLog("make previous cell first responder")
form_makePreviousCellFirstResponder()
}
public func gotoNext() {
DLog("make next cell first responder")
form_makeNextCellFirstResponder()
}
public func dismissKeyboard() {
DLog("dismiss keyboard")
resignFirstResponder()
}
public override var inputView: UIView? {
return datePicker
}
public override var inputAccessoryView: UIView? {
if model.toolbarMode == .Simple {
return toolbar
}
return nil
}
public func valueChanged() {
let date = datePicker.date
model.valueDidChange(date)
updateValue()
}
public func obtainDateStyle(datePickerMode: UIDatePickerMode) -> NSDateFormatterStyle {
switch datePickerMode {
case .Time:
return .NoStyle
case .Date:
return .LongStyle
case .DateAndTime:
return .ShortStyle
case .CountDownTimer:
return .NoStyle
}
}
public func obtainTimeStyle(datePickerMode: UIDatePickerMode) -> NSDateFormatterStyle {
switch datePickerMode {
case .Time:
return .ShortStyle
case .Date:
return .NoStyle
case .DateAndTime:
return .ShortStyle
case .CountDownTimer:
return .ShortStyle
}
}
public func humanReadableValue() -> String {
if model.datePickerMode == .CountDownTimer {
let t = datePicker.countDownDuration
let date = NSDate(timeIntervalSinceReferenceDate: t)
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)!
calendar.timeZone = NSTimeZone(forSecondsFromGMT: 0)
let components = calendar.components([NSCalendarUnit.Hour, NSCalendarUnit.Minute], fromDate: date)
let hour = components.hour
let minute = components.minute
return String(format: "%02d:%02d", hour, minute)
}
if true {
let date = datePicker.date
//DLog("date: \(date)")
let dateFormatter = NSDateFormatter()
dateFormatter.locale = self.resolveLocale()
dateFormatter.dateStyle = obtainDateStyle(model.datePickerMode)
dateFormatter.timeStyle = obtainTimeStyle(model.datePickerMode)
return dateFormatter.stringFromDate(date)
}
}
public func updateValue() {
detailTextLabel?.text = humanReadableValue()
}
public func setDateWithoutSync(date: NSDate?, animated: Bool) {
DLog("set date \(date), animated \(animated)")
datePicker.setDate(date ?? NSDate(), animated: animated)
updateValue()
}
public func form_didSelectRow(indexPath: NSIndexPath, tableView: UITableView) {
// Hide the datepicker wheel, if it's already visible
// Otherwise show the datepicker
let alreadyFirstResponder = (self.form_firstResponder() != nil)
if alreadyFirstResponder {
tableView.form_firstResponder()?.resignFirstResponder()
tableView.deselectRowAtIndexPath(indexPath, animated: true)
return
}
//DLog("will invoke")
// hide keyboard when the user taps this kind of row
tableView.form_firstResponder()?.resignFirstResponder()
self.becomeFirstResponder()
tableView.deselectRowAtIndexPath(indexPath, animated: true)
//DLog("did invoke")
}
// MARK: UIResponder
public override func canBecomeFirstResponder() -> Bool {
return true
}
public override func becomeFirstResponder() -> Bool {
let result = super.becomeFirstResponder()
updateToolbarButtons()
assignTintColors()
return result
}
public override func resignFirstResponder() -> Bool {
super.resignFirstResponder()
assignDefaultColors()
return true
}
}
|
mit
|
42d5e4b5a7688417e09f67c55659cb99
| 27.530435 | 150 | 0.738647 | 4.098688 | false | false | false | false |
cathandnya/Pixitail
|
pixiViewer/Classes/Widget/WidgetCell.swift
|
1
|
5128
|
//
// WidgetCell.swift
// pixiViewer
//
// Created by nya on 2014/10/14.
//
//
import UIKit
let margin: CGFloat = 1
let defaultImageSize: CGFloat = 75
class WidgetCell: UITableViewCell {
fileprivate var imageViews: [CHCachedImageView] = []
//private var activityBaseView: RoundedRectView
//private var activityView: UIActivityIndicatorView
fileprivate var selectionLayer: CALayer
var context: NSExtensionContext?
required init?(coder aDecoder: NSCoder) {
//activityBaseView = RoundedRectView(frame: CGRectMake(0, 0, 44, 44))
//activityView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.White)
selectionLayer = CALayer()
super.init(coder: aDecoder)
//contentView.addSubview(activityBaseView)
//contentView.addSubview(activityView)
contentView.layer.addSublayer(selectionLayer)
/*
activityBaseView.backgroundColor = UIColor.clearColor()
activityBaseView.color = UIColor.blackColor().colorWithAlphaComponent(0.7)
activityBaseView.radius = 4
activityView.hidesWhenStopped = true;
*/
selectionLayer.backgroundColor = UIColor.black.withAlphaComponent(0.7).cgColor
selectionLayer.isHidden = true;
selectionLayer.zPosition = 10
let gr = UITapGestureRecognizer(target: self, action: #selector(WidgetCell.tapAction(_:)))
self.contentView.addGestureRecognizer(gr)
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
class func heightForWidth(_ w: CGFloat) -> CGFloat {
return floor(w / CGFloat(Int(w / defaultImageSize)))
}
fileprivate var cols: Int {
get {
return Int(self.frame.size.width / imageSize)
}
}
fileprivate var imageSize: CGFloat {
get {
return WidgetCell.heightForWidth(self.frame.size.width)
}
}
var entries: Entries? {
didSet {
setNeedsLayout()
}
}
override func layoutSubviews() {
super.layoutSubviews()
var count = 0
if let es = entries {
count = min(cols, es.list.count)
}
if count < imageViews.count {
while imageViews.count != count {
imageViews.last!.removeFromSuperview()
imageViews.removeLast()
}
}
if count > 0 {
for i in 0...count-1 {
if let e = entries?.list[i] as? Entry {
var v: CHCachedImageView
if i < imageViews.count {
v = imageViews[i]
} else {
v = CHCachedImageView()
v.backgroundColor = UIColor.white.withAlphaComponent(0.2)
v.contentMode = UIViewContentMode.scaleAspectFill
v.clipsToBounds = true
v.referer = "http://www.pixiv.net/"
contentView.addSubview(v)
//contentView.insertSubview(v, belowSubview: activityBaseView)
imageViews.append(v)
}
v.url = URL(string: e.thumbnail_url)
}
}
}
let size = imageSize
var r = CGRect(x: 0, y: 0, width: size, height: size)
for v in imageViews {
var f = r;
if v != imageViews.last {
f.size.width -= margin
}
v.frame = f
r.origin.x += r.size.width
}
/*
activityBaseView.center = contentView.center
activityView.center = contentView.center
if let es = entries {
if es.isLoading && !activityView.isAnimating() {
activityView.startAnimating();
} else if !es.isLoading && activityView.isAnimating() {
activityView.stopAnimating();
}
activityBaseView.hidden = !es.isLoading
} else {
if activityView.isAnimating() {
activityView.stopAnimating();
}
activityBaseView.hidden = true
}
*/
selectionLayer.isHidden = true;
}
func tapAction(_ sender: UITapGestureRecognizer) {
let loc = sender.location(in: contentView)
for v in imageViews {
if v.frame.contains(loc) {
if let idx = imageViews.index(of: v) {
CATransaction.begin()
CATransaction.setDisableActions(true)
selectionLayer.frame = v.frame
selectionLayer.isHidden = false
CATransaction.commit()
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(NSEC_PER_SEC / 10)) / Double(NSEC_PER_SEC)) {
if let e = self.entries?.list[idx] as? Entry {
self.selected(e)
}
}
}
}
}
}
func selected(_ entry: Entry) {
var url: URL?
if entry.service_name == "pixiv" {
url = URL(string: "pixitail://org.cathand.pixitail/pixiv/\(entry.illust_id)")
} else if entry.service_name == "TINAMI" {
url = URL(string: "illustail://org.cathand.illustail/tinami/\(entry.illust_id)")
} else if entry.service_name == "Danbooru" && entry.other_info != nil {
if let defaults = UserDefaults(suiteName: "group.org.cathand.illustail") {
defaults.set(entry.other_info, forKey: "danbooru_selected_post")
defaults.synchronize()
url = URL(string: "illustail://org.cathand.illustail/danbooru/\(entry.illust_id)")
}
} else if entry.service_name == "Seiga" {
url = URL(string: "illustail://org.cathand.illustail/seiga/\(entry.illust_id)")
}
if let u = url {
self.context?.open(u, completionHandler: nil)
}
}
}
|
mit
|
1839c828180afb81ba2f79e99108efba
| 26.132275 | 124 | 0.677847 | 3.49081 | false | false | false | false |
indragiek/DominantColor
|
DominantColor/Mac/AppDelegate.swift
|
1
|
1850
|
//
// AppDelegate.swift
// DominantColor
//
// Created by Indragie on 12/18/14.
// Copyright (c) 2014 Indragie Karunaratne. All rights reserved.
//
import Cocoa
import DominantColor
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate, DragAndDropImageViewDelegate {
@IBOutlet weak var window: NSWindow!
@IBOutlet weak var box1: NSBox!
@IBOutlet weak var box2: NSBox!
@IBOutlet weak var box3: NSBox!
@IBOutlet weak var box4: NSBox!
@IBOutlet weak var box5: NSBox!
@IBOutlet weak var box6: NSBox!
@IBOutlet weak var imageView: DragAndDropImageView!
var image: NSImage?
func applicationDidFinishLaunching(aNotification: NSNotification) {
}
// MARK: DragAndDropImageViewDelegate
@IBAction func runBenchmark(_ sender: NSButton) {
if let image = image {
let nValues: [Int] = [100, 1000, 2000, 5000, 10000]
let CGImage = image.cgImage(forProposedRect: nil, context: nil, hints: nil)!
for n in nValues {
let ns = dispatch_benchmark(5) {
_ = dominantColorsInImage(CGImage, maxSampledPixels: n)
return
}
print("n = \(n) averaged \(ns/1000000) ms")
}
}
}
func dragAndDropImageView(imageView: DragAndDropImageView, droppedImage image: NSImage?) {
if let image = image {
imageView.image = image
self.image = image
let colors = image.dominantColors()
let boxes = [box1, box2, box3, box4, box5, box6]
for box in boxes {
box?.fillColor = .clear
}
for i in 0..<min(colors.count, boxes.count) {
boxes[i]?.fillColor = colors[i]
}
}
}
}
|
mit
|
62a6b69b6f2a35900fcd69801054a767
| 28.83871 | 94 | 0.58 | 4.490291 | false | false | false | false |
adrfer/swift
|
stdlib/public/core/StringUTF8.swift
|
1
|
14275
|
//===--- StringUTF8.swift - A UTF8 view of _StringCore --------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// _StringCore currently has three representations: Native ASCII,
// Native UTF-16, and Opaque Cocoa. Expose each of these as UTF-8 in a
// way that will hopefully be efficient to traverse
//
//===----------------------------------------------------------------------===//
extension _StringCore {
/// An integral type that holds a sequence of UTF-8 code units, starting in
/// its low byte.
public typealias UTF8Chunk = UInt64
/// Encode text starting at `i` as UTF-8. Returns a pair whose first
/// element is the index of the text following whatever got encoded,
/// and the second element contains the encoded UTF-8 starting in its
/// low byte. Any unused high bytes in the result will be set to
/// 0xFF.
@warn_unused_result
func _encodeSomeUTF8(i: Int) -> (Int, UTF8Chunk) {
_sanityCheck(i <= count)
if _fastPath(elementWidth == 1) {
// How many UTF-16 code units might we use before we've filled up
// our UTF8Chunk with UTF-8 code units?
let utf16Count = min(sizeof(UTF8Chunk.self), count - i)
var result: UTF8Chunk = ~0 // Start with all bits set
_memcpy(
dest: UnsafeMutablePointer(Builtin.addressof(&result)),
src: UnsafeMutablePointer(startASCII + i),
size: numericCast(utf16Count))
return (i + utf16Count, result)
} else if _fastPath(!_baseAddress._isNull) {
return _encodeSomeContiguousUTF16AsUTF8(i)
} else {
#if _runtime(_ObjC)
return _encodeSomeNonContiguousUTF16AsUTF8(i)
#else
_sanityCheckFailure("_encodeSomeUTF8: Unexpected cocoa string")
#endif
}
}
/// Helper for `_encodeSomeUTF8`, above. Handles the case where the
/// storage is contiguous UTF-16.
@warn_unused_result
func _encodeSomeContiguousUTF16AsUTF8(i: Int) -> (Int, UTF8Chunk) {
_sanityCheck(elementWidth == 2)
_sanityCheck(!_baseAddress._isNull)
let storage = UnsafeBufferPointer(start: startUTF16, count: self.count)
return _transcodeSomeUTF16AsUTF8(storage, i)
}
#if _runtime(_ObjC)
/// Helper for `_encodeSomeUTF8`, above. Handles the case where the
/// storage is non-contiguous UTF-16.
@warn_unused_result
func _encodeSomeNonContiguousUTF16AsUTF8(i: Int) -> (Int, UTF8Chunk) {
_sanityCheck(elementWidth == 2)
_sanityCheck(_baseAddress._isNull)
let storage = _CollectionOf<Int, UInt16>(
startIndex: 0, endIndex: self.count) {
(i: Int) -> UInt16 in
return _cocoaStringSubscript(self, i)
}
return _transcodeSomeUTF16AsUTF8(storage, i)
}
#endif
}
extension String {
/// A collection of UTF-8 code units that encodes a `String` value.
public struct UTF8View : CollectionType, _Reflectable, CustomStringConvertible,
CustomDebugStringConvertible {
internal let _core: _StringCore
internal let _startIndex: Index
internal let _endIndex: Index
init(_ _core: _StringCore) {
self._core = _core
self._endIndex = Index(_core, _core.endIndex, Index._emptyBuffer)
if _fastPath(_core.count != 0) {
let (_, buffer) = _core._encodeSomeUTF8(0)
self._startIndex = Index(_core, 0, buffer)
} else {
self._startIndex = self._endIndex
}
}
init(_ _core: _StringCore, _ s: Index, _ e: Index) {
self._core = _core
self._startIndex = s
self._endIndex = e
}
/// A position in a `String.UTF8View`.
public struct Index : ForwardIndexType {
internal typealias Buffer = _StringCore.UTF8Chunk
init(_ _core: _StringCore, _ _coreIndex: Int,
_ _buffer: Buffer) {
self._core = _core
self._coreIndex = _coreIndex
self._buffer = _buffer
_sanityCheck(_coreIndex >= 0)
_sanityCheck(_coreIndex <= _core.count)
}
/// Returns the next consecutive value after `self`.
///
/// - Requires: The next value is representable.
@warn_unused_result
public func successor() -> Index {
let currentUnit = UTF8.CodeUnit(truncatingBitPattern: _buffer)
let hiNibble = currentUnit >> 4
// Map the high nibble of the current code unit into the
// amount by which to increment the utf16 index. Only when
// the high nibble is 1111 do we have a surrogate pair.
let u16Increments = Int(bitPattern:
// 1111 1110 1101 1100 1011 1010 1001 1000 0111 0110 0101 0100 0011 0010 0001 0000
0b10___01___01___01___00___00___00___00___01___01___01___01___01___01___01___01)
let increment = (u16Increments >> numericCast(hiNibble << 1)) & 0x3
let nextCoreIndex = _coreIndex &+ increment
let nextBuffer = Index._nextBuffer(_buffer)
// if the nextBuffer is non-empty, we have all we need
if _fastPath(nextBuffer != Index._emptyBuffer) {
return Index(_core, nextCoreIndex, nextBuffer)
}
// If the underlying UTF16 isn't exhausted, fill a new buffer
else if _fastPath(nextCoreIndex < _core.endIndex) {
let (_, freshBuffer) = _core._encodeSomeUTF8(nextCoreIndex)
return Index(_core, nextCoreIndex, freshBuffer)
}
else {
// Produce the endIndex
_precondition(
nextCoreIndex == _core.endIndex,
"Can't increment past endIndex of String.UTF8View")
return Index(_core, nextCoreIndex, nextBuffer)
}
}
/// True iff the index is at the end of its view or if the next
/// byte begins a new UnicodeScalar.
internal var _isOnUnicodeScalarBoundary : Bool {
let next = UTF8.CodeUnit(truncatingBitPattern: _buffer)
return UTF8._numTrailingBytes(next) != 4 || _isAtEnd
}
/// True iff the index is at the end of its view
internal var _isAtEnd : Bool {
return _buffer == Index._emptyBuffer
&& _coreIndex == _core.endIndex
}
/// The value of the buffer when it is empty
internal static var _emptyBuffer: Buffer {
return ~0
}
/// A Buffer value with the high byte set
internal static var _bufferHiByte: Buffer {
return 0xFF << numericCast((sizeof(Buffer.self) &- 1) &* 8)
}
/// Consume a byte of the given buffer: shift out the low byte
/// and put FF in the high byte
internal static func _nextBuffer(thisBuffer: Buffer) -> Buffer {
return (thisBuffer >> 8) | _bufferHiByte
}
/// The underlying buffer we're presenting as UTF8
internal let _core: _StringCore
/// The position of `self`, rounded up to the nearest unicode
/// scalar boundary, in the underlying UTF16.
internal let _coreIndex: Int
/// If `self` is at the end of its `_core`, has the value `_endBuffer`.
/// Otherwise, the low byte contains the value of
internal let _buffer: Buffer
}
/// The position of the first code unit if the `String` is
/// non-empty; identical to `endIndex` otherwise.
public var startIndex: Index {
return self._startIndex
}
/// The "past the end" position.
///
/// `endIndex` is not a valid argument to `subscript`, and is always
/// reachable from `startIndex` by zero or more applications of
/// `successor()`.
public var endIndex: Index {
return self._endIndex
}
/// Access the element at `position`.
///
/// - Requires: `position` is a valid position in `self` and
/// `position != endIndex`.
public subscript(position: Index) -> UTF8.CodeUnit {
let result: UTF8.CodeUnit = numericCast(position._buffer & 0xFF)
_precondition(result != 0xFF, "cannot subscript using endIndex")
return result
}
/// Access the elements delimited by the given half-open range of
/// indices.
///
/// - Complexity: O(1) unless bridging from Objective-C requires an
/// O(N) conversion.
public subscript(subRange: Range<Index>) -> UTF8View {
return UTF8View(_core, subRange.startIndex, subRange.endIndex)
}
/// Returns a mirror that reflects `self`.
@warn_unused_result
public func _getMirror() -> _MirrorType {
return _UTF8ViewMirror(self)
}
public var description: String {
return String._fromCodeUnitSequenceWithRepair(UTF8.self, input: self).0
}
public var debugDescription: String {
return "UTF8View(\(self.description.debugDescription))"
}
}
/// A UTF-8 encoding of `self`.
public var utf8: UTF8View {
return UTF8View(self._core)
}
public var _contiguousUTF8: UnsafeMutablePointer<UTF8.CodeUnit> {
return _core.elementWidth == 1 ? _core.startASCII : nil
}
/// A contiguously-stored nul-terminated UTF-8 representation of
/// `self`.
///
/// To access the underlying memory, invoke
/// `withUnsafeBufferPointer` on the `ContiguousArray`.
public var nulTerminatedUTF8: ContiguousArray<UTF8.CodeUnit> {
var result = ContiguousArray<UTF8.CodeUnit>()
result.reserveCapacity(utf8.count + 1)
result += utf8
result.append(0)
return result
}
/// Construct the `String` corresponding to the given sequence of
/// UTF-8 code units. If `utf8` contains unpaired surrogates, the
/// result is `nil`.
public init?(_ utf8: UTF8View) {
let wholeString = String(utf8._core)
if let start = utf8.startIndex.samePositionIn(wholeString),
let end = utf8.endIndex.samePositionIn(wholeString) {
self = wholeString[start..<end]
return
}
return nil
}
/// The index type for subscripting a `String`'s `.utf8` view.
public typealias UTF8Index = UTF8View.Index
}
@warn_unused_result
public func == (
lhs: String.UTF8View.Index,
rhs: String.UTF8View.Index
) -> Bool {
// If the underlying UTF16 index differs, they're unequal
if lhs._coreIndex != rhs._coreIndex {
return false
}
// Match up bytes in the buffer
var buffer = (lhs._buffer, rhs._buffer)
var isContinuation: Bool
repeat {
let unit = (
UTF8.CodeUnit(truncatingBitPattern: buffer.0),
UTF8.CodeUnit(truncatingBitPattern: buffer.1))
isContinuation = UTF8.isContinuation(unit.0)
if !isContinuation {
// We don't check for unit equality in this case because one of
// the units might be an 0xFF read from the end of the buffer.
return !UTF8.isContinuation(unit.1)
}
// Continuation bytes must match exactly
else if unit.0 != unit.1 {
return false
}
// Move the buffers along.
buffer = (
String.UTF8Index._nextBuffer(buffer.0),
String.UTF8Index._nextBuffer(buffer.1))
}
while true
}
// Index conversions
extension String.UTF8View.Index {
internal init(_ core: _StringCore, _utf16Offset: Int) {
let (_, buffer) = core._encodeSomeUTF8(_utf16Offset)
self.init(core, _utf16Offset, buffer)
}
/// Construct the position in `utf8` that corresponds exactly to
/// `utf16Index`. If no such position exists, the result is `nil`.
///
/// - Requires: `utf8Index` is an element of
/// `String(utf16)!.utf8.indices`.
public init?(_ utf16Index: String.UTF16Index, within utf8: String.UTF8View) {
let utf16 = String.UTF16View(utf8._core)
if utf16Index != utf16.startIndex
&& utf16Index != utf16.endIndex {
_precondition(
utf16Index >= utf16.startIndex
&& utf16Index <= utf16.endIndex,
"Invalid String.UTF16Index for this UTF-8 view")
// Detect positions that have no corresponding index. Note that
// we have to check before and after, because an unpaired
// surrogate will be decoded as a single replacement character,
// thus making the corresponding position valid in UTF8.
if UTF16.isTrailSurrogate(utf16[utf16Index])
&& UTF16.isLeadSurrogate(utf16[utf16Index.predecessor()]) {
return nil
}
}
self.init(utf8._core, _utf16Offset: utf16Index._offset)
}
/// Construct the position in `utf8` that corresponds exactly to
/// `unicodeScalarIndex`.
///
/// - Requires: `unicodeScalarIndex` is an element of
/// `String(utf8)!.unicodeScalars.indices`.
public init(
_ unicodeScalarIndex: String.UnicodeScalarIndex,
within utf8: String.UTF8View
) {
self.init(utf8._core, _utf16Offset: unicodeScalarIndex._position)
}
/// Construct the position in `utf8` that corresponds exactly to
/// `characterIndex`.
///
/// - Requires: `characterIndex` is an element of
/// `String(utf8)!.indices`.
public init(_ characterIndex: String.Index, within utf8: String.UTF8View) {
self.init(utf8._core, _utf16Offset: characterIndex._base._position)
}
/// Return the position in `utf16` that corresponds exactly
/// to `self`, or if no such position exists, `nil`.
///
/// - Requires: `self` is an element of `String(utf16)!.utf8.indices`.
@warn_unused_result
public func samePositionIn(
utf16: String.UTF16View
) -> String.UTF16View.Index? {
return String.UTF16View.Index(self, within: utf16)
}
/// Return the position in `unicodeScalars` that corresponds exactly
/// to `self`, or if no such position exists, `nil`.
///
/// - Requires: `self` is an element of
/// `String(unicodeScalars).utf8.indices`.
@warn_unused_result
public func samePositionIn(
unicodeScalars: String.UnicodeScalarView
) -> String.UnicodeScalarIndex? {
return String.UnicodeScalarIndex(self, within: unicodeScalars)
}
/// Return the position in `characters` that corresponds exactly
/// to `self`, or if no such position exists, `nil`.
///
/// - Requires: `self` is an element of `characters.utf8.indices`.
@warn_unused_result
public func samePositionIn(
characters: String
) -> String.Index? {
return String.Index(self, within: characters)
}
}
|
apache-2.0
|
851cff6d115a3c4d6f4f73afee37d9ce
| 33.564165 | 91 | 0.644553 | 4.060011 | false | false | false | false |
XSega/Words
|
Words/Scenes/Trainings/ListeningTraining/ListeningTrainingInteractor.swift
|
1
|
3070
|
//
// ListeningTrainingInteractor.swift
// Words
//
// Created by Sergey Ilyushin on 30/07/2017.
// Copyright (c) 2017 Sergey Ilyushin. All rights reserved.
//
import UIKit
protocol IListeningTrainingInteractor {
func start()
func checkTranslation(text: String?)
func skipMeaning()
func listenAgain()
}
class ListeningTrainingInteractor: IListeningTrainingInteractor, ITrainingDataStore {
var presenter: IListeningTrainingPresenter!
// MARK: Training vars
var meanings: [Meaning]!
var mistakes: Int = 0
var words: Int = 0
var learnedIdentifiers = [Int]()
// MARK: Private vars
fileprivate var currentMeaningIndex: Int = 0
// MARK: IEngRuTrainingInteractor
func start() {
currentMeaningIndex = 0
mistakes = 0
words = 0
learnedIdentifiers.removeAll()
presentCurrentMeaning()
}
func finish() {
currentMeaningIndex = 0
presenter.presentFinish()
}
func checkTranslation(text: String?) {
let meaning = meanings[currentMeaningIndex]
guard let text = text, text != "" else {
didSkipSelection(meaning: meaning)
return
}
if meaning.text.lowercased() == text.lowercased() {
didCorrectSelection(meaning: meaning)
} else {
didWrongSelection(meaning: meaning, wrongText: text)
}
}
func listenAgain() {
let meaning = meanings[currentMeaningIndex]
presenter.presentMeaningSound(meaning: meaning)
}
func skipMeaning(){
let meaning = meanings[currentMeaningIndex]
didSkipSelection(meaning: meaning)
}
// MARK: Private func
fileprivate func didCorrectSelection(meaning: Meaning) {
presenter.presentCorrectAlert(meaning: meaning)
learnedIdentifiers.append(meaning.identifier)
DispatchQueue.main.asyncAfter(deadline: .now() + 2) { [unowned self] in
self.nextPair()
}
}
fileprivate func didWrongSelection(meaning: Meaning, wrongText: String) {
mistakes += 1
presenter.presentWrongAlert(meaning: meaning, wrongText: wrongText)
DispatchQueue.main.asyncAfter(deadline: .now() + 2) { [unowned self] in
self.nextPair()
}
}
fileprivate func didSkipSelection(meaning: Meaning) {
mistakes += 1
presenter.presentSkipAlert(meaning: meaning)
DispatchQueue.main.asyncAfter(deadline: .now() + 2) { [unowned self] in
self.nextPair()
}
}
fileprivate func nextPair() {
currentMeaningIndex += 1
guard currentMeaningIndex < meanings.count else {
finish()
return
}
presentCurrentMeaning()
}
fileprivate func presentCurrentMeaning() {
let meaning = meanings[currentMeaningIndex]
presenter.present(meaning: meaning)
words += 1
}
}
|
mit
|
be55e5648f47f7546fc25b0aed27263d
| 25.239316 | 85 | 0.60684 | 4.75969 | false | false | false | false |
adrfer/swift
|
test/Driver/subcommands.swift
|
1
|
1880
|
// Check that each of 'swift', 'swift repl', 'swift run' invoke the REPL.
//
// REQUIRES: swift_interpreter
//
// RUN: %swift_driver_plain -### 2>&1 | FileCheck -check-prefix=CHECK-SWIFT-INVOKES-REPL %s
// RUN: %swift_driver_plain run -### 2>&1 | FileCheck -check-prefix=CHECK-SWIFT-INVOKES-REPL %s
// RUN: %swift_driver_plain repl -### 2>&1 | FileCheck -check-prefix=CHECK-SWIFT-INVOKES-REPL %s
//
// CHECK-SWIFT-INVOKES-REPL: {{.*}}/swift -frontend -repl
// Check that 'swift -', 'swift t.swift', and 'swift /path/to/file' invoke the interpreter
// (for shebang line use). We have to run these since we can't get the driver to
// dump what it is doing and test the argv[1] processing.
//
// RUN: rm -rf %t.dir
// RUN: mkdir -p %t.dir/subpath
// RUN: echo "print(\"exec: \" + __FILE__)" > %t.dir/stdin
// RUN: echo "print(\"exec: \" + __FILE__)" > %t.dir/t.swift
// RUN: echo "print(\"exec: \" + __FILE__)" > %t.dir/subpath/build
// RUN: cd %t.dir && %swift_driver_plain - < %t.dir/stdin -### 2>&1 | FileCheck -check-prefix=CHECK-SWIFT-STDIN-INVOKES-INTERPRETER %s
// CHECK-SWIFT-STDIN-INVOKES-INTERPRETER: exec: <stdin>
// RUN: cd %t.dir && %swift_driver_plain t.swift -### 2>&1 | FileCheck -check-prefix=CHECK-SWIFT-SUFFIX-INVOKES-INTERPRETER %s
// CHECK-SWIFT-SUFFIX-INVOKES-INTERPRETER: exec: t.swift
// RUN: cd %t.dir && %swift_driver_plain subpath/build -### 2>&1 | FileCheck -check-prefix=CHECK-SWIFT-PATH-INVOKES-INTERPRETER %s
// CHECK-SWIFT-PATH-INVOKES-INTERPRETER: exec: subpath/build
// Check that 'swift foo' invokes 'swift-foo'.
//
// RUN: rm -rf %t.dir
// RUN: mkdir -p %t.dir
// RUN: echo "#!/bin/sh" > %t.dir/swift-foo
// RUN: echo "echo \"exec: \$0\"" >> %t.dir/swift-foo
// RUN: chmod +x %t.dir/swift-foo
// RUN: env PATH=%t.dir %swift_driver_plain foo | FileCheck -check-prefix=CHECK-SWIFT-SUBCOMMAND %s
// CHECK-SWIFT-SUBCOMMAND: exec: {{.*}}/swift-foo
|
apache-2.0
|
cd927440b674f9bac58ec3e6dcea9b8a
| 49.810811 | 134 | 0.657447 | 2.979398 | false | false | false | false |
HIIT/JustUsed
|
JustUsed/DiMe Data/HistoryManager.swift
|
1
|
4689
|
//
// Copyright (c) 2015 Aalto University
//
// 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.
// The history manager is a singleton and keeps track of all history events happening trhough the application.
// This includes, for example, timers which trigger at predefined intervals (such as closing events after a
// specific amount of time has passed, assuming that the user went away from keyboard).
// See https://github.com/HIIT/PeyeDF/wiki/Data-Format for more information
import Foundation
import Quartz
class HistoryManager: NSObject {
/// Set to true to prevent automatic connection checks
static var forceDisconnect = false
/// Returns a shared instance of this class. This is the designed way of accessing the history manager.
static let sharedManager = HistoryManager()
/// DiMe connection is checked every time this amount of second passes
static let kConnectionCheckTime = 5.0
/// Is true if there is a connection to DiMe, and can be used
fileprivate var dimeAvailable: Bool = false
// MARK: - Initialization
override init() {
super.init()
let connectTimer = Timer(timeInterval: HistoryManager.kConnectionCheckTime, target: self, selector: #selector(connectionTimerCheck(_:)), userInfo: nil, repeats: true)
RunLoop.current.add(connectTimer, forMode: RunLoopMode.commonModes)
}
/// Callback for connection timer
@objc func connectionTimerCheck(_ aTimer: Timer) {
if !HistoryManager.forceDisconnect {
DiMeSession.dimeConnect()
}
}
// MARK: - External functions
}
// MARK: - Protocol implementations
/// Protocol implementations for browser and document history updates
extension HistoryManager: RecentDocumentUpdateDelegate, BrowserHistoryUpdateDelegate {
func newHistoryItems(_ newURLs: [BrowserHistItem]) {
for newURL in newURLs {
let sendingToBrowser = UserDefaults.standard.value(forKey: JustUsedConstants.prefSendSafariHistory) as! Bool
if !newURL.excludedFromDiMe && sendingToBrowser {
let infoElem = DocumentInformationElement(fromSafariHist: newURL)
let event = DesktopEvent(infoElem: infoElem, ofType: TrackingType.browser(newURL.browser), withDate: newURL.date, andLocation: newURL.location)
DiMePusher.sendToDiMe(event)
}
}
}
func newRecentDocument(_ newItem: RecentDocItem) {
// do all fetching on the utility queue (especially since pdfDoc.getMetadata() blocks)
DispatchQueue.global(qos: DispatchQoS.QoSClass.utility).async {
let infoElem = DocumentInformationElement(fromRecentDoc: newItem)
if infoElem.isPdf {
let docUrl = URL(fileURLWithPath: newItem.path)
if let pdfDoc = PDFDocument(url: docUrl) {
// try to get metadata from crossref, otherwise get title from pdf's metadata, and as a last resort guess it
if let json = pdfDoc.autoCrossref() {
infoElem.convertToSciDoc(fromCrossRef: json, keywords: pdfDoc.getKeywordsAsArray())
} else if let tit = pdfDoc.getTitle() {
infoElem.title = tit
} else if let tit = pdfDoc.guessTitle() {
infoElem.title = tit
}
}
}
let event = DesktopEvent(infoElem: infoElem, ofType: TrackingType.spotlight, withDate: newItem.lastAccessDate, andLocation: newItem.location)
DiMePusher.sendToDiMe(event)
}
}
}
|
mit
|
1ad163c1486668b57a4c336efbe12df2
| 44.086538 | 174 | 0.684368 | 4.731584 | false | false | false | false |
devpunk/punknote
|
punknote/View/Share/VShareCellScaleCell.swift
|
1
|
4566
|
import UIKit
class VShareCellScaleCell:UICollectionViewCell
{
private weak var labelTitle:UILabel!
private weak var labelDescr:UILabel!
private weak var viewCircle:UIView!
private weak var layoutCircleLeft:NSLayoutConstraint!
private weak var layoutCircleTop:NSLayoutConstraint!
private let kCircleSize:CGFloat = 45
private let kDescrHeight:CGFloat = 25
override init(frame:CGRect)
{
super.init(frame:frame)
clipsToBounds = true
backgroundColor = UIColor.clear
let labelTitle:UILabel = UILabel()
labelTitle.isUserInteractionEnabled = false
labelTitle.translatesAutoresizingMaskIntoConstraints = false
labelTitle.font = UIFont.regular(size:20)
labelTitle.textAlignment = NSTextAlignment.center
labelTitle.backgroundColor = UIColor.clear
self.labelTitle = labelTitle
let labelDescr:UILabel = UILabel()
labelDescr.isUserInteractionEnabled = false
labelDescr.translatesAutoresizingMaskIntoConstraints = false
labelDescr.font = UIFont.regular(size:13)
labelDescr.textAlignment = NSTextAlignment.center
labelDescr.backgroundColor = UIColor.clear
self.labelDescr = labelDescr
let viewCircle:UIView = UIView()
viewCircle.translatesAutoresizingMaskIntoConstraints = false
viewCircle.clipsToBounds = true
viewCircle.isUserInteractionEnabled = false
viewCircle.backgroundColor = UIColor.punkPurple
viewCircle.layer.cornerRadius = kCircleSize / 2.0
self.viewCircle = viewCircle
addSubview(labelDescr)
addSubview(viewCircle)
addSubview(labelTitle)
NSLayoutConstraint.equals(
view:labelTitle,
toView:self)
layoutCircleTop = NSLayoutConstraint.topToTop(
view:viewCircle,
toView:self)
layoutCircleLeft = NSLayoutConstraint.leftToLeft(
view:viewCircle,
toView:self)
NSLayoutConstraint.size(
view:viewCircle,
constant:kCircleSize)
NSLayoutConstraint.bottomToBottom(
view:labelDescr,
toView:self)
NSLayoutConstraint.height(
view:labelDescr,
constant:kDescrHeight)
NSLayoutConstraint.equalsHorizontal(
view:labelDescr,
toView:self)
}
required init?(coder:NSCoder)
{
return nil
}
override func layoutSubviews()
{
let width:CGFloat = bounds.maxX
let height:CGFloat = bounds.maxY
let remainWidth:CGFloat = width - kCircleSize
let remainHeight:CGFloat = height - kCircleSize
let marginLeft:CGFloat = remainWidth / 2.0
let marginTop:CGFloat = remainHeight / 2.0
layoutCircleLeft.constant = marginLeft
layoutCircleTop.constant = marginTop
super.layoutSubviews()
}
override var isSelected:Bool
{
didSet
{
hover()
}
}
override var isHighlighted:Bool
{
didSet
{
hover()
}
}
//MARK: private
private func hover()
{
if isSelected || isHighlighted
{
labelTitle.textColor = UIColor.white
labelDescr.textColor = UIColor.black
viewCircle.isHidden = false
}
else
{
labelTitle.textColor = UIColor(white:0.75, alpha:1)
labelDescr.textColor = UIColor(white:0.6, alpha:1)
viewCircle.isHidden = true
}
}
private func printDescr(scale:CGFloat)
{
let width:CGFloat = MShare.widthForScale(scale:scale)
let height:CGFloat = MShare.heightForScale(scale:scale)
let widthNumber:NSNumber = width as NSNumber
let heightNumber:NSNumber = height as NSNumber
let stringDescr:String = String(
format:NSLocalizedString("VShareCellScaleCell_labelDescr", comment:""),
widthNumber,
heightNumber)
labelDescr.text = stringDescr
}
//MARK: public
func config(scale:CGFloat)
{
let scaleNumber:NSNumber = scale as NSNumber
let stringTitle:String = String(
format:NSLocalizedString("VShareCellScaleCell_labelTitle", comment:""),
scaleNumber)
labelTitle.text = stringTitle
printDescr(scale:scale)
hover()
}
}
|
mit
|
1c01dc33115455262716e6e58e06cd74
| 29.238411 | 83 | 0.620018 | 5.334112 | false | false | false | false |
nathanwhy/BlurActionSheet
|
BlurActionSheet/BlurActionSheetCell.swift
|
1
|
1873
|
//
// BlurActionSheetCell.swift
// BlurActionSheetDemo
//
// Created by nathan on 15/4/23.
// Copyright (c) 2015年 nathan. All rights reserved.
//
import UIKit
class BlurActionSheetCell: UITableViewCell {
private let underLineColor = UIColor(white: 0.5, alpha: 0.7)
var underLineView:UIView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
underLineView = UIView()
underLineView.backgroundColor = underLineColor
contentView.addSubview(underLineView)
backgroundView = nil
backgroundColor = UIColor.clear()
selectedBackgroundView = UIView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
let width = self.bounds.size.width
let margin:CGFloat = 20
if (underLineView.frame.size.height != 1){
underLineView.frame = CGRect(x: margin, y: 0, width: width - margin * 2, height: 1)
}
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
if (selected) {
self.textLabel?.textColor = UIColor.lightGray()
underLineView.backgroundColor = underLineColor
}
}
override func setHighlighted(_ highlighted: Bool, animated: Bool) {
super.setHighlighted(highlighted, animated: animated)
if (highlighted){
self.textLabel?.textColor = UIColor.lightGray()
underLineView.backgroundColor = underLineColor
}
}
}
|
mit
|
753c1004106e466b646d846da5a970af
| 27.348485 | 95 | 0.626403 | 4.897906 | false | false | false | false |
JGiola/swift-corelibs-foundation
|
Foundation/XMLParser.swift
|
1
|
36570
|
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
// It is necessary to explicitly cast strlen to UInt to match the type
// of prefixLen because currently, strlen (and other functions that
// rely on swift_ssize_t) use the machine word size (int on 32 bit and
// long in on 64 bit). I've filed a bug at bugs.swift.org:
// https://bugs.swift.org/browse/SR-314
#if os(macOS) || os(iOS)
import Darwin
#elseif os(Linux) || CYGWIN
import Glibc
#endif
import CoreFoundation
extension XMLParser {
public enum ExternalEntityResolvingPolicy : UInt {
case never // default
case noNetwork
case sameOriginOnly //only applies to NSXMLParser instances initialized with -initWithContentsOfURL:
case always
}
}
extension _CFXMLInterface {
var parser: XMLParser {
return unsafeBitCast(self, to: XMLParser.self)
}
}
extension XMLParser {
internal var interface: _CFXMLInterface {
return unsafeBitCast(self, to: _CFXMLInterface.self)
}
}
private func UTF8STRING(_ bytes: UnsafePointer<UInt8>?) -> String? {
guard let bytes = bytes else {
return nil
}
if let (str, _) = String.decodeCString(bytes, as: UTF8.self,
repairingInvalidCodeUnits: false) {
return str
}
return nil
}
internal func _NSXMLParserCurrentParser() -> _CFXMLInterface? {
if let parser = XMLParser.currentParser() {
return parser.interface
} else {
return nil
}
}
internal func _NSXMLParserExternalEntityWithURL(_ interface: _CFXMLInterface, urlStr: UnsafePointer<Int8>, identifier: UnsafePointer<Int8>, context: _CFXMLInterfaceParserContext, originalLoaderFunction: _CFXMLInterfaceExternalEntityLoader) -> _CFXMLInterfaceParserInput? {
let parser = interface.parser
let policy = parser.externalEntityResolvingPolicy
var a: URL?
if let allowedEntityURLs = parser.allowedExternalEntityURLs {
if let url = URL(string: String(describing: urlStr)) {
a = url
if let scheme = url.scheme {
if scheme == "file" {
a = URL(fileURLWithPath: url.path)
}
}
}
if let url = a {
let allowed = allowedEntityURLs.contains(url)
if allowed || policy != .sameOriginOnly {
if allowed {
return originalLoaderFunction(urlStr, identifier, context)
}
}
}
}
switch policy {
case .sameOriginOnly:
guard let url = parser._url else { break }
if a == nil {
a = URL(string: String(describing: urlStr))
}
guard let aUrl = a else { break }
var matches: Bool
if let aHost = aUrl.host, let host = url.host {
matches = host == aHost
} else {
return nil
}
if matches {
if let aPort = aUrl.port, let port = url.port {
matches = port == aPort
} else {
return nil
}
}
if matches {
if let aScheme = aUrl.scheme, let scheme = url.scheme {
matches = scheme == aScheme
} else {
return nil
}
}
if !matches {
return nil
}
case .always:
break
case .never:
return nil
case .noNetwork:
return _CFXMLInterfaceNoNetExternalEntityLoader(urlStr, identifier, context)
}
return originalLoaderFunction(urlStr, identifier, context)
}
internal func _NSXMLParserGetContext(_ ctx: _CFXMLInterface) -> _CFXMLInterfaceParserContext {
return ctx.parser._parserContext!
}
internal func _NSXMLParserInternalSubset(_ ctx: _CFXMLInterface, name: UnsafePointer<UInt8>, ExternalID: UnsafePointer<UInt8>, SystemID: UnsafePointer<UInt8>) -> Void {
_CFXMLInterfaceSAX2InternalSubset(ctx.parser._parserContext, name, ExternalID, SystemID)
}
internal func _NSXMLParserIsStandalone(_ ctx: _CFXMLInterface) -> Int32 {
return _CFXMLInterfaceIsStandalone(ctx.parser._parserContext)
}
internal func _NSXMLParserHasInternalSubset(_ ctx: _CFXMLInterface) -> Int32 {
return _CFXMLInterfaceHasInternalSubset(ctx.parser._parserContext)
}
internal func _NSXMLParserHasExternalSubset(_ ctx: _CFXMLInterface) -> Int32 {
return _CFXMLInterfaceHasExternalSubset(ctx.parser._parserContext)
}
internal func _NSXMLParserGetEntity(_ ctx: _CFXMLInterface, name: UnsafePointer<UInt8>) -> _CFXMLInterfaceEntity? {
let parser = ctx.parser
let context = _NSXMLParserGetContext(ctx)
var entity = _CFXMLInterfaceGetPredefinedEntity(name)
if entity == nil {
entity = _CFXMLInterfaceSAX2GetEntity(context, name)
}
if entity == nil {
if let delegate = parser.delegate {
let entityName = UTF8STRING(name)!
// if the systemID was valid, we would already have the correct entity (since we're loading external dtds) so this callback is a bit of a misnomer
let result = delegate.parser(parser, resolveExternalEntityName: entityName, systemID: nil)
if _CFXMLInterfaceHasDocument(context) != 0 {
if let data = result {
// unfortunately we can't add the entity to the doc to avoid further lookup since the delegate can change under us
data.withUnsafeBytes { (bytes: UnsafePointer<UInt8>) -> Void in
_NSXMLParserCharacters(ctx, ch: bytes, len: Int32(data.count))
}
}
}
}
}
return entity
}
internal func _NSXMLParserNotationDecl(_ ctx: _CFXMLInterface, name: UnsafePointer<UInt8>, publicId: UnsafePointer<UInt8>, systemId: UnsafePointer<UInt8>) -> Void {
let parser = ctx.parser
if let delegate = parser.delegate {
let notationName = UTF8STRING(name)!
let publicIDString = UTF8STRING(publicId)
let systemIDString = UTF8STRING(systemId)
delegate.parser(parser, foundNotationDeclarationWithName: notationName, publicID: publicIDString, systemID: systemIDString)
}
}
internal func _NSXMLParserAttributeDecl(_ ctx: _CFXMLInterface, elem: UnsafePointer<UInt8>, fullname: UnsafePointer<UInt8>, type: Int32, def: Int32, defaultValue: UnsafePointer<UInt8>, tree: _CFXMLInterfaceEnumeration) -> Void {
let parser = ctx.parser
if let delegate = parser.delegate {
let elementString = UTF8STRING(elem)!
let nameString = UTF8STRING(fullname)!
let typeString = "" // FIXME!
let defaultValueString = UTF8STRING(defaultValue)
delegate.parser(parser, foundAttributeDeclarationWithName: nameString, forElement: elementString, type: typeString, defaultValue: defaultValueString)
}
// in a regular sax implementation tree is added to an attribute, which takes ownership of it; in our case we need to make sure to release it
_CFXMLInterfaceFreeEnumeration(tree)
}
internal func _NSXMLParserElementDecl(_ ctx: _CFXMLInterface, name: UnsafePointer<UInt8>, type: Int32, content: _CFXMLInterfaceElementContent) -> Void {
let parser = ctx.parser
if let delegate = parser.delegate {
let nameString = UTF8STRING(name)!
let modelString = "" // FIXME!
delegate.parser(parser, foundElementDeclarationWithName: nameString, model: modelString)
}
}
internal func _NSXMLParserUnparsedEntityDecl(_ ctx: _CFXMLInterface, name: UnsafePointer<UInt8>, publicId: UnsafePointer<UInt8>, systemId: UnsafePointer<UInt8>, notationName: UnsafePointer<UInt8>) -> Void {
let parser = ctx.parser
let context = _NSXMLParserGetContext(ctx)
// Add entities to the libxml2 doc so they'll resolve properly
_CFXMLInterfaceSAX2UnparsedEntityDecl(context, name, publicId, systemId, notationName)
if let delegate = parser.delegate {
let declName = UTF8STRING(name)!
let publicIDString = UTF8STRING(publicId)
let systemIDString = UTF8STRING(systemId)
let notationNameString = UTF8STRING(notationName)
delegate.parser(parser, foundUnparsedEntityDeclarationWithName: declName, publicID: publicIDString, systemID: systemIDString, notationName: notationNameString)
}
}
internal func _NSXMLParserStartDocument(_ ctx: _CFXMLInterface) -> Void {
let parser = ctx.parser
if let delegate = parser.delegate {
delegate.parserDidStartDocument(parser)
}
}
internal func _NSXMLParserEndDocument(_ ctx: _CFXMLInterface) -> Void {
let parser = ctx.parser
if let delegate = parser.delegate {
delegate.parserDidEndDocument(parser)
}
}
internal func _NSXMLParserStartElementNs(_ ctx: _CFXMLInterface, localname: UnsafePointer<UInt8>, prefix: UnsafePointer<UInt8>?, URI: UnsafePointer<UInt8>?, nb_namespaces: Int32, namespaces: UnsafeMutablePointer<UnsafePointer<UInt8>?>, nb_attributes: Int32, nb_defaulted: Int32, attributes: UnsafeMutablePointer<UnsafePointer<UInt8>?>) -> Void {
let parser = ctx.parser
let reportNamespaces = parser.shouldReportNamespacePrefixes
var nsDict = [String:String]()
var attrDict = [String:String]()
if nb_attributes + nb_namespaces > 0 {
for idx in stride(from: 0, to: Int(nb_namespaces) * 2, by: 2) {
var namespaceNameString: String?
var asAttrNamespaceNameString: String?
if let ns = namespaces[idx] {
namespaceNameString = UTF8STRING(ns)
asAttrNamespaceNameString = "xmlns:" + namespaceNameString!
} else {
namespaceNameString = ""
asAttrNamespaceNameString = "xmlns"
}
let namespaceValueString = namespaces[idx + 1] != nil ? UTF8STRING(namespaces[idx + 1]!) : ""
if reportNamespaces {
if let k = namespaceNameString, let v = namespaceValueString {
nsDict[k] = v
}
}
if !parser.shouldProcessNamespaces {
if let k = asAttrNamespaceNameString,
let v = namespaceValueString {
attrDict[k] = v
}
}
}
}
if reportNamespaces {
parser._pushNamespaces(nsDict)
}
for idx in stride(from: 0, to: Int(nb_attributes) * 5, by: 5) {
if attributes[idx] == nil {
continue
}
var attributeQName: String
let attrLocalName = attributes[idx]!
let attrLocalNameString = UTF8STRING(attrLocalName)!
let attrPrefix = attributes[idx + 1]
if let attrPrefixString = UTF8STRING(attrPrefix), !attrPrefixString.isEmpty {
attributeQName = attrPrefixString + ":" + attrLocalNameString
} else {
attributeQName = attrLocalNameString
}
// idx+2 = URI, which we throw away
// idx+3 = value, i+4 = endvalue
// By using XML_PARSE_NOENT the attribute value string will already have entities resolved
var attributeValue = ""
if let value = attributes[idx + 3], let endvalue = attributes[idx + 4] {
let numBytesWithoutTerminator = endvalue - value
if numBytesWithoutTerminator > 0 {
let buffer = UnsafeBufferPointer(start: value,
count: numBytesWithoutTerminator)
attributeValue = String(decoding: buffer, as: UTF8.self)
}
attrDict[attributeQName] = attributeValue
}
}
var elementName: String = UTF8STRING(localname)!
var namespaceURI: String? = nil
var qualifiedName: String? = nil
if parser.shouldProcessNamespaces {
namespaceURI = UTF8STRING(URI) ?? ""
qualifiedName = elementName
if let prefix = UTF8STRING(prefix) {
qualifiedName = elementName + ":" + prefix
}
}
else if let prefix = UTF8STRING(prefix) {
elementName = elementName + ":" + prefix
}
parser.delegate?.parser(parser, didStartElement: elementName, namespaceURI: namespaceURI, qualifiedName: qualifiedName, attributes: attrDict)
}
internal func _NSXMLParserEndElementNs(_ ctx: _CFXMLInterface , localname: UnsafePointer<UInt8>, prefix: UnsafePointer<UInt8>?, URI: UnsafePointer<UInt8>?) -> Void {
let parser = ctx.parser
var elementName: String = UTF8STRING(localname)!
var namespaceURI: String? = nil
var qualifiedName: String? = nil
if parser.shouldProcessNamespaces {
namespaceURI = UTF8STRING(URI) ?? ""
qualifiedName = elementName
if let prefix = UTF8STRING(prefix) {
qualifiedName = elementName + ":" + prefix
}
}
else if let prefix = UTF8STRING(prefix) {
elementName = elementName + ":" + prefix
}
parser.delegate?.parser(parser, didEndElement: elementName, namespaceURI: namespaceURI, qualifiedName: qualifiedName)
// Pop the last namespaces that were pushed (safe since XML is balanced)
if parser.shouldReportNamespacePrefixes {
parser._popNamespaces()
}
}
internal func _NSXMLParserCharacters(_ ctx: _CFXMLInterface, ch: UnsafePointer<UInt8>, len: Int32) -> Void {
let parser = ctx.parser
let context = parser._parserContext!
if _CFXMLInterfaceInRecursiveState(context) != 0 {
_CFXMLInterfaceResetRecursiveState(context)
} else {
if let delegate = parser.delegate {
let str = String(decoding: UnsafeBufferPointer(start: ch, count: Int(len)), as: UTF8.self)
delegate.parser(parser, foundCharacters: str)
}
}
}
internal func _NSXMLParserProcessingInstruction(_ ctx: _CFXMLInterface, target: UnsafePointer<UInt8>, data: UnsafePointer<UInt8>) -> Void {
let parser = ctx.parser
if let delegate = parser.delegate {
let targetString = UTF8STRING(target)!
let dataString = UTF8STRING(data)
delegate.parser(parser, foundProcessingInstructionWithTarget: targetString, data: dataString)
}
}
internal func _NSXMLParserCdataBlock(_ ctx: _CFXMLInterface, value: UnsafePointer<UInt8>, len: Int32) -> Void {
let parser = ctx.parser
if let delegate = parser.delegate {
delegate.parser(parser, foundCDATA: Data(bytes: value, count: Int(len)))
}
}
internal func _NSXMLParserComment(_ ctx: _CFXMLInterface, value: UnsafePointer<UInt8>) -> Void {
let parser = ctx.parser
if let delegate = parser.delegate {
let comment = UTF8STRING(value)!
delegate.parser(parser, foundComment: comment)
}
}
internal func _NSXMLParserExternalSubset(_ ctx: _CFXMLInterface, name: UnsafePointer<UInt8>, ExternalID: UnsafePointer<UInt8>, SystemID: UnsafePointer<UInt8>) -> Void {
_CFXMLInterfaceSAX2ExternalSubset(ctx.parser._parserContext, name, ExternalID, SystemID)
}
internal func _structuredErrorFunc(_ interface: _CFXMLInterface, error: _CFXMLInterfaceError) {
let err = _CFErrorCreateFromXMLInterface(error)._nsObject
let parser = interface.parser
parser._parserError = err
if let delegate = parser.delegate {
delegate.parser(parser, parseErrorOccurred: err)
}
}
open class XMLParser : NSObject {
private var _handler: _CFXMLInterfaceSAXHandler
internal var _stream: InputStream?
internal var _data: Data?
internal var _chunkSize = Int(4096 * 32) // a suitably large number for a decent chunk size
// This chunk of data stores the head of the stream. We know we have enough information for encoding
// when there are atleast 4 bytes in here.
internal var _bomChunk: Data?
fileprivate var _parserContext: _CFXMLInterfaceParserContext?
internal var _delegateAborted = false
internal var _url: URL?
internal var _namespaces = [[String:String]]()
// initializes the parser with the specified URL.
public convenience init?(contentsOf url: URL) {
if url.isFileURL {
if let stream = InputStream(url: url) {
self.init(stream: stream)
_url = url
} else {
return nil
}
} else {
do {
let data = try Data(contentsOf: url)
self.init(data: data)
self._url = url
} catch {
return nil
}
}
}
// create the parser from data
public init(data: Data) {
_CFSetupXMLInterface()
_data = data
_handler = _CFXMLInterfaceCreateSAXHandler()
_parserContext = nil
}
deinit {
_CFXMLInterfaceDestroySAXHandler(_handler)
_CFXMLInterfaceDestroyContext(_parserContext)
}
//create a parser that incrementally pulls data from the specified stream and parses it.
public init(stream: InputStream) {
_CFSetupXMLInterface()
_stream = stream
_handler = _CFXMLInterfaceCreateSAXHandler()
_parserContext = nil
}
open weak var delegate: XMLParserDelegate?
open var shouldProcessNamespaces: Bool = false
open var shouldReportNamespacePrefixes: Bool = false
//defaults to XMLNode.ExternalEntityResolvingPolicy.never
open var externalEntityResolvingPolicy: ExternalEntityResolvingPolicy = .never
open var allowedExternalEntityURLs: Set<URL>?
internal static func currentParser() -> XMLParser? {
if let current = Thread.current.threadDictionary["__CurrentNSXMLParser"] {
return current as? XMLParser
} else {
return nil
}
}
internal static func setCurrentParser(_ parser: XMLParser?) {
if let p = parser {
Thread.current.threadDictionary["__CurrentNSXMLParser"] = p
} else {
Thread.current.threadDictionary.removeObject(forKey: "__CurrentNSXMLParser")
}
}
internal func _handleParseResult(_ parseResult: Int32) -> Bool {
return true
/*
var result = true
if parseResult != 0 {
if parseResult != -1 {
// TODO: determine if this result is a fatal error from libxml via the CF implementations
}
}
return result
*/
}
internal func parseData(_ data: Data) -> Bool {
_CFXMLInterfaceSetStructuredErrorFunc(interface, _structuredErrorFunc)
let handler: _CFXMLInterfaceSAXHandler? = (delegate != nil ? _handler : nil)
let unparsedData: Data
// If the parser context is nil, we have not received enough bytes to create the push parser
if _parserContext == nil {
// Look at the bomChunk and this data
let bomChunk: Data = {
guard var bomChunk = _bomChunk else {
return data
}
bomChunk.append(data)
return bomChunk
}()
// If we have not received 4 bytes, save the bomChunk for next pass
if bomChunk.count < 4 {
_bomChunk = bomChunk
return false
}
// Prepare options (substitute entities, recover on errors)
var options = _kCFXMLInterfaceRecover | _kCFXMLInterfaceNoEnt
if shouldResolveExternalEntities {
options |= _kCFXMLInterfaceDTDLoad
}
if handler == nil {
options |= (_kCFXMLInterfaceNoError | _kCFXMLInterfaceNoWarning)
}
// Create the push context with the first 4 bytes
bomChunk.withUnsafeBytes { bytes in
_parserContext = _CFXMLInterfaceCreatePushParserCtxt(handler, interface, bytes, 4, nil)
}
_CFXMLInterfaceCtxtUseOptions(_parserContext, options)
// Prepare the remaining data for parsing
let dataRange = bomChunk.indices
let unparsed = Range(uncheckedBounds: (dataRange.startIndex.advanced(by: 4), dataRange.endIndex))
unparsedData = bomChunk.subdata(in: unparsed)
}
else {
unparsedData = data
}
let parseResult = unparsedData.withUnsafeBytes { (bytes: UnsafePointer<Int8>) -> Int32 in
return _CFXMLInterfaceParseChunk(_parserContext, bytes, Int32(unparsedData.count), 0)
}
let result = _handleParseResult(parseResult)
_CFXMLInterfaceSetStructuredErrorFunc(interface, nil)
return result
}
internal func parseFromStream() -> Bool {
var result = true
XMLParser.setCurrentParser(self)
defer { XMLParser.setCurrentParser(nil) }
if let stream = _stream {
stream.open()
defer { stream.close() }
let buffer = malloc(_chunkSize)!.bindMemory(to: UInt8.self, capacity: _chunkSize)
defer { free(buffer) }
var len = stream.read(buffer, maxLength: _chunkSize)
if len != -1 {
while len > 0 {
let data = Data(bytesNoCopy: buffer, count: len, deallocator: .none)
result = parseData(data)
len = stream.read(buffer, maxLength: _chunkSize)
}
} else {
result = false
}
} else if let data = _data {
let buffer = malloc(_chunkSize)!.bindMemory(to: UInt8.self, capacity: _chunkSize)
defer { free(buffer) }
var range = NSRange(location: 0, length: min(_chunkSize, data.count))
while result {
let chunk = data.withUnsafeBytes { (buffer: UnsafePointer<UInt8>) -> Data in
let ptr = buffer.advanced(by: range.location)
return Data(bytesNoCopy: UnsafeMutablePointer(mutating: ptr), count: range.length, deallocator: .none)
}
result = parseData(chunk)
if range.location + range.length >= data.count {
break
}
range = NSRange(location: range.location + range.length, length: min(_chunkSize, data.count - (range.location + range.length)))
}
} else {
result = false
}
return result
}
// called to start the event-driven parse. Returns YES in the event of a successful parse, and NO in case of error.
open func parse() -> Bool {
return parseFromStream()
}
// called by the delegate to stop the parse. The delegate will get an error message sent to it.
open func abortParsing() {
if let context = _parserContext {
_CFXMLInterfaceStopParser(context)
_delegateAborted = true
}
}
internal var _parserError: Error?
// can be called after a parse is over to determine parser state.
open var parserError: Error? {
return _parserError
}
//Toggles between disabling external entities entirely, and the current setting of the 'externalEntityResolvingPolicy'.
//The 'externalEntityResolvingPolicy' property should be used instead of this, unless targeting 10.9/7.0 or earlier
open var shouldResolveExternalEntities: Bool = false
// Once a parse has begun, the delegate may be interested in certain parser state. These methods will only return meaningful information during parsing, or after an error has occurred.
open var publicID: String? {
return nil
}
open var systemID: String? {
return nil
}
open var lineNumber: Int {
return Int(_CFXMLInterfaceSAX2GetLineNumber(_parserContext))
}
open var columnNumber: Int {
return Int(_CFXMLInterfaceSAX2GetColumnNumber(_parserContext))
}
internal func _pushNamespaces(_ ns: [String:String]) {
_namespaces.append(ns)
if let del = self.delegate {
ns.forEach {
del.parser(self, didStartMappingPrefix: $0.0, toURI: $0.1)
}
}
}
internal func _popNamespaces() {
let ns = _namespaces.removeLast()
if let del = self.delegate {
ns.forEach {
del.parser(self, didEndMappingPrefix: $0.0)
}
}
}
}
/*
For the discussion of event methods, assume the following XML:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type='text/css' href='cvslog.css'?>
<!DOCTYPE cvslog SYSTEM "cvslog.dtd">
<cvslog xmlns="http://xml.apple.com/cvslog">
<radar:radar xmlns:radar="http://xml.apple.com/radar">
<radar:bugID>2920186</radar:bugID>
<radar:title>API/NSXMLParser: there ought to be an NSXMLParser</radar:title>
</radar:radar>
</cvslog>
*/
// The parser's delegate is informed of events through the methods in the NSXMLParserDelegateEventAdditions category.
public protocol XMLParserDelegate: class {
// Document handling methods
func parserDidStartDocument(_ parser: XMLParser)
// sent when the parser begins parsing of the document.
func parserDidEndDocument(_ parser: XMLParser)
// sent when the parser has completed parsing. If this is encountered, the parse was successful.
// DTD handling methods for various declarations.
func parser(_ parser: XMLParser, foundNotationDeclarationWithName name: String, publicID: String?, systemID: String?)
func parser(_ parser: XMLParser, foundUnparsedEntityDeclarationWithName name: String, publicID: String?, systemID: String?, notationName: String?)
func parser(_ parser: XMLParser, foundAttributeDeclarationWithName attributeName: String, forElement elementName: String, type: String?, defaultValue: String?)
func parser(_ parser: XMLParser, foundElementDeclarationWithName elementName: String, model: String)
func parser(_ parser: XMLParser, foundInternalEntityDeclarationWithName name: String, value: String?)
func parser(_ parser: XMLParser, foundExternalEntityDeclarationWithName name: String, publicID: String?, systemID: String?)
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String])
// sent when the parser finds an element start tag.
// In the case of the cvslog tag, the following is what the delegate receives:
// elementName == cvslog, namespaceURI == http://xml.apple.com/cvslog, qualifiedName == cvslog
// In the case of the radar tag, the following is what's passed in:
// elementName == radar, namespaceURI == http://xml.apple.com/radar, qualifiedName == radar:radar
// If namespace processing >isn't< on, the xmlns:radar="http://xml.apple.com/radar" is returned as an attribute pair, the elementName is 'radar:radar' and there is no qualifiedName.
func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?)
// sent when an end tag is encountered. The various parameters are supplied as above.
func parser(_ parser: XMLParser, didStartMappingPrefix prefix: String, toURI namespaceURI: String)
// sent when the parser first sees a namespace attribute.
// In the case of the cvslog tag, before the didStartElement:, you'd get one of these with prefix == @"" and namespaceURI == @"http://xml.apple.com/cvslog" (i.e. the default namespace)
// In the case of the radar:radar tag, before the didStartElement: you'd get one of these with prefix == @"radar" and namespaceURI == @"http://xml.apple.com/radar"
func parser(_ parser: XMLParser, didEndMappingPrefix prefix: String)
// sent when the namespace prefix in question goes out of scope.
func parser(_ parser: XMLParser, foundCharacters string: String)
// This returns the string of the characters encountered thus far. You may not necessarily get the longest character run. The parser reserves the right to hand these to the delegate as potentially many calls in a row to -parser:foundCharacters:
func parser(_ parser: XMLParser, foundIgnorableWhitespace whitespaceString: String)
// The parser reports ignorable whitespace in the same way as characters it's found.
func parser(_ parser: XMLParser, foundProcessingInstructionWithTarget target: String, data: String?)
// The parser reports a processing instruction to you using this method. In the case above, target == @"xml-stylesheet" and data == @"type='text/css' href='cvslog.css'"
func parser(_ parser: XMLParser, foundComment comment: String)
// A comment (Text in a <!-- --> block) is reported to the delegate as a single string
func parser(_ parser: XMLParser, foundCDATA CDATABlock: Data)
// this reports a CDATA block to the delegate as an NSData.
func parser(_ parser: XMLParser, resolveExternalEntityName name: String, systemID: String?) -> Data?
// this gives the delegate an opportunity to resolve an external entity itself and reply with the resulting data.
func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error)
// ...and this reports a fatal error to the delegate. The parser will stop parsing.
func parser(_ parser: XMLParser, validationErrorOccurred validationError: Error)
}
public extension XMLParserDelegate {
func parserDidStartDocument(_ parser: XMLParser) { }
func parserDidEndDocument(_ parser: XMLParser) { }
func parser(_ parser: XMLParser, foundNotationDeclarationWithName name: String, publicID: String?, systemID: String?) { }
func parser(_ parser: XMLParser, foundUnparsedEntityDeclarationWithName name: String, publicID: String?, systemID: String?, notationName: String?) { }
func parser(_ parser: XMLParser, foundAttributeDeclarationWithName attributeName: String, forElement elementName: String, type: String?, defaultValue: String?) { }
func parser(_ parser: XMLParser, foundElementDeclarationWithName elementName: String, model: String) { }
func parser(_ parser: XMLParser, foundInternalEntityDeclarationWithName name: String, value: String?) { }
func parser(_ parser: XMLParser, foundExternalEntityDeclarationWithName name: String, publicID: String?, systemID: String?) { }
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) { }
func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { }
func parser(_ parser: XMLParser, didStartMappingPrefix prefix: String, toURI namespaceURI: String) { }
func parser(_ parser: XMLParser, didEndMappingPrefix prefix: String) { }
func parser(_ parser: XMLParser, foundCharacters string: String) { }
func parser(_ parser: XMLParser, foundIgnorableWhitespace whitespaceString: String) { }
func parser(_ parser: XMLParser, foundProcessingInstructionWithTarget target: String, data: String?) { }
func parser(_ parser: XMLParser, foundComment comment: String) { }
func parser(_ parser: XMLParser, foundCDATA CDATABlock: Data) { }
func parser(_ parser: XMLParser, resolveExternalEntityName name: String, systemID: String?) -> Data? { return nil }
func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) { }
func parser(_ parser: XMLParser, validationErrorOccurred validationError: Error) { }
}
extension XMLParser {
// If validation is on, this will report a fatal validation error to the delegate. The parser will stop parsing.
public static let errorDomain: String = "NSXMLParserErrorDomain" // for use with NSError.
// Error reporting
public enum ErrorCode : Int {
case internalError
case outOfMemoryError
case documentStartError
case emptyDocumentError
case prematureDocumentEndError
case invalidHexCharacterRefError
case invalidDecimalCharacterRefError
case invalidCharacterRefError
case invalidCharacterError
case characterRefAtEOFError
case characterRefInPrologError
case characterRefInEpilogError
case characterRefInDTDError
case entityRefAtEOFError
case entityRefInPrologError
case entityRefInEpilogError
case entityRefInDTDError
case parsedEntityRefAtEOFError
case parsedEntityRefInPrologError
case parsedEntityRefInEpilogError
case parsedEntityRefInInternalSubsetError
case entityReferenceWithoutNameError
case entityReferenceMissingSemiError
case parsedEntityRefNoNameError
case parsedEntityRefMissingSemiError
case undeclaredEntityError
case unparsedEntityError
case entityIsExternalError
case entityIsParameterError
case unknownEncodingError
case encodingNotSupportedError
case stringNotStartedError
case stringNotClosedError
case namespaceDeclarationError
case entityNotStartedError
case entityNotFinishedError
case lessThanSymbolInAttributeError
case attributeNotStartedError
case attributeNotFinishedError
case attributeHasNoValueError
case attributeRedefinedError
case literalNotStartedError
case literalNotFinishedError
case commentNotFinishedError
case processingInstructionNotStartedError
case processingInstructionNotFinishedError
case notationNotStartedError
case notationNotFinishedError
case attributeListNotStartedError
case attributeListNotFinishedError
case mixedContentDeclNotStartedError
case mixedContentDeclNotFinishedError
case elementContentDeclNotStartedError
case elementContentDeclNotFinishedError
case xmlDeclNotStartedError
case xmlDeclNotFinishedError
case conditionalSectionNotStartedError
case conditionalSectionNotFinishedError
case externalSubsetNotFinishedError
case doctypeDeclNotFinishedError
case misplacedCDATAEndStringError
case cdataNotFinishedError
case misplacedXMLDeclarationError
case spaceRequiredError
case separatorRequiredError
case nmtokenRequiredError
case nameRequiredError
case pcdataRequiredError
case uriRequiredError
case publicIdentifierRequiredError
case ltRequiredError
case gtRequiredError
case ltSlashRequiredError
case equalExpectedError
case tagNameMismatchError
case unfinishedTagError
case standaloneValueError
case invalidEncodingNameError
case commentContainsDoubleHyphenError
case invalidEncodingError
case externalStandaloneEntityError
case invalidConditionalSectionError
case entityValueRequiredError
case notWellBalancedError
case extraContentError
case invalidCharacterInEntityError
case parsedEntityRefInInternalError
case entityRefLoopError
case entityBoundaryError
case invalidURIError
case uriFragmentError
case noDTDError
case delegateAbortedParseError
}
}
|
apache-2.0
|
6e01044175f4b424e329e563c3f28bde
| 37.09375 | 345 | 0.645146 | 5.136236 | false | false | false | false |
theScud/Lunch
|
lunchPlanner/UI/SplashViewController.swift
|
1
|
1800
|
//
// SplashViewController.swift
// lunchPlanner
//
// Created by Sudeep Kini on 04/11/16.
// Copyright © 2016 TestLabs. All rights reserved.
//
import UIKit
import CoreLocation
class SplashViewController: UIViewController,CLLocationManagerDelegate {
var locationManager: CLLocationManager = CLLocationManager()
var gotlocation = false
override func viewDidLoad() {
super.viewDidLoad()
self.locationManager.requestWhenInUseAuthorization()
// Getting user Location
//Location Manager Request for Locations
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
locationManager.stopUpdatingLocation()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
if let location = locations.last {
if(gotlocation == false ){
appDelegate.appState?.updateUserLocation(location:location)
self.performSegue(withIdentifier:"gotoCategoriesPage", sender: self)
locationManager.stopUpdatingLocation()
gotlocation = true
}
}
}
}
|
apache-2.0
|
7c2753828ef45aeca83a231332f71318
| 27.555556 | 100 | 0.652585 | 6.098305 | false | false | false | false |
inderdhir/MemeGrabber
|
MemeGrabber/Reachability.swift
|
1
|
899
|
//
// Reachability.swift
// MemeGrabber
//
// Created by Inder Dhir on 6/26/16.
// Copyright © 2016 Inder Dhir. All rights reserved.
//
import SystemConfiguration
public class Reachability {
class func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
}
var flags = SCNetworkReachabilityFlags()
if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {
return false
}
let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
return (isReachable && !needsConnection)
}
}
|
apache-2.0
|
3f01b3b019df5f272de760a54307f0a9
| 32.259259 | 91 | 0.726058 | 4.628866 | false | false | false | false |
ResearchSuite/ResearchSuiteExtensions-iOS
|
source/Common/Classes/RSAlert.swift
|
1
|
1434
|
//
// RSAlert.swift
// ResearchSuiteExtensions
//
// Created by James Kizer on 6/26/18.
//
import UIKit
import Gloss
open class RSAlertChoice: Gloss.JSONDecodable {
public let title: String
public let style: UIAlertAction.Style
public let onTapActions: [JSON]
private static func styleFor(_ styleString: String) -> UIAlertAction.Style? {
switch styleString {
case "default":
return .default
case "cancel":
return .cancel
case "destructive":
return .destructive
default:
return nil
}
}
required public init?(json: JSON) {
guard let title: String = "title" <~~ json,
let styleString: String = "style" <~~ json,
let style = RSAlertChoice.styleFor(styleString) else {
return nil
}
self.title = title
self.style = style
self.onTapActions = "onTap" <~~ json ?? []
}
}
open class RSAlert: Gloss.JSONDecodable {
public let title: String
public let text: String?
public let choices: [RSAlertChoice]
required public init?(json: JSON) {
guard let title: String = "title" <~~ json else {
return nil
}
self.title = title
self.text = "text" <~~ json
self.choices = "choices" <~~ json ?? []
}
}
|
apache-2.0
|
573b404c7318bdf48886c62f71f60135
| 22.129032 | 81 | 0.54463 | 4.523659 | false | false | false | false |
ReactiveX/RxSwift
|
RxSwift/Observables/SwitchIfEmpty.swift
|
2
|
3464
|
//
// SwitchIfEmpty.swift
// RxSwift
//
// Created by sergdort on 23/12/2016.
// Copyright © 2016 Krunoslav Zaher. All rights reserved.
//
extension ObservableType {
/**
Returns the elements of the specified sequence or `switchTo` sequence if the sequence is empty.
- seealso: [DefaultIfEmpty operator on reactivex.io](http://reactivex.io/documentation/operators/defaultifempty.html)
- parameter other: Observable sequence being returned when source sequence is empty.
- returns: Observable sequence that contains elements from switchTo sequence if source is empty, otherwise returns source sequence elements.
*/
public func ifEmpty(switchTo other: Observable<Element>) -> Observable<Element> {
SwitchIfEmpty(source: self.asObservable(), ifEmpty: other)
}
}
final private class SwitchIfEmpty<Element>: Producer<Element> {
private let source: Observable<Element>
private let ifEmpty: Observable<Element>
init(source: Observable<Element>, ifEmpty: Observable<Element>) {
self.source = source
self.ifEmpty = ifEmpty
}
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element {
let sink = SwitchIfEmptySink(ifEmpty: self.ifEmpty,
observer: observer,
cancel: cancel)
let subscription = sink.run(self.source.asObservable())
return (sink: sink, subscription: subscription)
}
}
final private class SwitchIfEmptySink<Observer: ObserverType>: Sink<Observer>
, ObserverType {
typealias Element = Observer.Element
private let ifEmpty: Observable<Element>
private var isEmpty = true
private let ifEmptySubscription = SingleAssignmentDisposable()
init(ifEmpty: Observable<Element>, observer: Observer, cancel: Cancelable) {
self.ifEmpty = ifEmpty
super.init(observer: observer, cancel: cancel)
}
func run(_ source: Observable<Observer.Element>) -> Disposable {
let subscription = source.subscribe(self)
return Disposables.create(subscription, ifEmptySubscription)
}
func on(_ event: Event<Element>) {
switch event {
case .next:
self.isEmpty = false
self.forwardOn(event)
case .error:
self.forwardOn(event)
self.dispose()
case .completed:
guard self.isEmpty else {
self.forwardOn(.completed)
self.dispose()
return
}
let ifEmptySink = SwitchIfEmptySinkIter(parent: self)
self.ifEmptySubscription.setDisposable(self.ifEmpty.subscribe(ifEmptySink))
}
}
}
final private class SwitchIfEmptySinkIter<Observer: ObserverType>
: ObserverType {
typealias Element = Observer.Element
typealias Parent = SwitchIfEmptySink<Observer>
private let parent: Parent
init(parent: Parent) {
self.parent = parent
}
func on(_ event: Event<Element>) {
switch event {
case .next:
self.parent.forwardOn(event)
case .error:
self.parent.forwardOn(event)
self.parent.dispose()
case .completed:
self.parent.forwardOn(event)
self.parent.dispose()
}
}
}
|
mit
|
376b9959cfafb413ce104727e36adc68
| 32.298077 | 171 | 0.638753 | 4.816412 | false | false | false | false |
the-blue-alliance/the-blue-alliance-ios
|
the-blue-alliance-ios/View Controllers/Settings/SettingsViewController.swift
|
1
|
12541
|
import CoreData
import MyTBAKit
import Search
import TBAKit
import UIKit
private enum SettingsSection: Int, CaseIterable {
case info
case icons
case debug
}
private enum InfoRow: String, CaseIterable {
case website = "https://www.thebluealliance.com"
case github = "https://github.com/the-blue-alliance/the-blue-alliance-ios"
case testFlight = "https://testflight.apple.com/join/gz7RmdS7"
}
private enum DebugRow: Int, CaseIterable {
case deleteNetworkCache
case deleteSearchIndex
case troubleshootNotifications
}
class SettingsViewController: TBATableViewController {
private let fcmTokenProvider: FCMTokenProvider
private let myTBA: MyTBA
private let pushService: PushService
private let searchService: SearchService
private let urlOpener: URLOpener
// MARK: - Init
init(fcmTokenProvider: FCMTokenProvider, myTBA: MyTBA, pushService: PushService, searchService: SearchService, urlOpener: URLOpener, dependencies: Dependencies) {
self.fcmTokenProvider = fcmTokenProvider
self.myTBA = myTBA
self.pushService = pushService
self.searchService = searchService
self.urlOpener = urlOpener
super.init(style: .grouped, dependencies: dependencies)
title = RootType.settings.title
tabBarItem.image = RootType.settings.icon
hidesBottomBarWhenPushed = false
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
tableView.registerReusableCell(IconTableViewCell.self)
}
// MARK: - Private Methods
private func normalizedSection(_ section: Int) -> SettingsSection? {
var section = section
if !UIApplication.shared.supportsAlternateIcons, section >= SettingsSection.icons.rawValue {
section += 1
}
return SettingsSection(rawValue: section)!
}
// MARK: - Table View Data Source
override func numberOfSections(in tableView: UITableView) -> Int {
var sections = SettingsSection.allCases.count
// Remove our Icons section if they're not supported
if !UIApplication.shared.supportsAlternateIcons {
sections -= 1
}
return sections
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Remove our Icons section if they're not supported
guard let section = normalizedSection(section) else {
return 0
}
switch section {
case .info:
return InfoRow.allCases.count
case .icons:
return alternateAppIcons.count + 1 // +1 for default icon
case .debug:
return DebugRow.allCases.count
}
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
guard let section = normalizedSection(section) else {
return nil
}
switch section {
case .info:
return "Info"
case .icons:
return "App Icon"
case .debug:
return "Debug"
}
}
override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
guard let section = normalizedSection(section) else {
return nil
}
guard section == .debug else {
return nil
}
return "The Blue Alliance for iOS - \(Bundle.main.displayVersionString)"
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let section = normalizedSection(indexPath.section) else {
fatalError("This section does not exist")
}
switch section {
case .info:
let cell = UITableViewCell(style: .default, reuseIdentifier: nil)
let infoRow = InfoRow.allCases[indexPath.row]
let titleString: String = {
switch infoRow {
case .website:
return "The Blue Alliance website"
case .github:
return "The Blue Alliance for iOS is open source"
case .testFlight:
return "Join The Blue Alliance TestFlight"
}
}()
cell.accessoryType = .disclosureIndicator
cell.textLabel?.text = titleString
return cell
case .icons:
let cell = tableView.dequeueReusableCell(indexPath: indexPath) as IconTableViewCell
let viewModel: IconCellViewModel = {
if indexPath.row == 0 {
return IconCellViewModel(name: "The Blue Alliance", imageName: primaryAppIconName ?? "AppIcon")
} else {
let alternateName = Array(alternateAppIcons.keys)[indexPath.row - 1]
guard let alternateIconName = alternateAppIcons[alternateName] else {
fatalError("Unable to find alternate icon for \(alternateName)")
}
return IconCellViewModel(name: alternateName, imageName: alternateIconName)
}
}()
cell.viewModel = viewModel
// Show currently-selected app icon
if isCurrentAppIcon(viewModel.name) || (isCurrentAppIcon(nil) && indexPath.row == 0) {
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .none
}
return cell
case .debug:
let cell = UITableViewCell(style: .default, reuseIdentifier: nil)
let debugRow = DebugRow.allCases[indexPath.row]
let titleString: String = {
switch debugRow {
case .deleteNetworkCache:
return "Delete network cache"
case .deleteSearchIndex:
return "Delete search index"
case .troubleshootNotifications:
return "Troubleshoot notifications"
}
}()
cell.accessoryType = .disclosureIndicator
cell.textLabel?.text = titleString
return cell
}
}
// MARK: - Table View Delegate
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
// Override so we don't get colored headers
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
guard let section = normalizedSection(indexPath.section) else {
fatalError("This section does not exist")
}
switch section {
case .info:
let infoRow = InfoRow.allCases[indexPath.row]
if let url = URL(string: infoRow.rawValue) {
openURL(url: url)
}
case .icons:
if indexPath.row == 0 {
setDefaultAppIcon()
} else {
let alternateName = Array(alternateAppIcons.keys)[indexPath.row - 1]
setAlternateAppIcon(alternateName)
}
case .debug:
let debugRow = DebugRow.allCases[indexPath.row]
switch debugRow {
case .deleteNetworkCache:
showDeleteNetworkCache()
case .deleteSearchIndex:
showDeleteSearchIndex()
case .troubleshootNotifications:
pushTroubleshootNotifications()
}
}
}
// MARK: - Private Methods
// MARK: - Info Methods
private func openURL(url: URL) {
if urlOpener.canOpenURL(url) {
urlOpener.open(url, options: [:], completionHandler: nil)
}
}
// MARK: - Icons Methods
/**
Check if the current app icon is the same as the passed app icon name.
Used to show which app icon we currently have set.
*/
private func isCurrentAppIcon(_ icon: String?) -> Bool {
return icon == UIApplication.shared.alternateIconName
}
private var primaryAppIconName: String? {
guard let iconsDictionary = Bundle.main.infoDictionary?["CFBundleIcons"] as? [String:Any],
let primaryIconsDictionary = iconsDictionary["CFBundlePrimaryIcon"] as? [String:Any],
let iconFiles = primaryIconsDictionary["CFBundleIconFiles"] as? [String],
let lastIcon = iconFiles.last else { return nil }
return lastIcon
}
/*
Key is the name, value is the image name.
*/
private lazy var alternateAppIcons: [String: String] = {
guard let iconsDictionary = Bundle.main.infoDictionary?["CFBundleIcons"] as? [String:Any],
let alternateIconsDictionary = iconsDictionary["CFBundleAlternateIcons"] as? [String:Any] else { return [:] }
var alternateAppIcons: [String: String] = [:]
alternateIconsDictionary.forEach({ (key, value) in
guard let iconDictionary = value as? [String:Any],
let iconFiles = iconDictionary["CFBundleIconFiles"] as? [String],
let lastIcon = iconFiles.last else { return }
alternateAppIcons[key] = lastIcon
})
return alternateAppIcons
}()
private func setDefaultAppIcon() {
// Only change icons if it's supported by the OS
guard UIApplication.shared.supportsAlternateIcons else {
return
}
// Only set the default app icon if we have an alternate icon set
guard UIApplication.shared.alternateIconName != nil else {
return
}
UIApplication.shared.setAlternateIconName(nil, completionHandler: { _ in
self.reloadIconsSection()
})
}
private func setAlternateAppIcon(_ alternateName: String) {
// Only change icons if it's supported by the OS
guard UIApplication.shared.supportsAlternateIcons else {
return
}
// Only set the the alternate icon if it's different from the icon we have currently set
guard UIApplication.shared.alternateIconName != alternateName else {
return
}
UIApplication.shared.setAlternateIconName(alternateName, completionHandler: { _ in
self.reloadIconsSection()
})
}
private func reloadIconsSection() {
DispatchQueue.main.async {
self.tableView.reloadSections(IndexSet(integer: SettingsSection.icons.rawValue), with: .automatic)
}
}
// MARK: - Debug Methods
private func showDeleteNetworkCache() {
let alertController = UIAlertController(title: "Delete Network Cache", message: "Are you sure you want to delete all the network cache data?", preferredStyle: .alert)
let deleteCacheAction = UIAlertAction(title: "Delete", style: .destructive) { [unowned self] (deleteAction) in
self.tbaKit.clearCacheHeaders()
self.userDefaults.clearSuccessfulRefreshes()
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alertController.addAction(deleteCacheAction)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
private func showDeleteSearchIndex() {
let alertController = UIAlertController(title: "Delete Search Index", message: "Are you sure you want to delete the local search index? Search may not work properly.", preferredStyle: .alert)
let deleteCacheAction = UIAlertAction(title: "Delete", style: .destructive) { [unowned self] (deleteAction) in
self.searchService.deleteSearchIndex(errorRecorder: errorRecorder)
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alertController.addAction(deleteCacheAction)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
private func pushTroubleshootNotifications() {
let notificationsViewController = NotificationsViewController(fcmTokenProvider: fcmTokenProvider, myTBA: myTBA, pushService: pushService, urlOpener: urlOpener, dependencies: dependencies)
navigationController?.pushViewController(notificationsViewController, animated: true)
}
}
|
mit
|
7fb598a50208b59b87c7615bb8069977
| 34.426554 | 199 | 0.626266 | 5.225417 | false | false | false | false |
iamyuiwong/swift-common
|
basis/array.swift
|
1
|
8109
|
import Foundation
public class array_item_generator<T>: GeneratorType {
public init (data dt: [T]?) {
self.counter = 0
if (nil != dt) {
self.count = dt!.count
self.data = dt
}
}
public func next() -> T? {
return (self.counter >= self.count) ? nil
: self.data?[self.counter++]
}
private var data: [T]?
private var counter: Int = 0
private var count: Int = 0
}
public class array<T>: SequenceType {
subscript (index: Int) -> T? {
get {
LOCK()
let ret = self.data?[index]
UNLOCK()
return ret
}
/*
set {
if let nv = newValue {
LOCK()
self.data?[index] = nv
UNLOCK()
}
}
*/
}
public typealias Generator = array_item_generator<T>
public func generate() -> Generator {
return Generator(data: self.data)
}
public init () {
LOCK()
if (nil == self.data) {
self.data = [T]()
}
UNLOCK()
}
public init (count c: UInt, repeatedValue rv: T) {
LOCK()
if (c <= 0) {
self.data = [T]()
} else {
self.data = [T](count: Int(c), repeatedValue: rv)
}
UNLOCK()
}
public init (values vs: [T]) {
LOCK()
self.data = vs
UNLOCK()
}
public init (values vs: [T], start: UInt, count: UInt) {
LOCK()
if ((vs.count <= 0) || (count <= 0)) {
self.data = [T]()
} else {
let bsc = UInt(vs.count)
var s = start
if (s < 0) {
s = 0
} else if (s >= bsc) {
s = bsc - 1
}
var c = count
if ((s + c) > bsc) {
c = bsc - s
}
self.data = [T](count: Int(c), repeatedValue: vs.first!)
for i: UInt in 0..<c {
self.data![Int(i)] = vs[Int(start + i)]
}
}
UNLOCK()
}
public func finish () {
LOCK()
self.data = nil
UNLOCK()
}
public func bvalue (value v: T) -> Bool {
var ret: Bool?
LOCK()
if (nil == self.data) {
ret = false
} else {
let c = self.data!.count
for i in 0..<c {
self.data![i] = v
}
ret = true
}
UNLOCK()
return ret!
}
/* get all */
public func get () -> [T]? {
var ret: [T]?
LOCK()
ret = self.data
UNLOCK()
return ret
}
public func get (index i: Int) -> T? {
var ret: T?
self.LOCK()
if (nil == self.data) {
ret = nil
} else {
let c = self.data!.count
if (i >= 0 && c > i) {
ret = self.data![i]
} else {
ret = nil
}
}
self.UNLOCK()
return ret
}
/*
* get parts static
* thread safe
*/
public static func get (fromArray arr: [T], start: Int, count: size_t)
-> [T]? {
let cc = ArrayChecker.check(array: arr, start: start, count: count)
if (cc < 0) {
return nil
} else {
if (cc > 0) {
let rv = arr[0]
var ret = [T](count: cc, repeatedValue: rv)
for i in start..<(start + count) {
ret[i - start] = arr[i]
}
return ret
} else {
return [T]()
}
}
}
/* get parts */
public func get (fromStart s: Int, count: Int) -> [T]? {
var ret: [T]?
LOCK()
if ((s < 0) || (nil == self.data) || (count <= 0)) {
ret = nil
} else {
let c = self.data!.count
if ((s + count) > c) {
ret = nil
} else {
let rv = self.data![0]
ret = [T](count: Int(c), repeatedValue: rv)
for i in s..<(s + count) {
ret![Int(i - s)] = self.data![Int(i)]
}
}
}
UNLOCK()
return ret
}
public func set (values vs: [T]) {
self.LOCK()
self.data = vs
self.UNLOCK()
}
public func set (index i: Int, v: T) -> Bool {
var ret: Bool?
self.LOCK()
if ((i < 0) || (nil == self.data)) {
ret = false
} else {
let c = self.data!.count
if (i < c) {
self.data![i] = v
ret = true
} else {
ret = false
}
}
self.UNLOCK()
return ret!
}
/* TODO: add set parts to another-parts*/
/*
* NAME append - append to last (the latest one)
* For stack the-latest one is top
* For queue the-latest one is tail
*/
public final func append (v: T) -> Bool {
var ret: Bool?
self.LOCK()
if (nil == self.data) {
ret = false
} else {
self.data!.append(v)
ret = true
}
self.UNLOCK()
return ret!
}
public final func append (vs: [T]) -> Bool {
var ret: Bool?
self.LOCK()
if (nil == self.data) {
self.data = vs
ret = true
} else {
self.data = self.data! + vs
ret = true
}
self.UNLOCK()
return ret!
}
/*
* NAME insert - insert as new head
*/
public final func insert (head v: T) -> Bool {
var ret: Bool?
self.LOCK()
if (nil == self.data) {
ret = false
} else {
self.data!.insert(v, atIndex: 0)
ret = true
}
self.UNLOCK()
return ret!
}
/*
* NAME insert - insert as index i
*/
public final func insert (value v: T, atIndex i: Int) -> Bool {
var ret: Bool?
self.LOCK()
if ((nil == self.data) || (i < 0)) {
ret = false
} else {
let c = self.data!.count
if (i <= c) {
self.data!.insert(v, atIndex: i)
ret = true
} else {
ret = false
}
}
self.UNLOCK()
return ret!
}
/*
* NAME insert - insert all and first at index i
*/
public final func insert (values vs: [T], atIndex i: Int) -> Bool {
var ret: Bool?
self.LOCK()
if ((nil == self.data) || (i < 0)) {
ret = false
} else {
let c = self.data!.count
if (i <= c) {
let e = vs.count + i
for ins in i..<e {
self.data!.insert(vs[ins - i], atIndex: ins)
}
ret = true
} else {
ret = false
}
}
self.UNLOCK()
return ret!
}
/*
* NAME enqueue - append and after-old-tail (be-the-latest-one)
*/
public func enqueue (v: T) -> Bool {
return self.append(v)
}
/*
* NAME dequeue - remove and get head (first is the dequeue head)
*/
public func dequeue () -> T? {
var ret: T?
self.LOCK()
if (nil == self.data) {
ret = nil
} else {
let c = self.data!.count
if (c > 0) {
ret = self.data!.removeFirst()
} else {
ret = nil
}
}
self.UNLOCK()
return ret
}
/*
* NAME push - append and as top (latest-one)
*/
public final func push (v: T) -> Bool {
return self.append(v)
}
/*
* NAME pop - remove and get top (last is latest append one)
*/
public final func pop () -> T? {
var ret: T?
self.LOCK()
if (nil == self.data) {
ret = nil
} else {
let c = self.data!.count
if (c > 0) {
ret = self.data!.removeLast()
} else {
ret = nil
}
}
self.UNLOCK()
return ret
}
public func getLast () -> T? {
var ret: T?
self.LOCK()
if (nil == self.data) {
ret = nil
} else {
let c = self.data!.count
if (c > 0) {
ret = self.data![c - 1]
} else {
ret = nil
}
}
self.UNLOCK()
return ret
}
public func setLast (v: T) -> Bool {
var ret: Bool?
self.LOCK()
if (nil == self.data) {
ret = false
} else {
let c = self.data!.count
if (c > 0) {
self.data![c - 1] = v
ret = true
} else {
ret = false
}
}
self.UNLOCK()
return ret!
}
public func getFirst () -> T? {
var ret: T?
self.LOCK()
if (nil == self.data) {
ret = nil
} else {
let c = self.data!.count
if (c > 0) {
ret = self.data![0]
} else {
ret = nil
}
}
self.UNLOCK()
return ret
}
public func setFirst (v: T) -> Bool {
var ret: Bool?
self.LOCK()
if (nil == self.data) {
ret = false
} else {
let c = self.data!.count
if (c > 0) {
self.data![0] = v
ret = true
} else {
ret = false
}
}
self.UNLOCK()
return ret!
}
public final func empty () {
self.LOCK()
if (nil != self.data) {
if (self.data!.count > 0) {
self.data!.removeAll()
}
}
self.UNLOCK()
}
public var count: Int {
get {
LOCK()
var ret: Int?
let reto = self.data?.count
if let ret2 = reto {
ret = ret2
} else {
ret = -1
}
UNLOCK()
return ret!
}
}
/*
* NAME LOCK - lock
*/
private final func LOCK () {
while (self.LOCKED) {
usleep(BasisConfigRO.COMMON_LOCK_SLICE)
}
self.LOCKED = true
}
/*
* NAME UNLOCK - unlock
*/
private final func UNLOCK () {
self.LOCKED = false
}
public var data: [T]?
/*
* NAME LOCKED - var locked
*/
private final var LOCKED: Bool = false
}
|
lgpl-3.0
|
adb4b2e617bccdece18457b9d87bae4b
| 11.953674 | 71 | 0.515477 | 2.625121 | false | false | false | false |
dalu93/SwiftHelpSet
|
Sources/Foundation/StringExtensions.swift
|
1
|
2047
|
//
// StringExtensions.swift
// SwiftHelpSet
//
// Created by Luca D'Alberti on 7/14/16.
// Copyright © 2016 dalu93. All rights reserved.
//
import Foundation
// MARK: - Localizable
extension String: Localizable {
/// The `localized` version of the `String` instance
public var localized: String {
return NSLocalizedString(self, comment: "")
}
}
// MARK: - String Validation
public extension String {
/// It tells if the `String` instance is a valid email or not
public var isEmail: Bool {
let trimmed = trimmingCharacters(in: NSCharacterSet.whitespaces)
do {
let regex = try NSRegularExpression(
pattern: "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$",
options: .caseInsensitive
)
return regex.firstMatch(
in: trimmed,
options: NSRegularExpression.MatchingOptions(rawValue: 0),
range: NSMakeRange(0, trimmed.characters.count)) != nil
} catch {
return false
}
}
/// It tells if the `String` instance is completely empty (by trimming the spaces)
public var isBlank: Bool {
get {
let trimmed = replacingOccurrences(of: " ", with: "")
return trimmed.isEmpty
}
}
/// It tells if the `String` instance is a valid phone number or not
public var isPhoneNumber: Bool {
let character = NSCharacterSet(
charactersIn: "+0123456789"
).inverted
let inputString: [String] = self.components(separatedBy: character)
let filtered = inputString.joined()
let trimmed = replacingOccurrences(of: " ", with: "")
return trimmed == filtered
}
/// Length of the string
public var length: Int {
return self.characters.count
}
}
|
mit
|
4e828c302e3226dcca10c4ad71eee55b
| 27.027397 | 161 | 0.551808 | 4.516556 | false | false | false | false |
SettlePad/client-iOS
|
SettlePad/BalancesViewController.swift
|
1
|
14896
|
//
// BalancesViewController.swift
// SettlePad
//
// Created by Rob Everhardt on 10/05/15.
// Copyright (c) 2015 SettlePad. All rights reserved.
//
import UIKit
class BalancesViewController: UITableViewController, NewUOmeModalDelegate, ContactsViewControllerDelegate {
var balancesRefreshControl:UIRefreshControl!
var footer = BalancesFooterView(frame: CGRectMake(0, 0, 320, 44))
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showUOmeSegueFromBalances" {
let navigationController = segue.destinationViewController as! UINavigationController
let vc = navigationController.viewControllers[0] as! NewUOmeViewController
vc.delegate = self
}
}
func transactionsPosted(controller:NewUOmeViewController) {
controller.dismissViewControllerAnimated(true, completion: nil)
//do not reload until post completed
}
func reloadContent(error_msg: String?) {
//When coming from ContactViewController
if error_msg != nil {
displayError(error_msg!, viewController: self)
}
self.tableView.reloadData()
}
func transactionsPostCompleted(controller:NewUOmeViewController, error_msg: String?) {
//Goto login screen
if error_msg != nil {
displayError(error_msg!, viewController: self)
if (activeUser == nil) {
dispatch_async(dispatch_get_main_queue()) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("LoginController")
self.presentViewController(vc, animated: false, completion: nil)
}
} else {
self.refreshBalances()
}
} else {
self.refreshBalances()
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
//Add pull to refresh
self.balancesRefreshControl = UIRefreshControl()
self.balancesRefreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
self.balancesRefreshControl.addTarget(self, action: #selector(BalancesViewController.refreshBalances), forControlEvents: UIControlEvents.ValueChanged)
self.tableView.addSubview(balancesRefreshControl)
//Hide additional gridlines, and set gray background for footer
//self.tableView.tableFooterView = UIView(frame:CGRectZero)
}
override func viewWillAppear(animated: Bool) {
//refresh Balances
refreshBalances()
balancesRefreshControl.beginRefreshing()
}
func refreshBalances() {
activeUser!.balances.updateBalances(
{
self.footer.no_results = (activeUser!.balances.sortedCurrencies.count == 0)
dispatch_async(dispatch_get_main_queue(), {
//so it is run now, instead of at the end of code execution
self.tableView.reloadData()
self.balancesRefreshControl.endRefreshing()
self.footer.setNeedsDisplay()
self.tableView.tableFooterView = self.footer
})
},
failure: {error in
displayError(error.errorText, viewController: self)
}
)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return activeUser!.balances.sortedCurrencies.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return activeUser!.balances.getBalancesForCurrency(activeUser!.balances.sortedCurrencies[section]).count
}
/*override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerCell = tableView.dequeueReusableCellWithIdentifier("Header") as! BalanceHeaderCell
let currency = balances.sortedCurrencies[section]
headerCell.currencyLabel.text = currency.toLongName()
let doubleFormat = ".2" //See http://www.codingunit.com/printf-format-specifiers-format-conversions-and-formatted-output
if let currencySummary = balances.getSummaryForCurrency(currency) {
headerCell.getPayLabel.text = "get "+currency.rawValue+" "+currencySummary.get.format(doubleFormat)+", pay "+currency.rawValue+" " + (currencySummary.owe * -1).format(doubleFormat)
headerCell.balanceLabel.text = currency.rawValue+" "+currencySummary.balance.format(doubleFormat)
if currencySummary.balance < 0 {
headerCell.balanceLabel.textColor = Colors.gray.textToUIColor()
} else {
headerCell.balanceLabel.textColor = Colors.success.textToUIColor()
}
} else {
headerCell.getPayLabel.text = "Unknown"
headerCell.balanceLabel.text = "Unknown"
}
return headerCell
}*/
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
/*if balances.sortedCurrencies.count < section {
return "Refresh please" //To overcome bad access
} else {*/
let currency = activeUser!.balances.sortedCurrencies[section]
if let currencySummary = activeUser!.balances.getSummaryForCurrency(currency) {
let doubleFormat = ".2" //See http://www.codingunit.com/printf-format-specifiers-format-conversions-and-formatted-output
//return currency.rawValue+" "+currencySummary.balance.format(doubleFormat)+" (get "+currencySummary.get.format(doubleFormat)+", owe " + (currencySummary.owe * -1).format(doubleFormat)+")"
return currency.rawValue+" "+currencySummary.balance.format(doubleFormat)
} else {
return "Unknown"
}
//}
}
override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
let headerView = view as! UITableViewHeaderFooterView
let currency = activeUser!.balances.sortedCurrencies[section]
if let currencySummary = activeUser!.balances.getSummaryForCurrency(currency) {
if currencySummary.balance < 0 {
headerView.textLabel!.textColor = Colors.gray.textToUIColor()
} else {
headerView.textLabel!.textColor = Colors.success.textToUIColor()
}
}
//headerView.contentView.backgroundColor = UIColor(red: 0/255, green: 181/255, blue: 229/255, alpha: 1.0) //make the background color light blue
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//TODO: add indicator for memos that are not yet reduced and call it queued
let cell = tableView.dequeueReusableCellWithIdentifier("Balance", forIndexPath: indexPath) as! BalanceCell
let balance = activeUser!.balances.getBalancesForCurrency(activeUser!.balances.sortedCurrencies[indexPath.section])[indexPath.row] //of type Balance
// Configure the cell...
var balanceName = balance.resultingName
var balanceFavorite = balance.favorite
let identifier: Identifier? = activeUser!.contacts.getIdentifier(balance.identifierStr)
cell.markup(balanceName, currency: balance.currency, balance: balance.balance, favorite: balanceFavorite)
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let balance = activeUser!.balances.getBalancesForCurrency(activeUser!.balances.sortedCurrencies[indexPath.section])[indexPath.row]
if balance.balance > 0 {
//Remind
let alertController = UIAlertController(title: nil, message: "Do you want to remind " + balance.name + " to pay you?", preferredStyle: .ActionSheet)
//For iPad
alertController.popoverPresentationController?.sourceView = tableView.cellForRowAtIndexPath(indexPath)
alertController.popoverPresentationController?.sourceRect = tableView.cellForRowAtIndexPath(indexPath)!.bounds
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in
// ...
}
alertController.addAction(cancelAction)
let OKAction = UIAlertAction(title: "Remind", style: .Default) { (action) in
balance.remind({
let alertController = UIAlertController(title: "Reminder sent", message: "We've sent " + balance.name + " an email asking to pay you", preferredStyle: .Alert)
let OKAction = UIAlertAction(title: "OK", style: .Default) { (action) in
// ...
}
alertController.addAction(OKAction)
self.presentViewController(alertController, animated: true) {
// ...
}
}, failure: { (error) in
displayError(error.errorText,viewController: self)
})
}
alertController.addAction(OKAction)
self.presentViewController(alertController, animated: true) {
// ...
}
} else {
//Pay
UIPasteboard.generalPasteboard().string = balance.iban //copy iban to clipboard
let title = "Please wire " + balance.currency.rawValue + " " + balance.balance.format(".2") + " to " + balance.resultingName
let msg = "His IBAN is " + balance.iban + " (copied to clipboard)"
let alertController = UIAlertController(title: title, message: msg, preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in
// ...
}
alertController.addAction(cancelAction)
let OKAction = UIAlertAction(title: "I have paid", style: .Default) { (action) in
balance.pay({
let alertController = UIAlertController(title: "Settlement memo sent", message: "Not right? You can cancel it for 5 minutes.", preferredStyle: .Alert)
let OKAction = UIAlertAction(title: "OK", style: .Default) { (action) in
// ...
}
alertController.addAction(OKAction)
self.presentViewController(alertController, animated: true) {
// ...
}
}, failure: { (error) in
displayError(error.errorText,viewController: self)
})
}
alertController.addAction(OKAction)
self.presentViewController(alertController, animated: true) {
// ...
}
}
/*
//Go to contact view if available, otherwise ask to create a new contact
let balance = activeUser!.balances.getBalancesForCurrency(activeUser!.balances.sortedCurrencies[indexPath.section])[indexPath.row] //of type Balance
let identifier: Identifier? = activeUser!.contacts.getIdentifier(balance.identifierStr)
dispatch_async(dispatch_get_main_queue()) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let navigationController = storyboard.instantiateViewControllerWithIdentifier("ContactNavigationController") as! UINavigationController
let destVC = navigationController.viewControllers[0] as! ContactViewController
if let balanceContact = identifier?.contact {
//Go to balanceContact
destVC.contact = balanceContact
destVC.delegate = self
destVC.modalForEditing = true //So display close instead of save and cancel
} else {
//Create a new contact
destVC.contact = Contact(name: balance.name, friendlyName: "", registered: true, favorite: true, autoAccept: AutoAccept.Manual, identifiers: [balance.identifierStr], propagatedToServer: false, user: activeUser!)
}
destVC.delegate = self
self.presentViewController(navigationController, animated: true, completion: nil)
}
*/
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
}
class BalancesFooterView: UIView {
var no_results = true
override init (frame : CGRect) {
super.init(frame : frame)
self.opaque = false //Required for transparent background
}
/*convenience override init () {
self.init(frame:CGRectMake(0, 0, 320, 44)) //By default, make a rect of 320x44
}*/
required init?(coder aDecoder: NSCoder) {
fatalError("This class does not support NSCoding")
}
override func drawRect(rect: CGRect) {
//To make sure we are not adding one layer of text onto another
for view in self.subviews {
view.removeFromSuperview()
}
if self.no_results {
let footerLabel: UILabel = UILabel(frame: rect)
footerLabel.textColor = Colors.gray.textToUIColor()
footerLabel.font = UIFont.boldSystemFontOfSize(11)
footerLabel.textAlignment = NSTextAlignment.Center
footerLabel.text = "You do not owe anyone, nor do they owe you!"
self.addSubview(footerLabel)
}
}
}
class BalanceCell: UITableViewCell {
@IBOutlet var nameLabel: UILabel!
@IBOutlet var amountLabel: UILabel!
@IBOutlet var statusImage: UIImageView!
//var contact: Contact?
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func markup(name: String, currency: Currency, balance: Double, favorite: Bool){
let doubleFormat = ".2" //See http://www.codingunit.com/printf-format-specifiers-format-conversions-and-formatted-output
amountLabel.text = currency.rawValue + " " + balance.format(doubleFormat)
if balance < 0 {
amountLabel.textColor = Colors.gray.textToUIColor()
} else {
amountLabel.textColor = Colors.success.textToUIColor()
}
if favorite {
statusImage.hidden = true
} else {
statusImage.hidden = false
}
nameLabel.text = name
}
}
|
mit
|
5d145de43895207d3eba4be394ee2eaf
| 34.810096 | 216 | 0.720865 | 4.308938 | false | false | false | false |
enricmacias/SwiftFireworks
|
SwiftFireworks/Classes/SwiftFireworks.swift
|
1
|
6943
|
//
// SwiftFireworks.swift
// SwiftFireworks
//
// Created by Enric Macias Lopez on 2017/07/28.
// Copyright © 2017 Enric Macias Lopez. All rights reserved.
//
import UIKit
public class SwiftFireworks: NSObject, CAAnimationDelegate {
//------------------------------------------------------------------------------
// MARK: - Properties -
//------------------------------------------------------------------------------
public static let sharedInstance = SwiftFireworks()
private var fireworksDic: [String:CAShapeLayer] = [:]
//------------------------------------------------------------------------------
// MARK: - Public methods -
//------------------------------------------------------------------------------
/*
* @discussion Shows a firework on the view and position given
* @param view View where the firework must be shown
* @param position Firework position inside the given view
* @param radius Firework radius in scree units
* @param sparkLength Firework sparks length in screen units
* @param sparkThickness Firework sparks thickness in screen units
* @param sparkSeparation Firework sparks separation in screen units
* @param color Firework color
*/
public func showFirework(inView view:UIView, andPosition position:CGPoint, radius:CGFloat? = nil, sparkLength:CGFloat? = nil, sparkThickness:CGFloat? = nil, sparkSeparation:CGFloat? = nil, color:UIColor? = nil) {
// If there are nil parameters, random values are assigned by default
let radius = radius ?? randomCGFloat(min: 50.0, max: 180.0)
let sparkLength = sparkLength ?? randomCGFloat(min: 5.0, max: 20.0)
let sparkThickness = sparkThickness ?? randomCGFloat(min: 1, max: 6)
let sparkSeparation = sparkSeparation ?? randomCGFloat(min: 20, max: 50)
let color = color ?? randomColor()
// Create firework
let firework: CAShapeLayer = CAShapeLayer()
firework.frame = CGRect(x: position.x - radius, y: position.y - radius, width: radius*2, height: radius*2)
firework.lineWidth = sparkLength
firework.strokeColor = color.cgColor
firework.fillColor = UIColor.clear.cgColor
//firework = UIColor.brown.cgColor
firework.lineDashPattern = [sparkThickness, sparkSeparation] as [NSNumber]
let circlePath = UIBezierPath(arcCenter: CGPoint(x: radius, y: radius),
radius: radius,
startAngle: CGFloat(0.0),
endAngle: CGFloat(Double.pi*2),
clockwise: false)
firework.path = circlePath.cgPath
firework.mask = mask(radius: radius)
view.layer.addSublayer(firework)
animate(firework: firework)
}
/*
* @discussion Shows a set of fireworks on the view and position given
* @param view View where the firework must be shown
* @param position Firework position inside the given view
* @param num Number of fireworks to be shown
* @param color Firework color
*/
public func showFireworkSet(inView view:UIView, andPosition position:CGPoint, numberOfFireworks num:UInt? = nil) {
var num = num ?? 5
num = (num == 0) ? 1 : num
for _ in 1...num {
showFirework(inView: view,
andPosition: position)
}
}
//------------------------------------------------------------------------------
// MARK: - Private methods -
//------------------------------------------------------------------------------
private func mask(radius:CGFloat) -> CAShapeLayer {
let mask: CAShapeLayer = CAShapeLayer()
mask.frame = CGRect(x: 0, y: 0, width: radius*2, height: radius*2)
let arcCenter = CGPoint(x: radius, y: radius)
let startAngle = CGFloat(0.0)
let endAngle = CGFloat(Double.pi*2)
let donutPath = CGMutablePath()
donutPath.addArc(center: arcCenter,
radius: radius + radius*0.25,
startAngle: startAngle,
endAngle: endAngle,
clockwise: false)
donutPath.addArc(center: arcCenter,
radius: radius*0.75,
startAngle: startAngle,
endAngle: endAngle,
clockwise: false)
mask.path = donutPath
mask.fillRule = kCAFillRuleEvenOdd
return mask
}
private func animate(firework:CAShapeLayer) {
let animation = CABasicAnimation(keyPath: "transform.scale")
animation.duration = 0.5
animation.fromValue = 0.001
animation.toValue = 1.0
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
firework.add(animation, forKey: "boom")
let maskAnimation = CABasicAnimation(keyPath: "transform.scale")
maskAnimation.duration = 2.0
maskAnimation.fromValue = 1.0
maskAnimation.toValue = 2.0
maskAnimation.fillMode = kCAFillModeForwards
maskAnimation.isRemovedOnCompletion = false
maskAnimation.delegate = self
maskAnimation.setValue(firework.description, forKey: "vanish")
// Tracking fireworks to remove them from the superlayer when animation finishes
fireworksDic[firework.description] = firework
firework.mask?.add(maskAnimation, forKey: "vanish")
}
//------------------------------------------------------------------------------
// MARK: - Helpers -
//------------------------------------------------------------------------------
public func randomCGFloat(min: CGFloat, max: CGFloat) -> CGFloat {
return CGFloat(Float(arc4random()) / Float(UINT32_MAX)) * (max - min) + min
}
public func randomInt(min: Int, max: Int) -> Int {
return Int(arc4random_uniform(UInt32(max - min + 1))) + min
}
public func randomColor() -> UIColor{
//Generate between 0 to 1
let red:CGFloat = CGFloat(drand48())
let green:CGFloat = CGFloat(drand48())
let blue:CGFloat = CGFloat(drand48())
return UIColor(red:red, green: green, blue: blue, alpha: 1.0)
}
//------------------------------------------------------------------------------
// MARK: - CAAnimationDelegate -
//------------------------------------------------------------------------------
public func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
let firework = fireworksDic[anim.value(forKey: "vanish") as! String]
firework?.removeFromSuperlayer()
}
}
|
mit
|
4492b036e96113f045a3b13c477a7936
| 40.568862 | 216 | 0.531115 | 5.215627 | false | false | false | false |
skonmeme/Reservation
|
Reservation/AppDelegate.swift
|
1
|
4593
|
//
// AppDelegate.swift
// Reservation
//
// Created by Sung Gon Yi on 23/12/2016.
// Copyright © 2016 skon. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. 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 active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "Reservation")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
|
mit
|
e899b7486b66a5565edfa10706cf9c46
| 48.376344 | 285 | 0.685758 | 5.857143 | false | false | false | false |
hongqingWang/HQSwiftMVVM
|
HQSwiftMVVM/HQSwiftMVVM/Classes/View/A/Cell/HQACell.swift
|
1
|
2790
|
//
// HQACell.swift
// HQSwiftMVVM
//
// Created by 王红庆 on 2017/8/28.
// Copyright © 2017年 王红庆. All rights reserved.
//
import UIKit
/// 头像的宽度
let AvatarImageViewWidth: CGFloat = 35
class HQACell: UITableViewCell {
var viewModel: HQStatusViewModel? {
didSet {
topView.viewModel = viewModel
contentLabel.text = viewModel?.status.text
bottomView.viewModel = viewModel
var height: CGFloat = 0
height = viewModel?.pictureViewSize?.height ?? 0
pictureView.snp.updateConstraints { (make) in
make.height.equalTo(height)
}
// print("aaa===\(viewModel?.status.pic_urls)")
// pictureView.urls = viewModel?.status.pic_urls
}
}
/// 顶部视图
fileprivate lazy var topView: HQACellTopView = HQACellTopView()
/// 正文
fileprivate lazy var contentLabel: UILabel = UILabel(hq_title: "正文", fontSize: 15, color: UIColor.darkGray)
/// 配图视图
fileprivate lazy var pictureView: HQACellPictureView = HQACellPictureView()
/// 底部视图
fileprivate lazy var bottomView: HQACellBottomView = HQACellBottomView()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
selectionStyle = .none
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - UI
extension HQACell {
fileprivate func setupUI() {
addSubview(topView)
addSubview(contentLabel)
addSubview(pictureView)
addSubview(bottomView)
topView.snp.makeConstraints { (make) in
make.top.equalTo(self)
make.left.equalTo(self)
make.right.equalTo(self)
make.height.equalTo(margin * 2 + AvatarImageViewWidth)
}
contentLabel.snp.makeConstraints { (make) in
make.top.equalTo(topView.snp.bottom).offset(margin / 2)
make.left.equalTo(self).offset(margin)
make.right.equalTo(self).offset(-12)
}
pictureView.snp.makeConstraints { (make) in
make.top.equalTo(contentLabel.snp.bottom)
make.left.equalTo(contentLabel)
make.right.equalTo(contentLabel)
make.bottom.equalTo(bottomView.snp.top).offset(-12)
make.height.equalTo(300)
}
bottomView.snp.makeConstraints { (make) in
make.left.equalTo(self)
make.right.equalTo(self)
make.height.equalTo(44)
make.bottom.equalTo(self)
}
}
}
|
mit
|
c5de6fcde429442b3681c71b434420de
| 29.366667 | 111 | 0.59678 | 4.45114 | false | false | false | false |
mysangle/algorithm-study
|
maximal-square/MaximalSquare.swift
|
1
|
1095
|
func testSquare(_ matrix: [[Character]], _ startX: Int, _ startY: Int, _ maxX: Int, _ maxY: Int) -> Int {
var xx = startX + 1
var yy = startY + 1
var m = 1
outerLoop: while xx < maxX && yy < maxY {
var x = xx - startX
var y = 0
var count = 0
while y + startY < maxY && y <= x {
if matrix[startX + x][startY + y] == "0" {
break outerLoop
}
count += 1
y += 1
}
y = y - 1
x -= 1
while x >= 0 {
if (matrix[startX + x][startY + y] == "0") {
break outerLoop
}
count += 1
x -= 1
}
m = m + count
xx += 1
yy += 1
}
return m
}
func maximalSquare(_ matrix: [[Character]]) -> Int {
var maximum = 0
for x in 0..<matrix.count {
for y in 0..<matrix[x].count {
if matrix[x][y] != "0" {
maximum = max(maximum, testSquare(matrix, x, y, matrix.count, matrix[x].count))
}
}
}
return maximum
}
|
mit
|
dac072013fec2770a3b4bfeb5849ae76
| 24.465116 | 105 | 0.410959 | 3.828671 | false | false | false | false |
Pyroh/Fluor
|
Fluor/Models/Items.swift
|
1
|
3542
|
//
// RulesTableItem.swift
//
// Fluor
//
// MIT License
//
// Copyright (c) 2020 Pierre Tacchi
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Cocoa
import DefaultsWrapper
class Item: NSObject, Identifiable {
var notificationSource: NotificationSource { .undefined }
let id: String
@objc let url: URL
@objc dynamic var behavior: AppBehavior
@objc var icon: NSImage { NSWorkspace.shared.icon(forFile: self.url.path) }
@objc var name: String { Bundle(path: self.url.path)?.localizedInfoDictionary?["CFBundleName"] as? String ?? self.url.deletingPathExtension().lastPathComponent }
override var hash: Int {
self.url.hashValue
}
init(id: String, url: URL, behavior: AppBehavior) {
self.id = id
self.url = url
self.behavior = behavior
}
}
final class RunningApp: Item, BehaviorDidChangeObserver {
override var notificationSource: NotificationSource { .runningApp }
let pid: pid_t
@objc let isApp: Bool
override var hash: Int {
Int(self.pid)
}
init(id: String, url: URL, behavior: AppBehavior, pid: pid_t, isApp: Bool) {
self.pid = pid
self.isApp = isApp
super.init(id: id, url: url, behavior: behavior)
self.startObservingBehaviorDidChange()
}
deinit {
self.stopObservingBehaviorDidChange()
}
// MARK: BehaviorDidChangeObserver
func behaviorDidChangeForApp(notification: Notification) {
guard let id = notification.userInfo?["id"] as? String, self.id == id,
let appBehavior = notification.userInfo?["behavior"] as? AppBehavior else { return }
self.behavior = appBehavior
}
}
final class Rule: Item, UserDefaultsConvertible {
override var notificationSource: NotificationSource { .rule }
override var hash: Int {
self.url.hashValue
}
// MARK: UserDefaultsConvertible
func convertedObject() -> [String: Any] {
["id": self.id, "path": self.url.path, "behavior": self.behavior.rawValue]
}
static func instanciate(from object: [String: Any]) -> Rule? {
guard let id = object["id"] as? String, let path = object["path"] as? String, let rawBehavior = object["behavior"] as? Int, let behavior = AppBehavior(rawValue: rawBehavior) else { return nil }
let url = URL(fileURLWithPath: path)
return Rule(id: id, url: url, behavior: behavior)
}
}
|
mit
|
0cdb98a0461a3ef0c13b701aeea83e77
| 33.38835 | 201 | 0.673348 | 4.288136 | false | false | false | false |
miguelgutierrez/Curso-iOS-Swift-Programming-Netmind
|
newsApp 1.8/newsApp/Articulo.swift
|
1
|
1275
|
//
// Articulo.swift
// newsApp
//
// Created by Miguel Gutiérrez Moreno on 2/2/15.
// Copyright (c) 2015 MGM. All rights reserved.
//
import Foundation
import CoreData
@objc(Articulo)
class Articulo: NSManagedObject {
// MARK: properties
@NSManaged var fecha: NSDate
@NSManaged var nombre: String
@NSManaged var texto: String
// MARK: métodos de ayuda
class func entityName() -> String {
return "Articulo"
}
class func articulos() -> [Articulo]? {
let request = NSFetchRequest()
let model = StoreNewsApp.defaultStore().model
let entidad = model.entitiesByName[Articulo.entityName()]
request.entity = entidad
let sd = NSSortDescriptor(key: "nombre", ascending: true)
request.sortDescriptors = [sd]
let context = StoreNewsApp.defaultStore().context
let result: [AnyObject]?
do {
result = try context.executeFetchRequest(request)
return result as? [Articulo]
} catch let error as NSError {
NSException.raise(MensajesErrorCoreData.fetchFailed, format: MensajesErrorCoreData.errorFetchObjectFormat, arguments:getVaList([error]))
return nil
}
}
}
|
mit
|
4ca5ab47b002a8bc9d58a0c5ee0f5cb0
| 25.520833 | 148 | 0.626866 | 4.34471 | false | false | false | false |
wscqs/FMDemo-
|
FMDemo/Classes/Module/Main/MainTableView.swift
|
1
|
2238
|
//
// MainTableView.swift
// FMDemo
//
// Created by mba on 17/2/9.
// Copyright © 2017年 mbalib. All rights reserved.
//
import UIKit
class MainTableView: RefreshBaseTableView {
var parentVC: MainViewController?
/// 加载刷新数据
override func loadData() {
KeService.actionGetCourses(start: start, num: num, success: { (bean) in
if self.action == .loadNew {
self.dataList?.removeAll()
}
if let datas = bean.data {
for data in datas {
self.dataList?.append(data)
}
}
self.loadCompleted()
}) { (error) in
if 40301 == error.code {
self.loadError(error, isEmptyData: true)
} else {
self.loadError(error, isEmptyData: false)
}
}
}
}
// MARK: - tableviewDelegate
extension MainTableView{
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if let bean = self.dataList?[indexPath.row] as? GetCoursesData {
if let url = bean.url {
parentVC?.pushPlayCourseVC(url: url)
} else {
parentVC?.pushCourseDetailVC(cid: bean.cid ?? "",title: bean.title ?? "")
}
}
}
}
// MARK: - DZNEmptyDataSetSource, DZNEmptyDataSetDelegate
extension MainTableView {
func image(forEmptyDataSet scrollView: UIScrollView!) -> UIImage! {
return #imageLiteral(resourceName: "course_emptyBgimg")
}
func title(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
let attributes = [ NSFontAttributeName: UIFont.boldSystemFont(ofSize: 15.0), NSForegroundColorAttributeName: UIColor.colorWithHexString("5bacff")]
let text = "当前无任何课程"
return NSAttributedString(string: text, attributes: attributes)
}
func spaceHeight(forEmptyDataSet scrollView: UIScrollView!) -> CGFloat {
return 20
}
func verticalOffset(forEmptyDataSet scrollView: UIScrollView!) -> CGFloat {
return -60
}
}
|
apache-2.0
|
defe1768c5a301094266222bcc0d3d3b
| 28.851351 | 154 | 0.588954 | 4.740343 | false | false | false | false |
mumbler/PReVo-iOS
|
ReVoModeloj/Komunaj/Modeloj/Fako.swift
|
1
|
859
|
//
// Fako.swift
// PoshReVo
//
// Created by Robin Hill on 5/4/20.
// Copyright © 2020 Robin Hill. All rights reserved.
//
import Foundation
/*
Reprezentas fakon al kiu apartenas vorto aŭ frazaĵo. Uzataj en kelkaj difinoj.
*/
public struct Fako {
public let kodo: String
public let nomo: String
public init(kodo: String, nomo: String) {
self.kodo = kodo
self.nomo = nomo
}
}
// MARK: - Equatable
extension Fako: Equatable {
public static func ==(lhs: Fako, rhs: Fako) -> Bool {
return lhs.kodo == rhs.kodo && lhs.nomo == rhs.nomo
}
}
// MARK: - Comparable
extension Fako: Comparable {
public static func < (lhs: Fako, rhs: Fako) -> Bool {
return lhs.nomo.compare(rhs.nomo, options: .caseInsensitive, range: nil, locale: Locale(identifier: "eo")) == .orderedAscending
}
}
|
mit
|
e1863e124131f4c2743eb9aa11386f4a
| 21.526316 | 135 | 0.630841 | 3.17037 | false | false | false | false |
tonychan818/TCMedia
|
TCMedia/VCTrim.swift
|
1
|
25560
|
//
// VCTrim.swift
// TCMedia
//
// Created by Tony on 26/8/15.
// Copyright (c) 2015 Tony. All rights reserved.
//
import UIKit
import MediaPlayer
import SVProgressHUD
import SCRecorder
protocol PTFrameWindowControlDelegate:class{
func PTFrameWindowControlVideoShouldReset(isSetFront:Bool)
}
class PTFrameWindowControl: UIControl,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout {
weak var delegate:PTFrameWindowControlDelegate?
var slider = UIView()
var sliderMovementConstraint = CGFloat(0)
// var blockedPortion = CALayer()
var blockedView = UIView()
var blockedLineView = UIView()
var framesView = UICollectionView(frame: CGRectZero, collectionViewLayout: PTFrameWindowControl.defaultLayout(CGSize(width: 0, height: 0)))
var offset: NSTimeInterval = Double(C.MAX_DURATION)
var numOfFrames: Int = 0
var framesPerSecond: Int32 = 0
var frames = [UIImage]()
var videoURL:NSURL!
var lastFrameWidth = CGFloat(0.0)
var lastNumOfFrames: Int = -1
var slideBegin = false
let frameWindowPadding = CGFloat(20)
let frameWindowHeight = CGFloat(40)
var durationInSeconds: Float64!
var imgPointer:UIImageView!
func resetPointer(){
var pointerSize = CGFloat(20)
if(self.imgPointer != nil){
self.imgPointer.frame = CGRectMake(frameWindowPadding - pointerSize/2, 0, pointerSize, pointerSize)
}
println("resetPointer")
}
func correctEndPointerPosition(){
self.imgPointer.frame = CGRectMake(self.blockedLineView.frame.origin.x - self.imgPointer.frame.size.width/2, self.imgPointer.frame.origin.y, self.imgPointer.frame.size.width, self.imgPointer.frame.size.width)
}
func setSliderAndLineEndPosition(){
let indicatorSize = CGFloat(26)
slider.clipsToBounds = true
slider.layer.cornerRadius = indicatorSize/2.0
slider.frame = CGRect(x: self.sliderMovementConstraint,
y: self.frame.height - indicatorSize
, width:indicatorSize, height: indicatorSize)
println("setSliderAndLineEndPosition slider: \(self.slider.frame.origin.x) blockLineVie: \(self.blockedLineView.frame.origin.x)")
self.blockedLineView.frame = CGRectMake(slider.frame.origin.x + slider.frame.size.width/2, 0, 1, self.frame.size.height)
println("setSliderAndLineEndPosition done")
}
func reloadLayoutSubviews(){
self.lastFrameWidth = -1
self.setNeedsLayout()
}
override func layoutSubviews() {
if(self.lastFrameWidth != self.frame.size.width){
println("layoutSubViews!!")
framesView.frame = CGRectMake(frameWindowPadding, frameWindowPadding, self.frame.size.width - frameWindowPadding * 2, frameWindowHeight)
if(self.sliderMovementConstraint == 0){
self.sliderMovementConstraint = self.framesView.frame.origin.x + self.framesView.frame.size.width - slider.frame.size.width/2
}
self.lastFrameWidth = self.frame.size.width
self.setSliderAndLineEndPosition()
}
var maxX = self.framesView.frame.origin.x + self.framesView.frame.size.width - self.slider.frame.size.width
if(self.slider.frame.origin.x > maxX && !self.slideBegin){
self.slider.frame = CGRectMake(maxX + self.slider.frame.size.width/2,
self.slider.frame.origin.y,
self.slider.frame.size.width,
self.slider.frame.size.height)
self.blockedLineView.frame = CGRectMake(slider.frame.origin.x + slider.frame.size.width/2, 0, 1, self.self.frame.size.height)
}
}
func updatePointerSizeWithProgress(p:CGFloat){
var pointerPosition = self.framesView.frame.origin.x + (self.blockedLineView.frame.origin.x - self.framesView.frame.origin.x) * p - self.imgPointer.frame.size.width/2
if(pointerPosition < self.imgPointer.frame.size.width/2){
self.resetPointer()
}
else{
self.imgPointer.frame = CGRectMake(pointerPosition, self.imgPointer.frame.origin.y, self.imgPointer.frame.size.width, self.imgPointer.frame.size.height)
}
// println("updatePointer frame: \(self.imgPointer.frame)")
}
class func defaultLayout(headerSize: CGSize) -> UICollectionViewFlowLayout {
let layout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsetsZero
layout.headerReferenceSize = headerSize
layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
layout.minimumInteritemSpacing = 0.0
layout.minimumLineSpacing = 0.0
return layout
}
func getVideoStartEnd() -> (videoStart:CGFloat,videoEnd:CGFloat,frameStartX:CGFloat,frameEndX:CGFloat){
//maually calculate contentFull Width
// var contentFullWidth = self.framesView.contentSize.width
var contentFullWidth = self.framesView.frame.size.width/CGFloat(C.MAX_DURATION) * CGFloat(numOfFrames)
var contentOffsetX = self.framesView.contentOffset.x
var lineX = self.blockedLineView.frame.origin.x - self.framesView.frame.origin.x
var realLineX = contentOffsetX + lineX
println("getVideoEnd contentOffsetX: \(contentOffsetX), contentFullWidth: \(contentFullWidth), frame X: \(self.framesView.frame.origin.x)")
var s = contentOffsetX/contentFullWidth * CGFloat(self.durationInSeconds)
var e = realLineX / contentFullWidth * CGFloat(self.durationInSeconds)
println("getVIdeoEnd frameWidth:\(self.framesView.frame.size.width), numOfFrame: \(self.numOfFrames)")
println("getVideoEnd realLineX: \(realLineX), fullWidth: \(contentFullWidth), duration: \(self.durationInSeconds)")
return (s,e,self.framesView.frame.origin.x - self.imgPointer.frame.size.width/2,
self.blockedLineView.frame.origin.x - self.imgPointer.frame.size.width/2)
}
func setupViews(setupDoneHandler:(Void)->(Void)) {
self.framesView.dataSource = self
self.framesView.delegate = self
self.framesView.bounces = false
self.framesView.showsHorizontalScrollIndicator = false
framesView.backgroundColor = UIColor.clearColor()
framesView.layer.borderWidth = 1
framesView.layer.borderColor = UIColor.orangeColor().CGColor
addSubview(framesView)
slider.backgroundColor = UIColor.redColor()
// slider.layer.cornerRadius = 6.0
var panGesture = UIPanGestureRecognizer(target: self, action: "moveSlider:")
slider.userInteractionEnabled = true
slider.addGestureRecognizer(panGesture)
addSubview(slider)
self.blockedLineView.backgroundColor = slider.backgroundColor
addSubview(self.blockedLineView)
self.framesView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
self.framesView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "LoadingCell")
self.blockedView = UIView()
self.addSubview(self.blockedView)
self.blockedView.backgroundColor = UIColor(red: 18/255, green: 17/255, blue: 17/255, alpha: 0.5)
self.imgPointer = UIImageView(image: UIImage(named: "pointer"))
self.imgPointer.tintColor = UIColor.whiteColor()
self.addSubview(self.imgPointer)
self.resetPointer()
self.fetchFrames { (Void) -> (Void) in
setupDoneHandler()
}
}
func moveSlider(recognizer: UIPanGestureRecognizer) {
self.slideBegin = true
if(recognizer.state == UIGestureRecognizerState.Changed) {
var currentLocation = recognizer.locationInView(self)
var minX = self.framesView.frame.origin.x + CGFloat(C.MIN_DURATION) * self.framesView.frame.size.width
var maxX = self.framesView.frame.origin.x + self.framesView.frame.size.width - self.slider.frame.size.width/2
var finalX = currentLocation.x
if(currentLocation.x < minX){
finalX = minX
}
else if(currentLocation.x > maxX){
finalX = maxX
}
self.slider.frame = CGRectMake(finalX,
self.slider.frame.origin.y,
self.slider.frame.size.width,
self.slider.frame.size.height)
self.blockedLineView.frame = CGRectMake(slider.frame.origin.x + slider.frame.size.width/2, 0, 1, self.self.frame.size.height)
self.blockedView.frame = CGRect(x: self.slider.frame.origin.x + self.slider.frame.size.width/2,
y: self.framesView.frame.origin.y,
width: self.framesView.frame.size.width - (self.slider.frame.origin.x - self.framesView.frame.origin.x + self.slider.frame.width/2),
height: self.framesView.frame.size.height)
// var numOfSelectedFrames = (self.blockedView.frame.origin.x / (bounds.width / 8))
var numOfSelectedFrames = (self.blockedView.frame.origin.x - self.framesView.frame.origin.x) / (self.framesView.frame.size.width / CGFloat(C.MAX_DURATION))
offset = NSTimeInterval(numOfSelectedFrames)
self.delegate?.PTFrameWindowControlVideoShouldReset(false)
} else if(recognizer.state == UIGestureRecognizerState.Ended) {
sendActionsForControlEvents(UIControlEvents.ValueChanged)
}
}
func fetchFrames(durationTimeGotHandler:(Void)->(Void)) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
var asset = AVURLAsset(URL: self.videoURL, options: nil)
var movieTrack = asset.tracksWithMediaType(AVMediaTypeVideo)[0] as! AVAssetTrack
var imageGenerator = AVAssetImageGenerator(asset: asset)
imageGenerator.appliesPreferredTrackTransform = true
var maxSize = CGSizeMake(320, 180);
imageGenerator.maximumSize = maxSize
self.durationInSeconds = CMTimeGetSeconds(asset.duration)
println("video duration : \(self.durationInSeconds)")
self.framesPerSecond = Int32(movieTrack.nominalFrameRate)
var timePerFrame = 1.0 / Float64(movieTrack.nominalFrameRate)
var totalFrames = self.durationInSeconds * Float64(movieTrack.nominalFrameRate)
self.numOfFrames = Int(ceil(self.durationInSeconds))
var isCallbackCalled = false
var intDurationInSeconds = round(self.durationInSeconds)
for var i:Float64 = 0; i < intDurationInSeconds ; i++ {
var time = CMTimeMakeWithSeconds(i, Int32(movieTrack.nominalFrameRate))
var image = imageGenerator.copyCGImageAtTime(time, actualTime: nil, error: nil)
if(image != nil) {
self.frames.append(UIImage(CGImage:image!)!)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.framesView.reloadData()
})
}
if(((i == intDurationInSeconds - 1) || (Int(i) > C.MAX_DURATION)) && !isCallbackCalled){
//if it is last one
dispatch_sync(dispatch_get_main_queue(), { () -> Void in
durationTimeGotHandler()
})
isCallbackCalled = true
}
}
})
}
//Collection View Delegate
func scrollViewDidScroll(scrollView: UIScrollView) {
self.delegate?.PTFrameWindowControlVideoShouldReset(true)
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// println("collectionView numOfFrames: \(numOfFrames)")
if(self.lastNumOfFrames != self.numOfFrames) {
if(numOfFrames < C.MAX_DURATION && frames.count == numOfFrames){
self.sliderMovementConstraint = self.framesView.frame.origin.x + self.framesView.frame.size.width - slider.frame.size.width/2
}
else{
self.sliderMovementConstraint = self.framesView.frame.origin.x - slider.frame.size.width/2 + CGFloat(numOfFrames) * (collectionView.bounds.width / CGFloat(C.MAX_DURATION))
}
self.reloadLayoutSubviews()
self.lastNumOfFrames = numOfFrames
}
return frames.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
var cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as? UICollectionViewCell
var videoThumbnail = frames[indexPath.row]
var sx = cell!.bounds.width / videoThumbnail.size.width
var sy = cell!.bounds.height / videoThumbnail.size.height
var cellThumbnail = UIImageView(image:videoThumbnail)
cellThumbnail.transform = CGAffineTransformScale(cellThumbnail.transform, sx, sy)
cellThumbnail.frame.origin.x = 0
cellThumbnail.frame.origin.y = 0
cell!.addSubview(cellThumbnail)
return cell!
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
// let itemSize = CGSize(width: floor(collectionView.bounds.width / 8), height: floor(collectionView.bounds.height))
let itemSize = CGSizeMake(self.framesView.frame.size.width/CGFloat(C.MAX_DURATION), frameWindowHeight)
return itemSize
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
return 0
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
// do something
}
}
class VCTrim: UIViewController,PTFrameWindowControlDelegate {
@IBOutlet weak var scrollView:UIScrollView!
@IBOutlet weak var viewHeader:UIView!
@IBOutlet weak var frameWindow:PTFrameWindowControl!
var mediaPlayer = MPMoviePlayerController()
var videoURL = NSURL()
var videoHeight = CGFloat(0)
var videoWidth = CGFloat(0)
var initialPlaybackTime: NSTimeInterval = 0
var endingPlaybackTime: NSTimeInterval = Double(C.MAX_DURATION)
var cropLine1 = CALayer()
var cropLine2 = CALayer()
var cropLine3 = CALayer()
var cropLine4 = CALayer()
var cropLayer = CALayer()
var videoMonitorTimer = NSTimer()
var videoFrameObj:(videoStart:CGFloat,videoEnd:CGFloat,frameStartX:CGFloat,frameEndX:CGFloat)!
var indicatorUpdateInterval = 0.05
@IBOutlet weak var btnDone:UIButton!
deinit{
println("viewTrim deinit");
}
func stopMediaPlayer(){
self.frameWindow.resetPointer()
if(self.mediaPlayer.playbackState == MPMoviePlaybackState.Playing){
self.mediaPlayer.pause()
}
if(self.videoMonitorTimer.valid){
self.videoMonitorTimer.invalidate()
}
}
func updatePlayTime(){
var progress = (CGFloat(self.mediaPlayer.currentPlaybackTime)-self.videoFrameObj.videoStart)/(self.videoFrameObj.videoEnd-self.videoFrameObj.videoStart)
//update indicator
// println("updatePlayTime currentTime: \(self.mediaPlayer.currentPlaybackTime), start: \(self.videoFrameObj.videoStart) end: \(self.videoFrameObj.videoEnd), p: \(progress)")
self.frameWindow.updatePointerSizeWithProgress(progress)
if(self.mediaPlayer.currentPlaybackTime >= self.mediaPlayer.endPlaybackTime - indicatorUpdateInterval){
// println("movie end!!")
self.mediaPlayer.pause()
self.videoMonitorTimer.invalidate()
self.frameWindow.correctEndPointerPosition()
}
}
func videoDidPaused(){
}
func videoDidPlaying(){
if(self.videoMonitorTimer.valid){
self.videoMonitorTimer.invalidate()
}
self.videoMonitorTimer = NSTimer.scheduledTimerWithTimeInterval(indicatorUpdateInterval, target: self, selector: "updatePlayTime", userInfo: nil, repeats: true)
NSRunLoop.currentRunLoop().addTimer(self.videoMonitorTimer, forMode: NSRunLoopCommonModes)
}
func playbackStateChanged(){
switch(self.mediaPlayer.playbackState){
case MPMoviePlaybackState.Stopped:
println("Stopped")
self.videoDidPaused()
case MPMoviePlaybackState.Playing:
println("Playing currentPlaybackTime: \(self.mediaPlayer.currentPlaybackTime)")
self.videoDidPlaying()
case MPMoviePlaybackState.Paused:
println("Paused")
self.videoDidPaused()
case MPMoviePlaybackState.Interrupted:
println("Interrupted")
case MPMoviePlaybackState.SeekingForward:
println("SeekingForward")
case MPMoviePlaybackState.SeekingBackward:
println("SeekingBackward")
default:
println("default")
}
println("playbackStateChanged: \(self.mediaPlayer.playbackState.rawValue)")
}
func playbackEnded(){
println("playbackEnded: \(self.mediaPlayer.playbackState.rawValue)")
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
if(videoMonitorTimer.valid){
videoMonitorTimer.invalidate()
}
NSNotificationCenter.defaultCenter().removeObserver(self, name: MPMoviePlayerPlaybackStateDidChangeNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: MPMoviePlayerPlaybackDidFinishNotification, object: nil)
self.mediaPlayer.stop()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "playbackStateChanged", name: MPMoviePlayerPlaybackStateDidChangeNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "playbackEnded", name: MPMoviePlayerPlaybackDidFinishNotification, object: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
self.scrollView.contentOffset = CGPointZero
self.scrollView.showsHorizontalScrollIndicator = false
self.scrollView.showsVerticalScrollIndicator = false
self.scrollView.bounces = false
//media
self.scrollView.addSubview(mediaPlayer.view)
self.scrollView.contentSize = CGSizeMake(videoWidth, videoHeight)
self.mediaPlayer.view.frame = CGRect(x: 0, y: 0, width:videoWidth, height: videoHeight)
self.mediaPlayer.contentURL = self.videoURL
self.mediaPlayer.shouldAutoplay = false
self.mediaPlayer.prepareToPlay()
self.mediaPlayer.movieSourceType = MPMovieSourceType.File
self.mediaPlayer.controlStyle = MPMovieControlStyle.None
self.mediaPlayer.scalingMode = MPMovieScalingMode.AspectFit
self.mediaPlayer.initialPlaybackTime = self.initialPlaybackTime
self.mediaPlayer.endPlaybackTime = self.endingPlaybackTime
self.mediaPlayer.pause()
self.addCropLine()
self.frameWindow.videoURL = self.videoURL
self.frameWindow.delegate = self
self.frameWindow.setupViews { (Void) -> (Void) in
println("frameWindow done!!")
//for handle video bar not set yet problem
NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: "replay", userInfo: nil, repeats: false)
}
}
func addCropLine(){
cropLine1.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.5).CGColor
cropLayer.addSublayer(cropLine1)
cropLine2.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.5).CGColor
cropLayer.addSublayer(cropLine2)
cropLine3.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.5).CGColor
cropLayer.addSublayer(cropLine3)
cropLine4.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.5).CGColor
cropLayer.addSublayer(cropLine4)
self.view.layer.addSublayer(cropLayer)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let paddingHeight = self.viewHeader.frame.size.height
cropLayer.frame = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: UIScreen.mainScreen().bounds.width)
cropLine1.frame = CGRect(x: 0, y: paddingHeight+cropLayer.bounds.height / 3, width: cropLayer.bounds.width, height: cropLayer.bounds.height * 0.005)
cropLine2.frame = CGRect(x: 0, y: paddingHeight + 2 * cropLayer.bounds.height / 3, width: cropLayer.bounds.width, height: cropLayer.bounds.height * 0.005)
cropLine3.frame = CGRect(x: cropLayer.bounds.width / 3, y: paddingHeight+0, width: self.view.bounds.width * 0.005, height: cropLayer.bounds.height)
cropLine4.frame = CGRect(x: cropLine3.frame.origin.x + cropLayer.bounds.width / 3, y: paddingHeight+0, width: self.view.bounds.width * 0.005, height: cropLayer.bounds.height)
}
override func prefersStatusBarHidden() -> Bool {
return true
}
func setup(url:NSURL,videoWidth:CGFloat,videoHeight:CGFloat){
self.videoURL = url
self.videoWidth = videoWidth
self.videoHeight = videoHeight
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func btnReplayClicked(){
self.replay()
}
func replay(){
println("replay!")
self.videoFrameObj = self.frameWindow.getVideoStartEnd()
if(self.videoFrameObj.videoEnd == 0){
//not ready
println("not ready, call it later..")
self.frameWindow.reloadLayoutSubviews()
NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "replay", userInfo: nil, repeats: false)
}
else{
println("start: \(self.videoFrameObj.videoStart), end: \(self.videoFrameObj.videoEnd)")
self.mediaPlayer.currentPlaybackTime = Double(self.videoFrameObj.videoStart)
self.mediaPlayer.endPlaybackTime = Double(self.videoFrameObj.videoEnd)
self.initialPlaybackTime = Double(self.videoFrameObj.videoStart)
self.endingPlaybackTime = Double(self.videoFrameObj.videoEnd)
self.mediaPlayer.play()
println("setted currentPlaybackTime: \(self.mediaPlayer.currentPlaybackTime)")
}
}
@IBAction func btnBackClicked(){
self.navigationController?.popViewControllerAnimated(true)
}
@IBAction func btnDoneClicked(){
self.trimVideoView()
}
func trimVideoView(){
self.stopMediaPlayer()
SVProgressHUD.show()
var trimmedVideo = AVURLAsset(URL: videoURL, options: nil)
var videoProcessor = PTVideoProcessor()
//initialize videoProcessor
videoProcessor.asset = trimmedVideo
videoProcessor.videoHeight = videoHeight
videoProcessor.videoWidth = videoWidth
// videoProcessor.indicator = indicator
videoProcessor.cropOffsetX = self.scrollView.contentOffset.x
videoProcessor.cropOffsetY = self.scrollView.contentOffset.y
videoProcessor.offset = self.frameWindow.offset
videoProcessor.initialPlaybackTime = initialPlaybackTime
videoProcessor.endingPlaybackTime = endingPlaybackTime
videoProcessor.framesPerSecond = self.frameWindow.framesPerSecond
println("trim with:\nWidth: \(videoWidth)\nHeight: \(videoHeight)\n cropX: \(videoProcessor.cropOffsetX),\n cropY: \(videoProcessor.cropOffsetY),\n offset: \(videoProcessor.offset),\n initTime: \(videoProcessor.initialPlaybackTime), \n endTime: \(videoProcessor.endingPlaybackTime), \n framesPerSecond: \(videoProcessor.framesPerSecond)")
//crop and trim video
videoProcessor.cropVideo { (Void) -> (Void) in
SVProgressHUD.dismiss()
}
}
//Control Delegate
func PTFrameWindowControlVideoShouldReset(isSetFront: Bool) {
// println("delegate did call")
self.stopMediaPlayer()
self.videoFrameObj = self.frameWindow.getVideoStartEnd()
if(isSetFront){
self.mediaPlayer.currentPlaybackTime = Double(self.videoFrameObj.videoStart)
}
else{
self.mediaPlayer.currentPlaybackTime = Double(self.videoFrameObj.videoEnd)
}
println("isSetFront: \(isSetFront), self.mediaPlayer: \(self.mediaPlayer)")
}
}
|
mit
|
52c17156e15932fe61bf7a3d39e93c40
| 43.068966 | 346 | 0.661698 | 4.770437 | false | false | false | false |
crass45/PoGoApiAppleWatchExample
|
PoGoApiAppleWatchExample/PGoApi/PGOApiController.swift
|
1
|
8863
|
//
// PGOApiController.swift
// PGoApi
//
// Created by Jose Luis on 19/8/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import PGoApi
class PGOApiController: AnyObject, PGoApiDelegate {
var replyHandler: ([String: AnyObject] -> Void)?
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
func didReceiveApiResponse(intent: PGoApiIntent, response: PGoApiResponse) {
print("Got that API response: \(intent)")
if (intent == .Login) {
loginOK = true
request.getMapObjects()
request.makeRequest(.GetMapObjects, delegate: self)
}
if (intent == .EncounterPokemon){
print("ENCOUNTER POKEMON!")
// print(response.response)
// print(response.subresponses)
if response.subresponses.count > 0 {
if let r = response.subresponses[0] as? Pogoprotos.Networking.Responses.EncounterResponse {
if r.status == .EncounterSuccess {
let wPokem = r.wildPokemon
cazaPokemonConPokeBall(wPokem.encounterId, spawnPointId: wPokem.spawnPointId)
}else {
if replyHandler != nil {
replyHandler!(["status":r.status.toString()])
}
}
}
}
}
if (intent == .CatchPokemon){
print("CAZANDO POKEMON!")
if response.subresponses.count > 0 {
if let r = response.subresponses[0] as? Pogoprotos.Networking.Responses.CatchPokemonResponse {
let status = r.status.toString()
print(status)
if self.replyHandler != nil {
replyHandler!(["status":status])
}
// appDelegate.session.sendMessage(["status":status], replyHandler: {(respuesta)->Void in
// print(respuesta)
//
// // handle reply from iPhone app here
// }, errorHandler: {(error )->Void in
// // catch any errors here
// print(error.localizedDescription)
// })
if r.status == .CatchSuccess {
//TODO se ha capturado correctamente al pokemon
print("CATCH SUCCESS")
}
if r.status == .CatchFlee {
//
print("CATCHFLEE")
}
if r.status == .CatchError {
print("CATCH ERROR")
}
if r.status == .CatchMissed {
print("CATCH MISSED")
}
if r.status == .CatchEscape {
print("CATCH ESCAPE")
}
}
}
textoLog += "\(response.response)"
textoLog += "\(response.subresponses)"
UIApplication.sharedApplication().cancelAllLocalNotifications()
NSNotificationCenter.defaultCenter().postNotificationName(UPDATE_LOG, object: nil)
}
if (intent == .GetMapObjects) {
// print(response)
// print(response.subresponses)
if response.subresponses.count > 0 {
if let r = response.subresponses[0] as? Pogoprotos.Networking.Responses.GetMapObjectsResponse {
catchablePokes = []
gimnasios = []
for cell in r.mapCells {
catchablePokes.appendContentsOf(cell.catchablePokemons)
gimnasios.appendContentsOf(cell.forts)
}
for fort in gimnasios {
// print(fort.hasActiveFortModifier)
}
// request.getInventory()
// request.makeRequest(.GetInventory, delegate: self)
}
}
NSNotificationCenter.defaultCenter().postNotificationName(NEW_POKEMONS_NOTIFICATION, object: nil)
}
if (intent == .GetInventory){
// print("Got INVENTORY!")
// print(response.response)
// print(response.subresponses)
// let r = response.subresponses[0] as! Pogoprotos.Networking.Responses.GetInventoryResponse
// let inventarioJugador = r.inventoryDelta.inventoryItems[0].inventoryItemData.playerStats//.pokemonData
// let pokemonsInventario = r.inventoryDelta.inventoryItems[0].inventoryItemData.pokemonData
// let caramelos = r.inventoryDelta.inventoryItems[0].inventoryItemData.candy
// let r = response.subresponses[0] as! Pogoprotos.Networking.Responses.GetInventoryResponse
// let cell = r.inventoryDelta.inventoryItems[0]
// print(cell.inventoryItemData.eggIncubators)
// print(cell.wildPokemons)
// print(cell.catchablePokemons)
}
if catchablePokes.count > 0 {
for poke in catchablePokes {
if !pokesNotificados.contains(poke.spawnPointId){
pokesNotificados.append(poke.spawnPointId)
poke.spawnPointId
print("PokemonID:\(poke.pokemonId.hashValue)")
let not = UILocalNotification()
not.soundName = UILocalNotificationDefaultSoundName
not.alertBody = "\(poke.pokemonId.toString()) CERCANO"
not.alertTitle = "Tienes Cerca un \(poke.pokemonId.toString())"
not.category = "REMINDER_CATEGORY"
var infoNotif = [String: AnyObject]()
infoNotif["encounterID"] = poke.encounterId.hashValue
infoNotif["pokemonId"] = poke.pokemonId.hashValue
infoNotif["spawnPointId"] = poke.spawnPointId
not.userInfo = infoNotif
UIApplication.sharedApplication().scheduleLocalNotification(not)
}
}
}
// if gimnasios.count>0{
//
// for gim in gimnasios {
// let not = UILocalNotification()
// not.soundName = UILocalNotificationDefaultSoundName
// not.alertBody = "GIMNASIO CERCANO"
// not.alertTitle = "Tienes Cerca un Gimnasio:\(gim.guardPokemonId.toString())"
// not.category = "REMINDER_CATEGORY"
// // not.fireDate = currentDate
// UIApplication.sharedApplication().scheduleLocalNotification(not)
// }
//
// }
}
func didReceiveApiError(intent: PGoApiIntent, statusCode: Int?) {
print("API Error: \(statusCode)")
UIAlertView(title: "API ERROR", message: "\(statusCode)", delegate: self, cancelButtonTitle: "OK").show()
}
func getMapObject(){
request.getMapObjects()
request.makeRequest(.GetMapObjects, delegate: self)
}
func encounterPokemon(encounterId:UInt64, spawnPointId:String, replyHandler: [String: AnyObject] -> Void){
request.encounterPokemon(encounterId, spawnPointId: spawnPointId)
request.makeRequest(.EncounterPokemon, delegate: self)
self.replyHandler = replyHandler
}
func cazaPokemonConPokeBall(encounterId:UInt64, spawnPointId:String){
request.catchPokemon(encounterId, spawnPointId: spawnPointId, pokeball: Pogoprotos.Inventory.Item.ItemId.ItemPokeBall, hitPokemon: true, normalizedReticleSize: 1, normalizedHitPosition: 1, spinModifier: 1)
request.makeRequest(.CatchPokemon, delegate: self)
}
}
|
mit
|
73f4334504836ad41dd449593c8da575
| 41.406699 | 213 | 0.482961 | 5.830263 | false | false | false | false |
benbahrenburg/BucketList
|
Example/Pods/RNCryptor/Sources/RNCryptor/RNCryptor.swift
|
1
|
29103
|
//
// RNCryptor.swift
//
// Copyright © 2015 Rob Napier. All rights reserved.
//
// This code is licensed under the MIT License:
//
// 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
import Foundation
#if SWIFT_PACKAGE
import Cryptor
#endif
/// The `RNCryptorType` protocol defines generic API to a mutable,
/// incremental, password-based encryptor or decryptor. Its generic
/// usage is as follows:
///
/// let cryptor = Encryptor(password: "mypassword")
/// // or Decryptor()
///
/// var result = Data()
/// for data in datas {
/// result.appendData(try cryptor.update(data))
/// }
/// result.appendData(try cryptor.final())
///
/// After calling `finalData()`, the cryptor is no longer valid.
public protocol RNCryptorType {
/// Creates and returns a cryptor.
///
/// - parameter password: Non-empty password string. This will be interpretted as UTF-8.
init(password: String)
/// Updates cryptor with data and returns processed data.
///
/// - parameter data: Data to process. May be empty.
/// - throws: `Error`
/// - returns: Processed data. May be empty.
func update(withData data: Data) throws -> Data
/// Returns trailing data and invalidates the cryptor.
///
/// - throws: `Error`
/// - returns: Trailing data
func finalData() throws -> Data
}
public extension RNCryptorType {
/// Simplified, generic interface to `RNCryptorType`. Takes a data,
/// returns a processed data. Generally you should use
/// `RNCryptor.encrypt(data:withPassword:)`, or
/// `RNCryptor.decrypt(data:withPassword:)` instead, but this is useful
/// for code that is neutral on whether it is encrypting or decrypting.
///
/// - throws: `Error`
fileprivate func oneshot(data: Data) throws -> Data {
var result = try update(withData: data)
result.append(try finalData())
return result
}
}
/// RNCryptor encryption/decryption interface.
public enum RNCryptor {
/// Errors thrown by `RNCryptorType`.
public enum Error: Int, Swift.Error {
/// Ciphertext was corrupt or password was incorrect.
/// It is not possible to distinguish between these cases in the v3 data format.
case hmacMismatch = 1
/// Unrecognized data format. Usually this means the data is corrupt.
case unknownHeader = 2
/// `final()` was called before sufficient data was passed to `update(withData:)`
case messageTooShort
/// Memory allocation failure. This should never happen.
case memoryFailure
/// A password-based decryptor was used on a key-based ciphertext, or vice-versa.
case invalidCredentialType
}
/// Encrypt data using password and return encrypted data.
public static func encrypt(data: Data, withPassword password: String) -> Data {
return Encryptor(password: password).encrypt(data: data)
}
/// Decrypt data using password and return decrypted data. Throws if
/// password is incorrect or ciphertext is in the wrong format.
/// - throws `Error`
public static func decrypt(data: Data, withPassword password: String) throws -> Data {
return try Decryptor(password: password).decrypt(data: data)
}
/// Generates random Data of given length
/// Crashes if `length` is larger than allocatable memory, or if the system random number generator is not available.
public static func randomData(ofLength length: Int) -> Data {
var data = Data(count: length)
let result = data.withUnsafeMutableBytes { return SecRandomCopyBytes(kSecRandomDefault, length, $0) }
guard result == errSecSuccess else {
fatalError("SECURITY FAILURE: Could not generate secure random numbers: \(result).")
}
return data
}
/// A encryptor for the latest data format. If compatibility with other RNCryptor
/// implementations is required, you may wish to use the specific encryptor version rather
/// than accepting "latest."
///
public final class Encryptor: RNCryptorType {
private let encryptor: EncryptorV3
/// Creates and returns a cryptor.
///
/// - parameter password: Non-empty password string. This will be interpretted as UTF-8.
public init(password: String) {
precondition(password != "")
encryptor = EncryptorV3(password: password)
}
/// Updates cryptor with data and returns processed data.
///
/// - parameter data: Data to process. May be empty.
/// - returns: Processed data. May be empty.
public func update(withData data: Data) -> Data {
return encryptor.update(withData: data)
}
/// Returns trailing data and invalidates the cryptor.
///
/// - returns: Trailing data
public func finalData() -> Data {
return encryptor.finalData()
}
/// Simplified, generic interface to `RNCryptorType`. Takes a data,
/// returns a processed data, and invalidates the cryptor.
public func encrypt(data: Data) -> Data {
return encryptor.encrypt(data: data)
}
}
/// Password-based decryptor that can handle any supported format.
public final class Decryptor : RNCryptorType {
private var decryptors: [VersionedDecryptorType.Type] = [DecryptorV3.self]
private var buffer = Data()
private var decryptor: RNCryptorType?
private let password: String
/// Creates and returns a cryptor.
///
/// - parameter password: Non-empty password string. This will be interpretted as UTF-8.
public init(password: String) {
assert(password != "")
self.password = password
}
/// Decrypt data using password and return decrypted data, invalidating decryptor. Throws if
/// password is incorrect or ciphertext is in the wrong format.
/// - throws `Error`
public func decrypt(data: Data) throws -> Data {
return try oneshot(data: data)
}
/// Updates cryptor with data and returns processed data.
///
/// - parameter data: Data to process. May be empty.
/// - throws: `Error`
/// - returns: Processed data. May be empty.
public func update(withData data: Data) throws -> Data {
if let d = decryptor {
return try d.update(withData: data)
}
buffer.append(data)
let toCheck:[VersionedDecryptorType.Type]
(toCheck, decryptors) = decryptors.splitPassFail { self.buffer.count >= $0.preambleSize }
for decryptorType in toCheck {
if decryptorType.canDecrypt(preamble: buffer.subdata(in: 0..<decryptorType.preambleSize)) {
let d = decryptorType.init(password: password)
decryptor = d
let result = try d.update(withData: buffer)
buffer.count = 0
return result
}
}
guard !decryptors.isEmpty else { throw Error.unknownHeader }
return Data()
}
/// Returns trailing data and invalidates the cryptor.
///
/// - throws: `Error`
/// - returns: Trailing data
public func finalData() throws -> Data {
guard let d = decryptor else {
throw Error.unknownHeader
}
return try d.finalData()
}
}
}
// V3 implementaion
public extension RNCryptor {
/// V3 format settings
public final class FormatV3 {
/// Size of AES and HMAC keys
public static let keySize = kCCKeySizeAES256
/// Size of PBKDF2 salt
public static let saltSize = 8
/// Generate a key from a password and salt
/// - parameters:
/// - password: Password to convert
/// - salt: Salt. Generally constructed with RNCryptor.randomDataOfLength(FormatV3.saltSize)
/// - returns: Key of length FormatV3.keySize
public static func makeKey(forPassword password: String, withSalt salt: Data) -> Data {
let passwordData = Data(password.utf8)
return passwordData.withUnsafeBytes { (passwordPtr : UnsafePointer<Int8>) in
salt.withUnsafeBytes { (saltPtr : UnsafePointer<UInt8>) in
var derivedKey = Data(count: keySize)
derivedKey.withUnsafeMutableBytes { (derivedKeyPtr : UnsafeMutablePointer<UInt8>) in
// All the crazy casting because CommonCryptor hates Swift
let algorithm = CCPBKDFAlgorithm(kCCPBKDF2)
let prf = CCPseudoRandomAlgorithm(kCCPRFHmacAlgSHA1)
let pbkdf2Rounds = UInt32(10000)
let result = CCCryptorStatus(
CCKeyDerivationPBKDF(
algorithm,
passwordPtr, passwordData.count,
saltPtr, salt.count,
prf, pbkdf2Rounds,
derivedKeyPtr, keySize)
)
guard result == CCCryptorStatus(kCCSuccess) else {
fatalError("SECURITY FAILURE: Could not derive secure password (\(result))")
}
}
return derivedKey
}
}
}
static let formatVersion = UInt8(3)
static let ivSize = kCCBlockSizeAES128
static let hmacSize = Int(CC_SHA256_DIGEST_LENGTH)
static let keyHeaderSize = 1 + 1 + kCCBlockSizeAES128
static let passwordHeaderSize = 1 + 1 + 8 + 8 + kCCBlockSizeAES128
}
/// Format version 3 encryptor. Use this to ensure a specific format verison
/// or when using keys (which are inherrently versions-specific). To use
/// "the latest encryptor" with a password, use `Encryptor` instead.
public final class EncryptorV3 : RNCryptorType {
private let engine: Engine
private let hmac: HMACV3
private var pendingHeader: Data?
/// Creates and returns an encryptor.
///
/// - parameter password: Non-empty password string. This will be interpretted as UTF-8.
public convenience init(password: String) {
self.init(
password: password,
encryptionSalt: RNCryptor.randomData(ofLength: V3.saltSize),
hmacSalt: RNCryptor.randomData(ofLength: V3.saltSize),
iv: RNCryptor.randomData(ofLength: V3.ivSize))
}
/// Creates and returns an encryptor using keys.
///
/// - Attention: This method requires some expertise to use correctly.
/// Most users should use `init(password:)` which is simpler
/// to use securely.
///
/// Keys should not be generated directly from strings (`.dataUsingEncoding()` or similar).
/// Ideally, keys should be random (`Cryptor.randomDataOfLength()` or some other high-quality
/// random generator. If keys must be generated from strings, then use `FormatV3.keyForPassword(salt:)`
/// with a random salt, or just use password-based encryption (that's what it's for).
///
/// - parameters:
/// - encryptionKey: AES-256 key. Must be exactly FormatV3.keySize (kCCKeySizeAES256, 32 bytes)
/// - hmacKey: HMAC key. Must be exactly FormatV3.keySize (kCCKeySizeAES256, 32 bytes)
public convenience init(encryptionKey: Data, hmacKey: Data) {
self.init(encryptionKey: encryptionKey, hmacKey: hmacKey, iv: RNCryptor.randomData(ofLength: V3.ivSize))
}
/// Takes a data, returns a processed data, and invalidates the cryptor.
public func encrypt(data: Data) -> Data {
return try! oneshot(data: data)
}
/// Updates cryptor with data and returns encrypted data.
///
/// - parameter data: Data to process. May be empty.
/// - returns: Processed data. May be empty.
public func update(withData data: Data) -> Data {
// It should not be possible for this to fail during encryption
return handle(data: engine.update(withData: data))
}
/// Returns trailing data and invalidates the cryptor.
///
/// - returns: Trailing data
public func finalData() -> Data {
var result = handle(data: engine.finalData())
result.append(hmac.finalData())
return result
}
// Expose random numbers for testing
internal convenience init(encryptionKey: Data, hmacKey: Data, iv: Data) {
let preamble = [V3.formatVersion, UInt8(0)]
var header = Data(bytes: preamble)
header.append(iv)
self.init(encryptionKey: encryptionKey, hmacKey: hmacKey, iv: iv, header: header)
}
// Expose random numbers for testing
internal convenience init(password: String, encryptionSalt: Data, hmacSalt: Data, iv: Data) {
let encryptionKey = V3.makeKey(forPassword: password, withSalt: encryptionSalt)
let hmacKey = V3.makeKey(forPassword: password, withSalt: hmacSalt)
let preamble = [V3.formatVersion, UInt8(1)]
var header = Data(bytes: preamble)
header.append(encryptionSalt)
header.append(hmacSalt)
header.append(iv)
self.init(encryptionKey: encryptionKey, hmacKey: hmacKey, iv: iv, header: header)
}
private init(encryptionKey: Data, hmacKey: Data, iv: Data, header: Data) {
precondition(encryptionKey.count == V3.keySize)
precondition(hmacKey.count == V3.keySize)
precondition(iv.count == V3.ivSize)
hmac = HMACV3(key: hmacKey)
engine = Engine(operation: .encrypt, key: encryptionKey, iv: iv)
pendingHeader = header
}
private func handle(data: Data) -> Data {
let result: Data
if var accum = pendingHeader {
pendingHeader = nil
accum.append(data)
result = accum
} else {
result = data
}
hmac.update(withData: result)
return result
}
}
/// Format version 3 decryptor. This is required in order to decrypt
/// using keys (since key configuration is version-specific). For password
/// decryption, `Decryptor` is generally preferred, and will call this
/// if appropriate.
public final class DecryptorV3: VersionedDecryptorType {
//
// Static methods
//
fileprivate static let preambleSize = 1
fileprivate static func canDecrypt(preamble: Data) -> Bool {
assert(preamble.count >= 1)
return preamble[0] == 3
}
//
// Private properties
//
private var buffer = Data()
private var decryptorEngine: DecryptorEngineV3?
private let credential: Credential
/// Creates and returns a decryptor.
///
/// - parameter password: Non-empty password string. This will be interpretted as UTF-8.
public init(password: String) {
credential = .password(password)
}
/// Creates and returns a decryptor using keys.
///
/// - parameters:
/// - encryptionKey: AES-256 key. Must be exactly FormatV3.keySize (kCCKeySizeAES256, 32 bytes)
/// - hmacKey: HMAC key. Must be exactly FormatV3.keySize (kCCKeySizeAES256, 32 bytes)
public init(encryptionKey: Data, hmacKey: Data) {
precondition(encryptionKey.count == V3.keySize)
precondition(hmacKey.count == V3.hmacSize)
credential = .keys(encryptionKey: encryptionKey, hmacKey: hmacKey)
}
/// Decrypt data using password and return decrypted data. Throws if
/// password is incorrect or ciphertext is in the wrong format.
/// - throws `Error`
public func decrypt(data: Data) throws -> Data {
return try oneshot(data: data)
}
/// Updates cryptor with data and returns encrypted data.
///
/// - parameter data: Data to process. May be empty.
/// - returns: Processed data. May be empty.
public func update(withData data: Data) throws -> Data {
if let e = decryptorEngine {
return e.update(withData: data)
}
buffer.append(data)
guard buffer.count >= requiredHeaderSize else {
return Data()
}
let e = try makeEngine(credential: credential, header: buffer.subdata(in: 0..<requiredHeaderSize))
decryptorEngine = e
let body = buffer.subdata(in: requiredHeaderSize..<buffer.count)
buffer.count = 0
return e.update(withData: body)
}
/// Returns trailing data and invalidates the cryptor.
///
/// - returns: Trailing data
public func finalData() throws -> Data {
guard let result = try decryptorEngine?.finalData() else {
throw Error.messageTooShort
}
return result
}
//
// Private functions
//
private var requiredHeaderSize: Int {
switch credential {
case .password: return V3.passwordHeaderSize
case .keys: return V3.keyHeaderSize
}
}
private func makeEngine(credential: Credential, header: Data) throws -> DecryptorEngineV3 {
switch credential {
case let .password(password):
return try makeEngine(password: password, header: header)
case let .keys(encryptionKey, hmacKey):
return try makeEngine(encryptionKey: encryptionKey, hmacKey: hmacKey, header: header)
}
}
private func makeEngine(password: String, header: Data) throws -> DecryptorEngineV3 {
assert(password != "")
precondition(header.count == V3.passwordHeaderSize)
guard DecryptorV3.canDecrypt(preamble: header) else {
throw Error.unknownHeader
}
guard header[1] == 1 else {
throw Error.invalidCredentialType
}
let encryptionSalt = header.subdata(in: Range(2...9))
let hmacSalt = header.subdata(in: Range(10...17))
let iv = header.subdata(in: Range(18...33))
let encryptionKey = V3.makeKey(forPassword: password, withSalt: encryptionSalt)
let hmacKey = V3.makeKey(forPassword: password, withSalt: hmacSalt)
return DecryptorEngineV3(encryptionKey: encryptionKey, hmacKey: hmacKey, iv: iv, header: header)
}
private func makeEngine(encryptionKey: Data, hmacKey: Data, header: Data) throws -> DecryptorEngineV3 {
precondition(header.count == V3.keyHeaderSize)
precondition(encryptionKey.count == V3.keySize)
precondition(hmacKey.count == V3.keySize)
guard DecryptorV3.canDecrypt(preamble: header) else {
throw Error.unknownHeader
}
guard header[1] == 0 else {
throw Error.invalidCredentialType
}
let iv = header.subdata(in: 2..<18)
return DecryptorEngineV3(encryptionKey: encryptionKey, hmacKey: hmacKey, iv: iv, header: header)
}
}
}
internal enum CryptorOperation: CCOperation {
case encrypt = 0 // CCOperation(kCCEncrypt)
case decrypt = 1 // CCOperation(kCCDecrypt)
}
internal final class Engine {
private let cryptor: CCCryptorRef?
private var buffer = Data()
init(operation: CryptorOperation, key: Data, iv: Data) {
cryptor = key.withUnsafeBytes { (keyPtr: UnsafePointer<UInt8>) in
iv.withUnsafeBytes { (ivPtr: UnsafePointer<UInt8>) in
var cryptorOut: CCCryptorRef?
let result = CCCryptorCreate(
operation.rawValue,
CCAlgorithm(kCCAlgorithmAES128), CCOptions(kCCOptionPKCS7Padding),
keyPtr, key.count,
ivPtr,
&cryptorOut
)
// It is a programming error to create us with illegal values
// This is an internal class, so we can constrain what is sent to us.
// If this is ever made public, it should throw instead of asserting.
assert(result == CCCryptorStatus(kCCSuccess))
return cryptorOut
}
}
}
deinit {
if cryptor != nil {
CCCryptorRelease(cryptor)
}
}
func sizeBuffer(forDataLength length: Int) -> Int {
let size = CCCryptorGetOutputLength(cryptor, length, true)
buffer.count = size
return size
}
func update(withData data: Data) -> Data {
let outputLength = sizeBuffer(forDataLength: data.count)
var dataOutMoved = 0
let result = data.withUnsafeBytes { dataPtr in
buffer.withUnsafeMutableBytes { bufferPtr in
return CCCryptorUpdate(
cryptor,
dataPtr, data.count,
bufferPtr, outputLength,
&dataOutMoved)
}
}
// The only error returned by CCCryptorUpdate is kCCBufferTooSmall, which would be a programming error
assert(result == CCCryptorStatus(kCCSuccess), "RNCRYPTOR BUG. PLEASE REPORT. (\(result)")
buffer.count = dataOutMoved
return buffer
}
func finalData() -> Data {
let outputLength = sizeBuffer(forDataLength: 0)
var dataOutMoved = 0
let result = buffer.withUnsafeMutableBytes {
CCCryptorFinal(
cryptor,
$0, outputLength,
&dataOutMoved
)
}
// Note that since iOS 6, CCryptor will never return padding errors or other decode errors.
// I'm not aware of any non-catestrophic (MemoryAllocation) situation in which this
// can fail. Using assert() just in case, but we'll ignore errors in Release.
// https://devforums.apple.com/message/920802#920802
assert(result == CCCryptorStatus(kCCSuccess), "RNCRYPTOR BUG. PLEASE REPORT. (\(result)")
buffer.count = dataOutMoved
defer { buffer = Data() }
return buffer
}
}
internal typealias V3 = RNCryptor.FormatV3
private enum Credential {
case password(String)
case keys(encryptionKey: Data, hmacKey: Data)
}
private final class DecryptorEngineV3 {
private let buffer = OverflowingBuffer(capacity: V3.hmacSize)
private let hmac: HMACV3
private let engine: Engine
init(encryptionKey: Data, hmacKey: Data, iv: Data, header: Data) {
precondition(encryptionKey.count == V3.keySize)
precondition(hmacKey.count == V3.hmacSize)
precondition(iv.count == V3.ivSize)
hmac = HMACV3(key: hmacKey)
hmac.update(withData: header)
engine = Engine(operation: .decrypt, key: encryptionKey, iv: iv)
}
func update(withData data: Data) -> Data {
let overflow = buffer.update(withData: data)
hmac.update(withData: overflow)
return engine.update(withData: overflow)
}
func finalData() throws -> Data {
let hash = hmac.finalData()
if !isEqualInConsistentTime(trusted: hash, untrusted: buffer.finalData()) {
throw RNCryptor.Error.hmacMismatch
}
return engine.finalData()
}
}
private final class HMACV3 {
var context = CCHmacContext()
init(key: Data) {
key.withUnsafeBytes {
CCHmacInit(
&context,
CCHmacAlgorithm(kCCHmacAlgSHA256),
$0,
key.count
)
}
}
func update(withData data: Data) {
data.withUnsafeBytes { CCHmacUpdate(&context, $0, data.count) }
}
func finalData() -> Data {
var hmac = Data(count: V3.hmacSize)
hmac.withUnsafeMutableBytes { CCHmacFinal(&context, $0) }
return hmac
}
}
// Internal protocol for version-specific decryptors.
private protocol VersionedDecryptorType: RNCryptorType {
static var preambleSize: Int { get }
static func canDecrypt(preamble: Data) -> Bool
init(password: String)
}
private extension Collection {
// Split collection into ([pass], [fail]) based on predicate.
func splitPassFail(forPredicate predicate: (Iterator.Element) -> Bool) -> ([Iterator.Element], [Iterator.Element]) {
var pass: [Iterator.Element] = []
var fail: [Iterator.Element] = []
for e in self {
if predicate(e) {
pass.append(e)
} else {
fail.append(e)
}
}
return (pass, fail)
}
}
internal final class OverflowingBuffer {
private var buffer = Data()
let capacity: Int
init(capacity: Int) {
self.capacity = capacity
}
func update(withData data: Data) -> Data {
if data.count >= capacity {
return sendAll(data: data)
} else if buffer.count + data.count <= capacity {
buffer.append(data)
return Data()
} else {
return sendSome(data: data)
}
}
func finalData() -> Data {
let result = buffer
buffer.count = 0
return result
}
private func sendAll(data: Data) -> Data {
let toSend = data.count - capacity
assert(toSend >= 0)
assert(data.count - toSend <= capacity)
var result = buffer
result.append(data.subdata(in: 0..<toSend))
buffer.count = 0
buffer.append(data.subdata(in: toSend..<data.count)) // TODO: Appending here to avoid later buffer growth, but maybe just buffer = data.subdata would be better
return result
}
private func sendSome(data: Data) -> Data {
let toSend = (buffer.count + data.count) - capacity
assert(toSend > 0) // If it were <= 0, we would have extended the array
assert(toSend < buffer.count) // If we would have sent everything, replaceBuffer should have been called
let result = buffer.subdata(in: 0..<toSend)
buffer.replaceSubrange(0..<toSend, with: Data())
buffer.append(data)
return result
}
}
/** Compare two Datas in time proportional to the untrusted data
Equatable-based comparisons genreally stop comparing at the first difference.
This can be used by attackers, in some situations,
to determine a secret value by considering the time required to compare the values.
We enumerate over the untrusted values so that the time is proportaional to the attacker's data,
which provides the attack no informatoin about the length of the secret.
*/
private func isEqualInConsistentTime(trusted: Data, untrusted: Data) -> Bool {
// The point of this routine is XOR the bytes of each data and accumulate the results with OR.
// If any bytes are different, then the OR will accumulate some non-0 value.
var result: UInt8 = untrusted.count == trusted.count ? 0 : 1 // Start with 0 (equal) only if our lengths are equal
for (i, untrustedByte) in untrusted.enumerated() {
// Use mod to wrap around ourselves if they are longer than we are.
// Remember, we already broke equality if our lengths are different.
result |= trusted[i % trusted.count] ^ untrustedByte
}
return result == 0
}
|
mit
|
d1384d5ed1135cc1df4f56f257202ac6
| 36.745785 | 167 | 0.606659 | 4.722817 | false | false | false | false |
manajay/DeviceOrientationDemo
|
DeviceOrientationDemo/Business/Helper/ModuleHelper.swift
|
1
|
4338
|
//
// ModuleHelper.swift
// SQLiteDBDemo
//
// Created by manajay on 24/01/2017.
// Copyright © 2017 manajay. All rights reserved.
//
import UIKit
class ModuleHelper {
private static let manager = ModuleHelper()
class var share: ModuleHelper {
return manager
}
var delegate: AppDelegate? {
if let delegate = UIApplication.shared.delegate as? AppDelegate {
return delegate
}
return nil
}
var topWindow: UIWindow{
return UIApplication.shared.windows.first!
}
var topView: UIView {
return currentViewController.view
}
/// 获取当前的 控制器
///
/// - Returns: 当前显示的控制器
var currentViewController: UIViewController {
var currVC: UIViewController? = nil
let delegate = (UIApplication.shared.delegate as! AppDelegate)
var Rootvc = delegate.window?.rootViewController!
if let rv = Rootvc as? MainController ,let modalVC = rv.modalNavigationController {
Rootvc = modalVC
}
repeat {
if (Rootvc is UINavigationController) {
let nav = (Rootvc as! UINavigationController)
let v = nav.viewControllers.last!
currVC = v
Rootvc = v.presentedViewController
}
else if (Rootvc is UITabBarController) {
let tabVC = (Rootvc as! UITabBarController)
currVC = tabVC
Rootvc = tabVC.viewControllers?[tabVC.selectedIndex]
}
} while Rootvc != nil
return currVC!
}
static func currentViewController(with rootViewController: UIViewController!)->UIViewController?{
if nil == rootViewController{
return nil
}
// UITabBarController就接着查找它当前显示的selectedViewController
if rootViewController.isKind(of: UITabBarController.self){
return self.currentViewController(with: (rootViewController as! UITabBarController).selectedViewController)
// UINavigationController就接着查找它当前显示的visibleViewController
}else if rootViewController.isKind(of: UINavigationController.self){
return self.currentViewController(with: (rootViewController as! UINavigationController).visibleViewController)
// 如果当前窗口有presentedViewController,就接着查找它的presentedViewController
}else if nil != rootViewController.presentedViewController{
return self.currentViewController(with: rootViewController.presentedViewController)
}
// 否则就代表找到了当前显示的控制器
return rootViewController
}
}
extension UIDevice {
/**
注意 // 当调用 rotate(to: UIInterfaceOrientation.landscapeLeft) 时,先允许自动旋转,然后进行屏幕旋转。再设置为不允许自动旋转
// 手动旋转屏幕的注意点
*/
class func orientation(to orientation: UIInterfaceOrientation) {
// 先自己给一个值0,然后再修改为其他屏幕方向就能顺利调起 KVO 来进入屏幕旋转流程
UIDevice.current.setValue(UIInterfaceOrientation.unknown.rawValue, forKey: "orientation")
UIDevice.current.setValue(orientation.rawValue, forKey: "orientation")
}
/**
1.当当前设备方向属性 orientation 发生变化时候,会调用 Controller 的 shouldAutorotate 属性。
2.如果 shouldAutorotate 为 true 则会进一步调用 supportedInterfaceOrientations 来查询支持的屏幕方向。
3.当 Controller 支持的方向和设备方向一致时候就进行旋转操作。
神 Bug 就出在第一步。UIDevice 的 orientation 属性并不是指的屏幕的方向,而是设备的方向。我们屏幕旋转的实现就是通过手动修改 orientation 属性来欺骗设备告诉他设备方向发生了变化,从而开始屏幕旋转流程。
如果当屏幕 UI 处于横屏且 shouldAutorotate = false 时候,我们旋转手机设备 orientation 属性会持续变化并开始屏幕旋转流程调用 shouldAutorotate。但是因为 shouldAutorotate 为 false 所以不会有任何反应。
当屏幕 UI 处于横屏且我们旋转手机设备至竖屏状态时, orientation 属性已经为 UIInterfaceOrientation.portrait.rawValue 了,所以此时再次设置为 UIInterfaceOrientation.portrait.rawValue 并不会调用被系统认为屏幕方向发生了变化。所以就不会有任何变化。
*/
}
|
mit
|
0ff87c58b643da8490fd9157232dae54
| 30.827273 | 174 | 0.733505 | 4.218072 | false | false | false | false |
IBM-MIL/IBM-Ready-App-for-Venue
|
iOS/Venue/Controllers/LeaderboardViewController.swift
|
1
|
2445
|
/*
Licensed Materials - Property of IBM
© Copyright IBM Corporation 2015. All Rights Reserved.
*/
import UIKit
/**
* Displays the current leaders based on points from challenges
*/
class LeaderboardViewController: VenueUIViewController {
@IBOutlet weak var leaderboardTableView: UITableView!
var viewModel: LeaderboardViewModel?
override func viewDidLoad() {
super.viewDidLoad()
setupBindings()
}
/**
Setup ReactiveCocoa bindings to UI and data
*/
func setupBindings() {
RACObserve(viewModel!, keyPath: "leaders").deliverOnMainThread().subscribeNext{ [unowned self] _ in
self.leaderboardTableView.reloadData()
}
RACObserve(UserDataManager.sharedInstance.currentUser, keyPath: "challengesCompleted").subscribeNext({ [unowned self] _ in
self.viewModel?.updateLeaderScore()
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
// MARK: - TableView Methods
extension LeaderboardViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModel!.leaders.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! LeaderboardTableViewCell
viewModel!.setupLeaderboardCell(cell, row: indexPath.row)
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
if let leaderboardDetailViewController = Utils.vcWithNameFromStoryboardWithName("LeaderboardDetailViewController", storyboardName: "Challenges") as? LeaderboardDetailViewController {
if leaderboardDetailViewController.viewModel == nil {
leaderboardDetailViewController.viewModel = LeaderboardDetailViewModel()
let user = viewModel!.leaders[indexPath.row]
leaderboardDetailViewController.viewModel?.user = user
}
navigationController?.pushViewController(leaderboardDetailViewController, animated: true)
}
}
}
|
epl-1.0
|
71b40626bf6d9161602702635b98ad4e
| 31.586667 | 190 | 0.686579 | 6.171717 | false | false | false | false |
mathewsheets/SwiftLearningExercises
|
Exercise_11.playground/Sources/BaseAccount.swift
|
1
|
562
|
import Foundation
public class BaseAccount {
public var balance = 0.0
public unowned var customer: Customer
public init(customer: Customer) {
self.customer = customer
}
public func debit(amount: Double) throws {
guard (balance - amount) >= 0 else {
throw TransactionError.InsufficientFunds(balance: balance, debiting: amount)
}
balance -= amount
}
public func credit(amount: Double) {
balance += amount
}
}
|
mit
|
83c11f7bf7da87e492b849956b8091a5
| 19.071429 | 88 | 0.551601 | 5.301887 | false | false | false | false |
nathankot/Alamofire
|
Source/Validation.swift
|
3
|
5714
|
// Alamofire.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
extension Request {
/**
A closure used to validate a request that takes a URL request and URL response, and returns whether the request was valid.
*/
public typealias Validation = (NSURLRequest, NSHTTPURLResponse) -> Bool
/**
Validates the request, using the specified closure.
If validation fails, subsequent calls to response handlers will have an associated error.
:param: validation A closure to validate the request.
:returns: The request.
*/
public func validate(validation: Validation) -> Self {
self.delegate.queue.addOperationWithBlock {
if let response = self.response where self.delegate.error == nil && !validation(self.request, response) {
self.delegate.error = NSError(domain: AlamofireErrorDomain, code: -1, userInfo: nil)
}
}
return self
}
// MARK: - Status Code
/**
Validates that the response has a status code in the specified range.
If validation fails, subsequent calls to response handlers will have an associated error.
:param: range The range of acceptable status codes.
:returns: The request.
*/
public func validate<S: SequenceType where S.Generator.Element == Int>(statusCode acceptableStatusCode: S) -> Self {
return validate { _, response in
return contains(acceptableStatusCode, response.statusCode)
}
}
// MARK: - Content-Type
private struct MIMEType {
let type: String
let subtype: String
init?(_ string: String) {
let components = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
.substringToIndex(string.rangeOfString(";")?.endIndex ?? string.endIndex)
.componentsSeparatedByString("/")
if let
type = components.first,
subtype = components.last
{
self.type = type
self.subtype = subtype
} else {
return nil
}
}
func matches(MIME: MIMEType) -> Bool {
switch (self.type, self.subtype) {
case (MIME.type, MIME.subtype), (MIME.type, "*"), ("*", MIME.subtype), ("*", "*"):
return true
default:
return false
}
}
}
/**
Validates that the response has a content type in the specified array.
If validation fails, subsequent calls to response handlers will have an associated error.
:param: contentType The acceptable content types, which may specify wildcard types and/or subtypes.
:returns: The request.
*/
public func validate<S : SequenceType where S.Generator.Element == String>(contentType acceptableContentTypes: S) -> Self {
return validate { _, response in
if let
responseContentType = response.MIMEType,
responseMIMEType = MIMEType(responseContentType)
{
for contentType in acceptableContentTypes {
if let acceptableMIMEType = MIMEType(contentType) where acceptableMIMEType.matches(responseMIMEType) {
return true
}
}
} else {
for contentType in acceptableContentTypes {
if let MIMEType = MIMEType(contentType) where MIMEType.type == "*" && MIMEType.subtype == "*" {
return true
}
}
}
return false
}
}
// MARK: - Automatic
/**
Validates that the response has a status code in the default acceptable range of 200...299, and that the content type matches any specified in the Accept HTTP header field.
If validation fails, subsequent calls to response handlers will have an associated error.
:returns: The request.
*/
public func validate() -> Self {
let acceptableStatusCodes: Range<Int> = 200..<300
let acceptableContentTypes: [String] = {
if let accept = self.request.valueForHTTPHeaderField("Accept") {
return accept.componentsSeparatedByString(",")
}
return ["*/*"]
}()
return validate(statusCode: acceptableStatusCodes).validate(contentType: acceptableContentTypes)
}
}
|
mit
|
52fedbdadf53395cbd200d0cf24cc6d2
| 36.333333 | 180 | 0.623424 | 5.471264 | false | false | false | false |
simplyzhao/ForecastIO
|
ForecastIO/ForecastIO.swift
|
1
|
2224
|
//
// Forecast.io.swift
// Weather
//
// Created by Alex Zhao on 11/25/15.
// Copyright © 2015 Alex Zhao. All rights reserved.
//
import Foundation
public protocol ForecastIODelegate: class {
func handlesForecastResponse(response: ForecastResponse)
func handlesForecastError(error: NSError)
}
public class ForecastIO {
// Singleton
public static let sharedInstance = ForecastIO()
// Delegate
public weak var delegate: ForecastIODelegate?
// Forecast API required fields (https://developer.forecast.io/)
private let apiKey: String = "f2fd4105de5163646596076704638ac2"
private static let apiFixedURL: String = "https://api.forecast.io/forecast/"
private let session = NSURLSession.sharedSession()
private init() {
print("Forecast initialized with API Key: \(self.apiKey)")
}
typealias CompletionHandler = (NSData?, NSURLResponse?, NSError?) -> Void
private lazy var completionHandler: CompletionHandler = {
[weak self] (data: NSData?, response: NSURLResponse?, error: NSError?) in
if error != nil {
self?.delegate?.handlesForecastError(error!);
} else {
if let responseData = (try? NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers)) as? [String: AnyObject] {
let response = ForecastResponse(response: responseData)
self?.delegate?.handlesForecastResponse(response)
}
}
}
public func forecast(latitude lat: Double, longitude lon: Double) -> Void {
let apiURL = ForecastIO.apiFixedURL + self.apiKey + "/\(lat),\(lon)"
if let url = NSURL(string: apiURL) {
let task = session.dataTaskWithURL(url, completionHandler: completionHandler)
task.resume()
}
}
public func forecast(latitude lat: Double, longitude lon: Double, time: NSTimeInterval) -> Void {
let apiURL = ForecastIO.apiFixedURL + self.apiKey + "/\(lat),\(lon),\(time)"
if let url = NSURL(string: apiURL) {
let task = session.dataTaskWithURL(url, completionHandler: completionHandler)
task.resume()
}
}
}
|
mit
|
9d49b89156ee36d8b7e333ad02413a58
| 35.442623 | 160 | 0.652272 | 4.670168 | false | false | false | false |
debugsquad/metalic
|
metalic/Model/Store/MStore.swift
|
1
|
3167
|
import Foundation
import StoreKit
class MStore:NSObject, SKProductsRequestDelegate, SKPaymentTransactionObserver, SKRequestDelegate
{
static let sharedInstance:MStore = MStore()
let purchase:MStorePurchase
var error:String?
override init()
{
purchase = MStorePurchase()
}
deinit
{
NotificationCenter.default.removeObserver(self)
}
//MARK: notifications
func notifiedPurchasesLoaded(sender notification:Notification)
{
NotificationCenter.default.removeObserver(self)
DispatchQueue.main.async
{
self.checkAvailability()
}
}
//MARK: private
private func notifyStore()
{
NotificationCenter.default.post(
name:Notification.storeLoaded,
object:nil)
}
//MARK: public
func checkAvailability()
{
error = nil
if purchase.mapItems.count > 0
{
let itemsSet:Set<String> = purchase.makeSet()
let request:SKProductsRequest = SKProductsRequest(productIdentifiers:itemsSet)
request.delegate = self
request.start()
}
else
{
NotificationCenter.default.addObserver(
self,
selector:#selector(notifiedPurchasesLoaded(sender:)),
name:Notification.purchasesLoaded,
object:nil)
purchase.loadDb()
}
}
func restorePurchases()
{
SKPaymentQueue.default().restoreCompletedTransactions()
}
func purchase(skProduct:SKProduct?)
{
guard
let skProduct:SKProduct = skProduct
else
{
return
}
let skPayment:SKPayment = SKPayment(product:skProduct)
SKPaymentQueue.default().add(skPayment)
}
//MARK: store delegate
func request(_ request:SKRequest, didFailWithError error:Error)
{
self.error = error.localizedDescription
notifyStore()
}
func productsRequest(_ request:SKProductsRequest, didReceive response:SKProductsResponse)
{
let products:[SKProduct] = response.products
for product:SKProduct in products
{
purchase.loadSkProduct(skProduct:product)
}
notifyStore()
}
func paymentQueue(_ queue:SKPaymentQueue, updatedTransactions transactions:[SKPaymentTransaction])
{
purchase.updateTransactions(transactions:transactions)
notifyStore()
}
func paymentQueue(_ queue:SKPaymentQueue, removedTransactions transactions:[SKPaymentTransaction])
{
purchase.updateTransactions(transactions:transactions)
notifyStore()
}
func paymentQueueRestoreCompletedTransactionsFinished(_ queue:SKPaymentQueue)
{
notifyStore()
}
func paymentQueue(_ queue:SKPaymentQueue, restoreCompletedTransactionsFailedWithError error:Error)
{
self.error = error.localizedDescription
notifyStore()
}
}
|
mit
|
ab627d094a020dabc0521b5777a97757
| 23.742188 | 102 | 0.604673 | 5.747731 | false | false | false | false |
xiaoxionglaoshi/DNSwiftProject
|
DNSwiftProject/DNSwiftProject/AppDelegate.swift
|
1
|
2518
|
//
// AppDelegate.swift
// DNSwiftProject
//
// Created by mainone on 16/11/25.
// Copyright © 2016年 wjn. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// User.userEmail = ""
print(UIDevice.deviceModelReadable())
// 创建window
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.makeKeyAndVisible()
self.window?.backgroundColor = UIColor.white
let picUrl = "http://ww3.sinaimg.cn/mw690/937882b5gw1f9alr6oysjj20hs0qowg0.jpg"
// 检测用户是不是首次安装
if isNewVersion {
self.window?.rootViewController = DNGuidePageViewController()
// 第一次加载不显示广告业,只是默默地下载下次用
DNLaunchImageView.downLoadAdsImage(imageUrl: picUrl)
} else {
self.window?.rootViewController = DNTabBarViewController()
// 加载广告页
let startView: DNLaunchImageView = DNLaunchImageView.startAdsWith(imageUrl: picUrl, clickImageAction: {[weak self] in
let vc = DNWKWebViewController()
vc.title = "广告页面"
vc.urlString = "https://www.google.com"
(self?.window?.rootViewController?.childViewControllers.first as! DNNavigationController).pushViewController(vc, animated: false)
}) as! DNLaunchImageView
startView.startAnimationTime(time: 5, completionBlock: { (adsView: DNLaunchImageView) in
print("广告结束")
})
}
// 推送注册
RegisterJPush(launchOptions: launchOptions)
return true
}
// 程序暂行
func applicationWillResignActive(_ application: UIApplication) {
}
// 程序进入后台
func applicationDidEnterBackground(_ application: UIApplication) {
}
// 程序进入前台
func applicationWillEnterForeground(_ application: UIApplication) {
}
// 程序从新激活
func applicationDidBecomeActive(_ application: UIApplication) {
}
// 程序意外退出
func applicationWillTerminate(_ application: UIApplication) {
}
}
|
apache-2.0
|
ccbe1d18f11dfacfdc250f551e259328
| 28.4625 | 145 | 0.618159 | 4.839836 | false | false | false | false |
terietor/GtsiapKit
|
GtsiapKit/Theme/Theme.swift
|
1
|
5151
|
// Copyright (c) 2015-2016 Giorgos Tsiapaliokas <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
public struct ViewShadow {
public var shadowOpacity: Float = 0.5
public var shadowRadius: CGFloat = 5.0
public var shadowColor: CGColor = UIColor.black.cgColor
public var shadowOffset: CGSize = CGSize(width: -10, height: 10)
}
public protocol Themeable {
var primaryColor: UIColor? { get set }
var tintColor: UIColor? { get set }
var appearanceForTabBar: (() -> ())? { get set }
var tintColorForControls: UIColor? { get set }
var selectedTitleTextColor: UIColor? { get set }
}
extension Themeable {
public func setup() {
// TODO use UIAppearance.appearanceWhenContainedInInstancesOfClasses
// when we won't need iOS 8.4
labelAppearance()
buttonAppearance()
searchBarAppearance()
segmentedAppearance()
switchAppearance()
navigationBarAppearance()
self.appearanceForTabBar?()
}
// MARK: appearance
public func labelAppearance() {
UILabel.appearance().font = font()
UILabel.appearance().lineBreakMode = NSLineBreakMode.byWordWrapping
UILabel.appearance().numberOfLines = 0
}
public func buttonAppearance() {
if let color = self.tintColorForControls {
UIButton.appearance().tintColor = color
}
}
public func searchBarAppearance() {
UISearchBar.appearance().barTintColor = self.primaryColor
UISearchBar.appearance().tintColor = self.tintColor
}
public func navigationBarAppearance() {
UINavigationBar.appearance().barTintColor = self.primaryColor
UINavigationBar.appearance().tintColor = self.tintColor
guard let tintColor = self.tintColor else { return }
UINavigationBar.appearance().titleTextAttributes = [
NSForegroundColorAttributeName: tintColor
]
}
public func switchAppearance() {
UISwitch.appearance().tintColor = self.primaryColor
UISwitch.appearance().onTintColor = self.tintColorForControls
}
public func segmentedAppearance() {
guard let
textColor = self.selectedTitleTextColor
else { return }
UISegmentedControl.appearance().setTitleTextAttributes([
NSFontAttributeName: smallBoldFont()
], for: UIControlState())
UISegmentedControl.appearance().setTitleTextAttributes([
NSForegroundColorAttributeName: textColor,
NSFontAttributeName: smallBoldFont()
], for: .selected)
}
// MARK: funcs
public func font() -> UIFont {
return UIFont.preferredFont(forTextStyle: UIFontTextStyle.body)
}
public func normalBoldFont() -> UIFont {
return UIFont.boldSystemFont(ofSize: UIFont.systemFontSize)
}
public func smallBoldFont() -> UIFont {
return UIFont.boldSystemFont(ofSize: UIFont.smallSystemFontSize)
}
public func headlineFont() -> UIFont {
return UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline)
}
public func subheadlineFont() -> UIFont {
return UIFont.preferredFont(forTextStyle: UIFontTextStyle.subheadline)
}
public func footnoteFont() -> UIFont {
return UIFont.preferredFont(forTextStyle: UIFontTextStyle.footnote)
}
public func defaultViewShadow() -> ViewShadow {
return ViewShadow()
}
public func invisibleViewShadow() -> ViewShadow {
return ViewShadow(
shadowOpacity: 0.0,
shadowRadius: 0,
shadowColor: UIColor.black.cgColor, // it doesn't matter
shadowOffset: CGSize(width: 0, height: 0)
)
}
}
open class Theme: Themeable {
open var primaryColor: UIColor?
open var tintColor: UIColor?
open var appearanceForTabBar: (() -> ())?
open var tintColorForControls: UIColor?
open var selectedTitleTextColor: UIColor?
}
open class ThemeManager {
open static var defaultTheme: Themeable = {
return Theme()
}()
}
|
mit
|
ac16514f3d633f5059b9abd3c2820b18
| 31.808917 | 82 | 0.684721 | 5.115194 | false | false | false | false |
worchyld/EYPlayground
|
Payout.playground/Pages/turnmgr.xcplaygroundpage/Contents.swift
|
1
|
5959
|
//: [Previous](@previous)
import Foundation
import GameplayKit
class Player {
var name: String
public private(set) var isAI: Bool = false
public private(set) var turnOrder: Int = 0
init(name: String, isAI: Bool?) {
self.name = name
if let hasAI = isAI {
self.isAI = hasAI
}
}
func setTurnOrderIndex(number: Int) {
self.turnOrder = number
}
}
let p1 = Player.init(name: "Player #1", isAI: true)
let p2 = Player.init(name: "Player #2", isAI: true)
let p3 = Player.init(name: "Player #3", isAI: true)
let p4 = Player.init(name: "Player #4", isAI: true)
let p5 = Player.init(name: "Player #5", isAI: true)
protocol TurnOrderManagerDelegate: NSObjectProtocol {
func turnOrderWasSet()
}
protocol TurnDelegate: class {
func turnIsCompleted()
}
class Turn: NSObject {
weak var player: Player?
weak var delegate: TurnDelegate?
public private(set) var completed: Bool = false {
didSet {
delegate?.turnIsCompleted()
}
}
init(player:Player, delegate: TurnDelegate) {
self.player = player
self.delegate = delegate
}
func setAsComplete() {
self.completed = true
}
}
class TurnOrderManager: NSObject, TurnOrderManagerDelegate, TurnDelegate
{
static var instance = TurnOrderManager()
public private(set) var turnOrderIndex: Int = 0
public private(set) var turnOrder: [Turn] = [Turn]() {
didSet {
self.turnOrderWasSet()
}
}
var currentTurn: Turn {
let turnObj = self.turnOrder[turnOrderIndex]
return turnObj
}
var playerOnTurn: Player? {
guard let playerOnTurn = self.currentTurn.player else {
print("No player is on turn")
return nil
}
return (playerOnTurn)
}
var allTurnsCompleted: Bool {
let filtered = turnOrder.filter { (turnObj:Turn) -> Bool in
return (turnObj.completed)
}.count
return (filtered == turnOrder.count)
}
//
// MARK: - Functions
//
func setTurnOrder(players:[Player]) {
if (self.turnOrder.count == 0) {
for playerObj in players {
let turnObj = Turn.init(player: playerObj, delegate: self)
self.turnOrder.append(turnObj)
}
}
}
func next() {
if (turnOrderIndex < (self.turnOrder.count - 1)) {
turnOrderIndex += 1
}
else {
turnOrderIndex = 0
}
}
func markTurnAsComplete() {
self.currentTurn.setAsComplete()
}
// MARK: - TurnOrderManagerDelegate
func turnOrderWasSet() {
for (index, turnObj) in self.turnOrder.enumerated() {
turnObj.player?.setTurnOrderIndex(number: index)
}
}
// MARK: - TurnDelegate
internal func turnIsCompleted() {
print (" - turnIsCompleted -")
TurnOrderManager.instance.next()
}
}
class GameModel {
var turnOrderManager: TurnOrderManager
init() {
self.turnOrderManager = TurnOrderManager.instance
self.turnOrderManager.setTurnOrder(players:[p1,p2])
}
// other game model stuff [...]
}
class BuyFactoryState : GKState {
weak var gameModel: GameModel!
init(gameModel:GameModel) {
super.init()
self.gameModel = gameModel
}
override func isValidNextState(_ stateClass: AnyClass) -> Bool
{
return false //(stateClass is BuyProductionState.Type)
}
override func didEnter(from previousState: GKState?) {
}
override func willExit(to nextState: GKState) {
}
// MARK: - Action
func buy() {
self.gameModel.turnOrderManager.markTurnAsComplete()
self.handleTurn()
}
func pass() {
}
func handleTurn() {
if (self.gameModel.turnOrderManager.allTurnsCompleted) {
print (" -- all turns complete --")
return
}
else {
guard let playerOnTurn = self.gameModel.turnOrderManager.playerOnTurn else {
return
}
print("handleTurn: Player: \(playerOnTurn.name) is on turn, isAI: \(playerOnTurn.isAI)")
if (playerOnTurn.isAI) {
self.buy()
}
else {
print ("Player is human")
return
}
}
}
}
class AI {
func decision(state: GKState) -> Bool {
print ("AI makes a decision")
return true
}
}
class SomeViewController: UIViewController
{
var gameModel: GameModel!
var gameState: BuyFactoryState!
var isPhaseComplete: Bool {
return self.gameModel?.turnOrderManager.allTurnsCompleted ?? false
}
override func viewDidLoad() {
super.viewDidLoad()
self.gameModel = GameModel.init()
self.gameState = BuyFactoryState(gameModel: self.gameModel)
guard let playerOnTurn = gameModel?.turnOrderManager.playerOnTurn else {
print ("no player on turn")
return
}
if (playerOnTurn.isAI) {
self.gameState.handleTurn()
}
else {
// assume human player
self.buyButtonPressed()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func buyButtonPressed() {
print ("human presses buy btn")
self.gameState?.buy()
}
}
class NXTViewController: UIViewController
{
var gameModel: GameModel!
override func viewDidLoad() {
super.viewDidLoad()
for (index, turnObj) in self.gameModel.turnOrderManager.turnOrder.enumerated()
{
print ("#\(index), \(turnObj.completed)")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
let vc = SomeViewController()
vc.viewDidLoad()
|
gpl-3.0
|
02279acfdd9451334803b6440e60a856
| 21.235075 | 100 | 0.587011 | 4.244302 | false | false | false | false |
codefellows/sea-c47-iOS
|
Sample Code/ClassRoster/ClassRoster/ViewController.swift
|
1
|
1238
|
//
// ViewController.swift
// ClassRoster
//
// Created by Bradley Johnson on 9/17/15.
// Copyright (c) 2015 Code Fellows. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var myName = "Brad"
var counter = 0
var numbers = [0,1,2,4]
@IBOutlet weak var myLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
//view.backgroundColor = UIColor.blueColor()
print(view.frame.size)
print("view did load")
numbers = [Int]()
numbers.append(0) //index 0
numbers.append(1) //index 1
numbers.append(1000) //index 2
//myName = "Bradley"
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func buttonPressed(sender: AnyObject) {
counter++
//numbers.append(counter)
//same as counter = counter + 1
if counter > 10 {
counter = 0
}
myLabel.text = "\(counter)"
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
print("view will appear")
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
print("view did appear")
//view.backgroundColor = UIColor.greenColor()
}
}
|
mit
|
9ae93d91cfc96e6d5820423bd901a36a
| 19.983051 | 76 | 0.638934 | 3.993548 | false | false | false | false |
melling/ios_topics
|
CustomTableViewHeaderCell/CustomTableViewHeaderCell/CustomHeaderCell.swift
|
1
|
1589
|
//
// CustomHeaderCell.swift
// CustomTableViewHeaderCell
//
// Created by Michael Mellinger on 11/27/17.
// Copyright © 2017 h4labs. All rights reserved.
//
import UIKit
class CustomTableViewHeaderCell: UIView {
public var label1 = UILabel()
public var label2 = UILabel()
private func _setup() {
let views = [label1, label2]
views.forEach {$0.translatesAutoresizingMaskIntoConstraints = false}
views.forEach(self.addSubview)
NSLayoutConstraint.activate([
label1.topAnchor.constraint(equalTo: self.topAnchor, constant: 0),
label2.topAnchor.constraint(equalTo: self.topAnchor, constant: 0),
label1.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 0),
label2.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 0),
label1.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 4),
label2.leftAnchor.constraint(equalTo: label1.rightAnchor, constant: 4),
label2.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -120),
label2.widthAnchor.constraint(equalTo: label1.widthAnchor, multiplier: 0.5),
])
label1.textAlignment = .center
label2.textAlignment = .center
}
override init(frame: CGRect) {
super.init(frame: frame)
_setup()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// override func layoutSubviews() {
//
// }
}
|
cc0-1.0
|
02b850447c213f93e401614264909d5f
| 31.408163 | 88 | 0.638539 | 4.485876 | false | false | false | false |
karivalkama/Agricola-Scripture-Editor
|
TranslationEditor/FilteredMultiSelection.swift
|
1
|
3939
|
//
// FilteredMultiSelection.swift
// TranslationEditor
//
// Created by Mikko Hilpinen on 28.2.2017.
// Copyright © 2017 SIL. All rights reserved.
//
import UIKit
import HTagView
protocol FilteredMultiSelectionDelegate: class
{
// This function will be called whether the selection status in the multi selection changes
func onSelectionChange(selectedIndices: [Int])
}
// This UI element allows the user to pick multiple elements from a table that also supports filtering
@IBDesignable class FilteredMultiSelection: CustomXibView, UITableViewDataSource, UITableViewDelegate, HTagViewDataSource, HTagViewDelegate, UITextFieldDelegate
{
// OUTLETS -----------------
@IBOutlet weak var searchField: UITextField!
@IBOutlet weak var optionTable: UITableView!
@IBOutlet weak var selectedTagView: HTagView!
// ATTRIBUTES -------------
weak var dataSource: FilteredSelectionDataSource?
weak var delegate: FilteredMultiSelectionDelegate?
private(set) var selectedIndices = [Int]()
private var displayedIndices = [Int]()
// INIT ---------------------
override init(frame: CGRect)
{
super.init(frame: frame)
setupXib(nibName: "FilteredMultiSelection")
}
required init?(coder: NSCoder)
{
super.init(coder: coder)
setupXib(nibName: "FilteredMultiSelection")
}
override func awakeFromNib()
{
optionTable.register(UINib(nibName: "LabelCell", bundle: nil), forCellReuseIdentifier: LabelCell.identifier)
optionTable.dataSource = self
optionTable.delegate = self
selectedTagView.dataSource = self
selectedTagView.delegate = self
}
// ACTIONS ----------------
@IBAction func filterChanged(_ sender: Any)
{
reloadData()
}
// IMPLEMENTED METHODS ----
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return displayedIndices.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
//return UITableViewCell()
// Finds and configures the cell
let cell = tableView.dequeueReusableCell(withIdentifier: LabelCell.identifier, for: indexPath) as! LabelCell
if let dataSouce = dataSource
{
cell.configure(text: dataSouce.labelForOption(atIndex: displayedIndices[indexPath.row]))
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
// Moves the element to selected indices, updates data
selectedIndices.append(displayedIndices[indexPath.row])
reloadData()
delegate?.onSelectionChange(selectedIndices: selectedIndices)
}
func numberOfTags(_ tagView: HTagView) -> Int
{
return selectedIndices.count
}
func tagView(_ tagView: HTagView, titleOfTagAtIndex index: Int) -> String
{
guard let dataSouce = dataSource else
{
print("ERROR: No data source available for multi selection view")
return "???"
}
return dataSouce.labelForOption(atIndex: selectedIndices[index])
}
func tagView(_ tagView: HTagView, tagTypeAtIndex index: Int) -> HTagType
{
return .cancel
}
func tagView(_ tagView: HTagView, didCancelTagAtIndex index: Int)
{
// Deselects the element and refreshes data
selectedIndices.remove(at: index)
reloadData()
delegate?.onSelectionChange(selectedIndices: selectedIndices)
}
// OTHER METHODS --------
func reset()
{
selectedIndices = []
reloadData()
}
func reloadData()
{
guard let dataSouce = dataSource else
{
return
}
if let filter = searchField.text, !filter.isEmpty
{
displayedIndices = (0 ..< dataSouce.numberOfOptions).compactMap { dataSouce.indexIsIncludedInFilter(index: $0, filter: filter) ? $0 : nil }
}
else
{
displayedIndices = Array(0 ..< dataSouce.numberOfOptions)
}
// Does not display the indices that are already selected
displayedIndices = displayedIndices.filter { !selectedIndices.contains($0) }
optionTable.reloadData()
selectedTagView.reloadData(false)
}
}
|
mit
|
cafee8093c30938c86214a883f1056d7
| 23.308642 | 160 | 0.722956 | 3.99797 | false | false | false | false |
rmavani/SocialQP
|
QPrint/Controllers/SideMenu/SideMenu.swift
|
1
|
5313
|
//
// SideMenu.swift
// QPrint
//
// Created by Admin on 23/02/17.
// Copyright © 2017 Admin. All rights reserved.
//
import UIKit
protocol DetailViewControllerDelegate: class {
func didFinishTask(sender: SideMenu, index : IndexPath)
func didSelectButton(sender : UIButton, strType : String)
}
class SideMenuCell: UITableViewCell {
@IBOutlet var lblName : UILabel!
@IBOutlet var imgIcon : UIImageView!
@IBOutlet var imgActive : UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
}
}
class SideMenu: UIViewController , UITableViewDelegate,UITableViewDataSource{
weak var delegate:DetailViewControllerDelegate?
@IBOutlet var tblMenu : UITableView!
@IBOutlet var imgProfileImage : UIImageView!
@IBOutlet var lblName : UILabel!
@IBOutlet var lblMobile : UILabel!
@IBOutlet var lblEmailID : UILabel!
@IBOutlet var viewImage : UIView!
var selectedIndex : Int = 0
// let ArrMerchantMenu = ["Home","My Profile","My Orders","Nearby Store","About Us","Contact Us","Feedback","My Files","Logout"]
//
// let ArrMerchantMenuImage = ["home_sidebar","profile_sidebar","myOrder_sidebar","nearbyStore_sidebar","aboutus_sidebar","contactus_sidebar","feedback_sidebar","files_sidebar","logout_sidebar"]
let ArrMerchantMenu = ["Home","My Profile","My Orders","My Files","Nearby Store","About Us","Feedback","Logout"]
let ArrMerchantMenuImage = ["home_sidebar","profile_sidebar","myOrder_sidebar","files_sidebar","nearbyStore_sidebar","aboutus_sidebar","feedback_sidebar","logout_sidebar"]
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool)
{
viewImage.layer.shadowOpacity = 0.5
viewImage.layer.shadowOffset = CGSize(width : 0.2, height : 0.2)
viewImage.layer.shadowColor = UIColor.darkGray.cgColor
viewImage.layer.cornerRadius = 30.0
let dictData = UserDefaults.standard.data(forKey: "UserData")
let dictRegisterData = NSKeyedUnarchiver.unarchiveObject(with: dictData!) as! NSMutableDictionary
lblName.text = dictRegisterData.object(forKey: "firstname") as? String
lblMobile.text = dictRegisterData.object(forKey: "contactno") as? String
lblEmailID.text = dictRegisterData.object(forKey: "email") as? String
let imgUrl : String = dictRegisterData.value(forKey: "profilepic") as! String
imgProfileImage.sd_setImage(with: NSURL(string: imgUrl) as URL!, placeholderImage: UIImage(named: "defaul_pic"))
if UserDefaults.standard.value(forKey: "selectedIndex") == nil {
UserDefaults.standard.set(selectedIndex, forKey: "selectedIndex")
}
else
{
selectedIndex = UserDefaults.standard.value(forKey: "selectedIndex") as! Int
}
}
@IBAction func btnSettingMenuClick(_ sender: UIButton) {
delegate?.didSelectButton(sender: sender, strType: "setting")
}
@IBAction func btnEditProfileClick(_ sender: UIButton) {
delegate?.didSelectButton(sender: sender, strType: "edit")
}
//Tableview
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return ArrMerchantMenu.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let identifier = "SideMenuCell"
var cell: SideMenuCell! = tableView.dequeueReusableCell(withIdentifier: identifier) as? SideMenuCell
if cell == nil {
tableView.register(UINib(nibName: "SideMenuCell", bundle: nil), forCellReuseIdentifier: identifier)
cell = tableView.dequeueReusableCell(withIdentifier: identifier) as? SideMenuCell
}
cell.imgActive.isHidden = true
cell.lblName.text = ArrMerchantMenu[indexPath.row]
if indexPath.row == selectedIndex {
cell.lblName.textColor = UIColor(red: 24.0/255.0, green: 143.0/255.0, blue: 220.0/255.0, alpha: 1.0)
}
else
{
cell.lblName.textColor = UIColor.black
}
cell.imgIcon.image = UIImage (named: ArrMerchantMenuImage[indexPath.row])
cell.selectionStyle = UITableViewCellSelectionStyle.none
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("You selected cell #\(indexPath.row)!")
selectedIndex = indexPath.row
UserDefaults.standard.set(selectedIndex, forKey: "selectedIndex")
let cell = (tableView.cellForRow(at: indexPath)) as! SideMenuCell
cell.imgActive.isHidden = false
delegate?.didFinishTask(sender: self, index: indexPath)
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
let cell = (tableView.cellForRow(at: indexPath)) as! SideMenuCell
cell.imgActive.isHidden = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
52b90fed664a0b396ad70dd0271a1858
| 36.942857 | 198 | 0.664721 | 4.647419 | false | false | false | false |
cdmx/MiniMancera
|
miniMancera/View/Home/VHomeFooter.swift
|
1
|
3774
|
import UIKit
class VHomeFooter:UIView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout
{
private weak var controller:CHome!
private let kCellSize:CGFloat = 100
private let kDeselectTime:TimeInterval = 0.4
init(controller:CHome)
{
super.init(frame:CGRect.zero)
clipsToBounds = true
backgroundColor = UIColor.clear
translatesAutoresizingMaskIntoConstraints = false
isHidden = true
self.controller = controller
let collectionView:VCollection = VCollection()
collectionView.isScrollEnabled = false
collectionView.bounces = false
collectionView.delegate = self
collectionView.dataSource = self
collectionView.registerCell(cell:VHomeFooterCell.self)
if let flow:VCollectionFlow = collectionView.collectionViewLayout as? VCollectionFlow
{
flow.scrollDirection = UICollectionViewScrollDirection.horizontal
flow.itemSize = CGSize(width:kCellSize, height:kCellSize)
}
addSubview(collectionView)
NSLayoutConstraint.equals(
view:collectionView,
toView:self)
}
required init?(coder:NSCoder)
{
return nil
}
//MARK: private
private func modelAtIndex(index:IndexPath) -> MHomeFooterProtocol
{
let item:MHomeFooterProtocol = controller.model.footer[index.item]
return item
}
//MARK: collectionView delegate
func collectionView(_ collectionView:UICollectionView, layout collectionViewLayout:UICollectionViewLayout, insetForSectionAt section:Int) -> UIEdgeInsets
{
let width:CGFloat = collectionView.bounds.maxX
let height:CGFloat = collectionView.bounds.maxY
let cells:CGFloat = CGFloat(controller.model.footer.count)
let cellsWidth:CGFloat = cells * kCellSize
let remainWidth:CGFloat = width - cellsWidth
let remainHeight:CGFloat = height - kCellSize
let remainWidth_2:CGFloat = remainWidth / 2.0
let insets:UIEdgeInsets = UIEdgeInsets(
top:0,
left:remainWidth_2,
bottom:remainHeight,
right:remainWidth_2)
return insets
}
func numberOfSections(in collectionView:UICollectionView) -> Int
{
return 1
}
func collectionView(_ collectionView:UICollectionView, numberOfItemsInSection section:Int) -> Int
{
let count:Int = controller.model.footer.count
return count
}
func collectionView(_ collectionView:UICollectionView, cellForItemAt indexPath:IndexPath) -> UICollectionViewCell
{
let item:MHomeFooterProtocol = modelAtIndex(index:indexPath)
let cell:VHomeFooterCell = collectionView.dequeueReusableCell(
withReuseIdentifier:
VHomeFooterCell.reusableIdentifier,
for:indexPath) as! VHomeFooterCell
cell.config(model:item)
return cell
}
func collectionView(_ collectionView:UICollectionView, didSelectItemAt indexPath:IndexPath)
{
collectionView.isUserInteractionEnabled = false
let item:MHomeFooterProtocol = modelAtIndex(index:indexPath)
item.selected(controller:controller)
DispatchQueue.main.asyncAfter(
deadline:DispatchTime.now() + kDeselectTime)
{ [weak collectionView] in
collectionView?.isUserInteractionEnabled = true
collectionView?.selectItem(
at:nil,
animated:true,
scrollPosition:UICollectionViewScrollPosition())
}
}
}
|
mit
|
d6a4d652c981707fe08ca89ba5521732
| 32.105263 | 157 | 0.652888 | 5.797235 | false | false | false | false |
ibrdrahim/TopBarMenu
|
TopBarMenu/View2.swift
|
1
|
1914
|
//
// View2.swift
// TopBarMenu
//
// Created by ibrahim on 11/22/16.
// Copyright © 2016 Indosytem. All rights reserved.
//
import UIKit
class View2 : UIView {
@IBOutlet weak var tableView: UITableView!
var contentView : UIView?
var cellIdentifier:String = "view2Cell"
override init(frame: CGRect) {
super.init(frame: frame)
xibSetup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
xibSetup()
// additional option
// use defined table nib, doesnt work in swift 3
//let nibName = UINib(nibName: "InvitationTableViewCell", bundle: nil)
//tableView.register(nibName, forCellReuseIdentifier: cellIdentifier)
// setting up table row
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 100.0
tableView.autoresizingMask = UIViewAutoresizing.flexibleBottomMargin
// don't show table separator
//tableView.separatorStyle = UITableViewCellSeparatorStyle.None
}
func xibSetup() {
contentView = loadViewFromNib()
// use bounds not frame or it'll be offset
contentView!.frame = bounds
// Make the view stretch with containing view
contentView!.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]
// Adding custom subview on top of our view (over any custom drawing > see note below)
addSubview(contentView!)
}
func loadViewFromNib() -> UIView! {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
return view
}
}
|
mit
|
353b80ba6ea066305f83d0cc1bd328f8
| 28.430769 | 109 | 0.619969 | 5.156334 | false | false | false | false |
mtransitapps/mtransit-for-ios
|
MonTransit/Source/Utils/iAdBannerView.swift
|
1
|
2215
|
//
// iAdBannerView.swift
// MonTransit
//
// Created by Thibault on 16-02-10.
// Copyright © 2016 Thibault. All rights reserved.
//
import UIKit
import GoogleMobileAds
extension UIViewController: GADBannerViewDelegate
{
func addIAdBanner()
{
if AgencyManager.getAgency().mDisplayIAds{
let adMobUdid = NSLocalizedString("AdMobKey", tableName: "AdMob", value: "ca-app-pub-3940256099942544/2934735716", comment: "")
let bannerView = GADBannerView(adSize: kGADAdSizeSmartBannerPortrait)
bannerView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(bannerView)
let widthConstraint = NSLayoutConstraint(item: bannerView, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 320)
view.addConstraint(widthConstraint)
let heightConstraint = NSLayoutConstraint(item: bannerView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 50)
view.addConstraint(heightConstraint)
let horizontalConstraint = NSLayoutConstraint(item: bannerView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0)
view.addConstraint(horizontalConstraint)
let bottomConstraint = NSLayoutConstraint(item: bannerView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0)
view.addConstraint(bottomConstraint)
bannerView.adUnitID = adMobUdid
bannerView.rootViewController = self
bannerView.delegate = self
bannerView.loadRequest(GADRequest())
bannerView.hidden = true
}
}
public func adViewDidReceiveAd(bannerView: GADBannerView!) {
bannerView.hidden = false
}
}
|
apache-2.0
|
eb7b1caf82ed81dfa07fd1106769f691
| 44.183673 | 230 | 0.686089 | 5.647959 | false | false | false | false |
watson-developer-cloud/ios-sdk
|
Sources/DiscoveryV1/Models/WordStyle.swift
|
1
|
1568
|
/**
* (C) Copyright IBM Corp. 2018, 2020.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
/**
Microsoft Word styles to convert into a specified HTML head level.
*/
public struct WordStyle: Codable, Equatable {
/**
HTML head level that content matching this style is tagged with.
*/
public var level: Int?
/**
Array of word style names to convert.
*/
public var names: [String]?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case level = "level"
case names = "names"
}
/**
Initialize a `WordStyle` with member variables.
- parameter level: HTML head level that content matching this style is tagged with.
- parameter names: Array of word style names to convert.
- returns: An initialized `WordStyle`.
*/
public init(
level: Int? = nil,
names: [String]? = nil
)
{
self.level = level
self.names = names
}
}
|
apache-2.0
|
ef2b0f31cce83b33b98a89c7321d5c7a
| 26.508772 | 89 | 0.660714 | 4.319559 | false | false | false | false |
HQL-yunyunyun/SinaWeiBo
|
SinaWeiBo/SinaWeiBo/Class/Model/HQLUser.swift
|
1
|
1105
|
//
// HQLUser.swift
// SinaWeiBo
//
// Created by 何启亮 on 16/5/18.
// Copyright © 2016年 HQL. All rights reserved.
//
import Foundation
class HQLUser: NSObject {
// ==================MARK: - 属性
/// 用户UID
var id: Int64 = 0
/// 用户昵称
var screen_name: String?
/// 用户头像地址(中图),50×50像素
var profile_image_url: String?
/// verified_type 没有认证:-1 认证用户:0 企业认证:2,3,5 达人:220
var verified_type: Int = -1
/// 会员等级 1-6
var mbrank: Int = 0
// ==================MARK: - 构造方法
init(dict: [String: AnyObject]) {
super.init()
setValuesForKeysWithDictionary(dict)
}
override func setValue(value: AnyObject?, forUndefinedKey key: String) {return}
override var description: String {
get {
let keys = ["id", "screen_name", "profile_image_url", "verified_type", "mbrank"]
return "\n \t \t用户模型: \(dictionaryWithValuesForKeys(keys))"
}
}
}
|
apache-2.0
|
a6523e4a7dcecbeab1bde62e1590dc67
| 20.76087 | 92 | 0.529471 | 3.575 | false | false | false | false |
mathebox/WorkoutTimer
|
Workout Timer/Workout Timer/Timer.swift
|
1
|
5471
|
//
// Timer.swift
// Workout Timer
//
// Created by Max Bothe on 14/02/16.
// Copyright © 2016 Max Bothe. All rights reserved.
//
import Foundation
import AVFoundation
protocol TimerDelegate {
func updateText(text: String)
}
class Timer : NSObject {
let synth = AVSpeechSynthesizer()
let numberFormatter = NSNumberFormatter()
var remainingDuration = 0
var duration = 0 {
didSet {
self.remainingDuration = self.duration
}
}
var countdownDuration = 10
var timer : NSTimer?
var isRunning : Bool {
return self.timer != nil
}
var speechOption = TimerSpeechOption.None
var delegate : TimerDelegate? {
didSet {
if self.countdownDuration > 0 {
self.delegate?.updateText("\(self.countdownDuration)")
} else {
self.delegate?.updateText("")
}
}
}
var formattedDuration: String {
return String(format: "%d:%02d", self.remainingDuration/60, self.remainingDuration%60)
}
override init() {
super.init()
self.numberFormatter.numberStyle = NSNumberFormatterStyle.SpellOutStyle
let defaults = NSUserDefaults.standardUserDefaults()
if let countdownDuration = defaults.integerForKey("countdown-duration") as Int? {
self.countdownDuration = countdownDuration
}
if let speechOptionString = defaults.stringForKey("timer-speech") as String? {
if let speechOption = TimerSpeechOption(rawValue: speechOptionString) {
self.speechOption = speechOption
}
}
}
func start() {
if let t = self.timer {
t.invalidate()
}
self.countdownDuration++
self.timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "countDown", userInfo: nil, repeats: true)
}
func stop() {
if let t = self.timer {
t.invalidate()
}
}
func countDown() {
self.countdownDuration--
if self.countdownDuration == 0 {
self.delegate?.updateText(self.formattedDuration)
self.timer?.invalidate()
self.say("go")
self.timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "timerAction", userInfo: nil, repeats: true)
} else {
self.delegate?.updateText("\(self.countdownDuration)")
}
if self.countdownDuration > 0 {
saySomethingForDuration(self.countdownDuration)
}
}
func timerAction() {
self.remainingDuration--
if self.remainingDuration == 0 {
self.delegate?.updateText("Done")
self.timer?.invalidate()
self.timer = nil
} else {
self.delegate?.updateText(self.formattedDuration)
}
if self.remainingDuration == 0 {
self.say("done")
} else {
self.saySomethingForDuration(self.remainingDuration)
}
}
func sayMinutesToGo(duration: Int) {
if duration % 60 == 0 {
let minutes = duration / 60
if minutes == 1 {
self.say("1 minute to go")
} else {
if let text = self.numberFormatter.stringFromNumber(minutes) {
self.say("\(text) minutes to go")
}
}
}
}
func sayMinutesPast(duration: Int) {
if duration % 60 == 0 {
let minutes = duration / 60
if minutes == 1 {
self.say("1 minute")
} else {
if let text = self.numberFormatter.stringFromNumber(minutes) {
self.say("\(text) minutes")
}
}
}
}
func sayHalves(duration: Int) {
if self.duration/2 == duration {
self.say("Halftime")
}
}
func sayThirds(duration: Int) {
let timePast = self.duration - duration
if timePast % (self.duration/3) == 0 {
let thirds = timePast/(self.duration/3)
if thirds == 1 {
self.say("one third")
} else {
if let text = numberFormatter.stringFromNumber(thirds) {
self.say("\(text) thirds")
}
}
}
}
func saySomethingForDuration(duration: Int) {
if duration <= 10 {
if let text = self.numberFormatter.stringFromNumber(duration) {
self.say(text)
}
} else if self.speechOption == .ToGo {
self.sayMinutesToGo(duration)
} else if self.speechOption == .Past {
let timePast = self.duration - duration
self.sayMinutesPast(timePast)
} else if self.speechOption == .Combined {
let timePast = self.duration - duration
if timePast > self.remainingDuration {
self.sayMinutesToGo(duration)
} else {
self.sayMinutesPast(timePast)
}
} else if self.speechOption == .Smart {
if self.duration >= 3*60 {
self.sayThirds(duration)
} else if self.duration >= 1*60 {
self.sayHalves(duration)
}
}
}
func say(text: String) {
let myUtterance = AVSpeechUtterance(string: text)
self.synth.speakUtterance(myUtterance)
}
}
|
mit
|
4ac4c9f4580a5e836607bcb4d7429660
| 28.728261 | 135 | 0.545887 | 4.683219 | false | false | false | false |
RedMadRobot/DAO
|
DAO/Classes/RealmDAO/Translator/RealmTranslator.swift
|
1
|
2439
|
//
// RealmTranslator.swift
// DAO
//
// Created by Igor Bulyga on 04.02.16.
// Copyright © 2016 RedMadRobot LLC. All rights reserved.
//
import Foundation
import RealmSwift
open class RealmTranslator<Model: Entity, RealmModel: RLMEntry> {
public required init() {}
open func fill(_ entry: RealmModel, fromEntity: Model) {
fatalError("Abstract method")
}
open func fill(_ entity: Model, fromEntry: RealmModel) {
fatalError("Abstract method")
}
/// All properties of entities will be overridden by entries properties.
/// If entry doesn't exist, it'll be created.
///
/// - Parameters:
/// - entries: list of instances of `RealmModel` type.
/// - fromEntities: array of instances of `Model` type.
open func fill(_ entries: List<RealmModel>, fromEntities: [Model]) {
var newEntries = [RealmModel]()
fromEntities
.map { entity -> (RealmModel, Model) in
let entry = entries.first { $0.entryId == entity.entityId }
if let entry = entry {
return (entry, entity)
} else {
let entry = RealmModel()
newEntries.append(entry)
return (entry, entity)
}
}
.forEach {
self.fill($0.0, fromEntity: $0.1)
}
if fromEntities.count < entries.count {
let entityIds = fromEntities.map { $0.entityId }
let deletedEntriesIndexes = entries
.filter { !entityIds.contains($0.entryId) }
deletedEntriesIndexes.forEach {
if let index = entries.index(of: $0) {
entries.remove(at: index)
}
}
} else {
entries.append(objectsIn: newEntries)
}
}
/// All properties of entries will be overridden by entities properties.
///
/// - Parameters:
/// - entities: array of instances of `Model` type.
/// - fromEntries: list of instances of `RealmModel` type.
open func fill( _ entities: inout [Model], fromEntries: List<RealmModel>) {
entities.removeAll()
fromEntries.forEach {
let model = Model()
entities.append(model)
self.fill(model, fromEntry: $0)
}
}
}
|
mit
|
73698cdedecbb843da42f2ffab28905a
| 28.02381 | 79 | 0.536095 | 4.540037 | false | false | false | false |
ArnavChawla/InteliChat
|
Carthage/Checkouts/swift-sdk/Source/TextToSpeechV1/WAVRepair.swift
|
1
|
5558
|
/**
* Copyright IBM Corporation 2018
*
* 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
internal class WAVRepair {
/**
Convert a big-endian byte buffer to a UTF-8 encoded string.
- parameter data: The byte buffer that contains a big-endian UTF-8 encoded string.
- parameter offset: The location within the byte buffer where the string begins.
- parameter length: The length of the string (without a null-terminating character).
- returns: A String initialized by converting the given big-endian byte buffer into
Unicode characters using a UTF-8 encoding.
*/
private static func dataToUTF8String(data: Data, offset: Int, length: Int) -> String? {
let range = Range(uncheckedBounds: (lower: offset, upper: offset + length))
let subdata = data.subdata(in: range)
return String(data: subdata, encoding: String.Encoding.utf8)
}
/**
Convert a little-endian byte buffer to a UInt32 integer.
- parameter data: The byte buffer that contains a little-endian 32-bit unsigned integer.
- parameter offset: The location within the byte buffer where the integer begins.
- returns: An Int initialized by converting the given little-endian byte buffer into an unsigned 32-bit integer.
*/
private static func dataToUInt32(data: Data, offset: Int) -> Int {
var num: UInt8 = 0
let length = 4
let range = Range(uncheckedBounds: (lower: offset, upper: offset + length))
data.copyBytes(to: &num, from: range)
return Int(num)
}
/**
Returns true if the given data is a WAV-formatted audio file.
To verify that the data is a WAV-formatted audio file, we simply check the "RIFF" chunk
descriptor. That is, we verify that the "ChunkID" field is "RIFF" and the "Format" is "WAVE".
Note that this does not require the "ChunkSize" to be valid and does not guarantee that any
sub-chunks are valid.
- parameter data: The byte buffer that may contain a WAV-formatted audio file.
- returns: `true` if the given data is a WAV-formatted audio file; otherwise, false.
*/
internal static func isWAVFile(data: Data) -> Bool {
// resources for WAV header format:
// [1] http://unusedino.de/ec64/technical/formats/wav.html
// [2] http://soundfile.sapp.org/doc/WaveFormat/
let riffHeaderChunkIDOffset = 0
let riffHeaderChunkIDSize = 4
let riffHeaderChunkSizeOffset = 8
let riffHeaderChunkSizeSize = 4
let riffHeaderSize = 12
guard data.count >= riffHeaderSize else {
return false
}
let riffChunkID = dataToUTF8String(data: data, offset: riffHeaderChunkIDOffset, length: riffHeaderChunkIDSize)
guard riffChunkID == "RIFF" else {
return false
}
let riffFormat = dataToUTF8String(data: data, offset: riffHeaderChunkSizeOffset, length: riffHeaderChunkSizeSize)
guard riffFormat == "WAVE" else {
return false
}
return true
}
/**
Repair the WAV header for a WAV-formatted audio file produced by Watson Text to Speech.
- parameter data: The WAV-formatted audio file produced by Watson Text to Speech.
The byte data will be analyzed and repaired in-place.
*/
internal static func repairWAVHeader(data: inout Data) {
// resources for WAV header format:
// [1] http://unusedino.de/ec64/technical/formats/wav.html
// [2] http://soundfile.sapp.org/doc/WaveFormat/
// update RIFF chunk size
let fileLength = data.count
var riffChunkSize = UInt32(fileLength - 8)
let riffChunkSizeData = Data(bytes: &riffChunkSize, count: MemoryLayout<UInt32>.stride)
data.replaceSubrange(Range(uncheckedBounds: (lower: 4, upper: 8)), with: riffChunkSizeData)
// find data subchunk
var subchunkID: String?
var subchunkSize = 0
var fieldOffset = 12
let fieldSize = 4
while true {
// prevent running off the end of the byte buffer
if fieldOffset + 2*fieldSize >= data.count {
return
}
// read subchunk ID
subchunkID = dataToUTF8String(data: data, offset: fieldOffset, length: fieldSize)
fieldOffset += fieldSize
if subchunkID == "data" {
break
}
// read subchunk size
subchunkSize = dataToUInt32(data: data, offset: fieldOffset)
fieldOffset += fieldSize + subchunkSize
}
// compute data subchunk size (excludes id and size fields)
var dataSubchunkSize = UInt32(data.count - fieldOffset - fieldSize)
// update data subchunk size
let dataSubchunkSizeData = Data(bytes: &dataSubchunkSize, count: MemoryLayout<UInt32>.stride)
data.replaceSubrange(Range(uncheckedBounds: (lower: fieldOffset, upper: fieldOffset+fieldSize)), with: dataSubchunkSizeData)
}
}
|
mit
|
d2a950d7b846457dfa80ba1794c4082f
| 39.569343 | 132 | 0.662109 | 4.335413 | false | false | false | false |
ArnavChawla/InteliChat
|
Carthage/Checkouts/swift-sdk/Source/ConversationV1/Models/DialogNodeNextStep.swift
|
2
|
4751
|
/**
* Copyright IBM Corporation 2018
*
* 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
/** The next step to execute following this dialog node. */
public struct DialogNodeNextStep: Codable {
/// What happens after the dialog node completes. The valid values depend on the node type: - The following values are valid for any node: - `get_user_input` - `skip_user_input` - `jump_to` - If the node is of type `event_handler` and its parent node is of type `slot` or `frame`, additional values are also valid: - if **event_name**=`filled` and the type of the parent node is `slot`: - `reprompt` - `skip_all_slots` - if **event_name**=`nomatch` and the type of the parent node is `slot`: - `reprompt` - `skip_slot` - `skip_all_slots` - if **event_name**=`generic` and the type of the parent node is `frame`: - `reprompt` - `skip_slot` - `skip_all_slots` If you specify `jump_to`, then you must also specify a value for the `dialog_node` property.
public enum Behavior: String {
case getUserInput = "get_user_input"
case skipUserInput = "skip_user_input"
case jumpTo = "jump_to"
case reprompt = "reprompt"
case skipSlot = "skip_slot"
case skipAllSlots = "skip_all_slots"
}
/// Which part of the dialog node to process next.
public enum Selector: String {
case condition = "condition"
case client = "client"
case userInput = "user_input"
case body = "body"
}
/// What happens after the dialog node completes. The valid values depend on the node type: - The following values are valid for any node: - `get_user_input` - `skip_user_input` - `jump_to` - If the node is of type `event_handler` and its parent node is of type `slot` or `frame`, additional values are also valid: - if **event_name**=`filled` and the type of the parent node is `slot`: - `reprompt` - `skip_all_slots` - if **event_name**=`nomatch` and the type of the parent node is `slot`: - `reprompt` - `skip_slot` - `skip_all_slots` - if **event_name**=`generic` and the type of the parent node is `frame`: - `reprompt` - `skip_slot` - `skip_all_slots` If you specify `jump_to`, then you must also specify a value for the `dialog_node` property.
public var behavior: String
/// The ID of the dialog node to process next. This parameter is required if **behavior**=`jump_to`.
public var dialogNode: String?
/// Which part of the dialog node to process next.
public var selector: String?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case behavior = "behavior"
case dialogNode = "dialog_node"
case selector = "selector"
}
/**
Initialize a `DialogNodeNextStep` with member variables.
- parameter behavior: What happens after the dialog node completes. The valid values depend on the node type: - The following values are valid for any node: - `get_user_input` - `skip_user_input` - `jump_to` - If the node is of type `event_handler` and its parent node is of type `slot` or `frame`, additional values are also valid: - if **event_name**=`filled` and the type of the parent node is `slot`: - `reprompt` - `skip_all_slots` - if **event_name**=`nomatch` and the type of the parent node is `slot`: - `reprompt` - `skip_slot` - `skip_all_slots` - if **event_name**=`generic` and the type of the parent node is `frame`: - `reprompt` - `skip_slot` - `skip_all_slots` If you specify `jump_to`, then you must also specify a value for the `dialog_node` property.
- parameter dialogNode: The ID of the dialog node to process next. This parameter is required if **behavior**=`jump_to`.
- parameter selector: Which part of the dialog node to process next.
- returns: An initialized `DialogNodeNextStep`.
*/
public init(behavior: String, dialogNode: String? = nil, selector: String? = nil) {
self.behavior = behavior
self.dialogNode = dialogNode
self.selector = selector
}
}
|
mit
|
3b5df17dcf4bb9ae5512233d31b8a066
| 65.915493 | 836 | 0.656704 | 3.822204 | false | false | false | false |
VoIPGRID/vialer-ios
|
Vialer/Calling/SIP/Controllers/KeypadViewController.swift
|
1
|
5490
|
//
// KeypadViewController.swift
// Copyright © 2016 VoIPGRID. All rights reserved.
//
protocol KeypadViewControllerDelegate {
func dtmfSent(_ dtmfSent: String?)
}
private var myContext = 0
class KeypadViewController: UIViewController {
private struct Configuration {
struct Timing {
static let ConnectDurationInterval = 1.0
}
}
// MARK: - Properties
var call: VSLCall?
var delegate: KeypadViewControllerDelegate?
var callManager: VSLCallManager {
get {
return VialerSIPLib.sharedInstance().callManager
}
}
var phoneNumberLabelText: String? {
didSet {
numberLabel?.text = phoneNumberLabelText
}
}
var dtmfSent: String? {
didSet {
delegate?.dtmfSent(dtmfSent)
DispatchQueue.main.async { [weak self] in
self?.numberLabel.text = self?.dtmfSent
}
}
}
private lazy var dateComponentsFormatter: DateComponentsFormatter = {
let dateComponentsFormatter = DateComponentsFormatter()
dateComponentsFormatter.zeroFormattingBehavior = .pad
dateComponentsFormatter.allowedUnits = [.minute, .second]
return dateComponentsFormatter
}()
private var connectDurationTimer: Timer?
// MARK: - Lifecycle
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
VialerGAITracker.trackScreenForController(name: controllerName)
updateUI()
call?.addObserver(self, forKeyPath: "callState", options: .new, context: &myContext)
startConnectDurationTimer()
}
override func viewWillDisappear(_ animated: Bool) {
call?.removeObserver(self, forKeyPath: "callState")
dtmfSent = nil
self.updateUI()
}
// MARK: - Outlets
@IBOutlet weak var numberLabel: UILabel!
@IBOutlet weak var statusLabel: UILabel!
// MARK: - Actions
@IBAction func numberButtonPressed(_ sender: NumberPadButton) {
guard let call = call, call.callState != .disconnected else { return }
DispatchQueue.main.async{ [weak self] in
if let numberPressed = sender.number {
self?.callManager.sendDTMF(for: call, character: numberPressed) { error in
if error != nil {
VialerLogError("Error sending DTMF: \(String(describing: error))")
} else {
self?.dtmfSent = (self?.dtmfSent ?? "") + numberPressed
}
}
}
}
}
@IBAction func endCallButtonPressed(_ sender: SipCallingButton) {
guard let call = call, call.callState != .disconnected else { return }
callManager.end(call) { error in
if error != nil {
VialerLogError("Error ending call: \(String(describing: error))")
}
}
}
@IBAction func hideButtonPressed(_ sender: UIButton) {
if let navController = self.navigationController {
navController.popViewController(animated: true)
} else {
self.dismiss(animated: true, completion: nil)
}
}
// MARK: - Helper functions
@objc func updateUI() {
numberLabel.text = dtmfSent ?? phoneNumberLabelText
guard let call = call else { return }
switch call.callState {
case .null:
statusLabel.text = ""
case .calling: fallthrough
case .early:
statusLabel.text = NSLocalizedString("Calling...", comment: "Statuslabel state text .Calling")
case .incoming:
statusLabel.text = NSLocalizedString("Incoming call...", comment: "Statuslabel state text .Incoming")
case .connecting:
statusLabel.text = NSLocalizedString("Connecting...", comment: "Statuslabel state text .Connecting")
case .confirmed:
if call.onHold {
statusLabel?.text = NSLocalizedString("On hold", comment: "On hold")
} else {
statusLabel?.text = "\(dateComponentsFormatter.string(from: call.connectDuration)!)"
}
case .disconnected:
statusLabel.text = NSLocalizedString("Call ended", comment: "Statuslabel state text .Disconnected")
}
}
private func startConnectDurationTimer() {
if connectDurationTimer == nil || !connectDurationTimer!.isValid {
connectDurationTimer = Timer.scheduledTimer(timeInterval: Configuration.Timing.ConnectDurationInterval, target: self, selector: #selector(updateUI), userInfo: nil, repeats: true)
}
}
// MARK: - KVO
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if context == &myContext , let call = object as? VSLCall {
DispatchQueue.main.async { [weak self] in
self?.updateUI()
if call.callState == .disconnected {
if let navController = self?.navigationController {
navController.popViewController(animated: true)
} else {
self?.dismiss(animated: true, completion: nil)
}
}
}
} else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
}
}
}
|
gpl-3.0
|
ceb07e163d31778d74f6aa3dd21426df
| 33.093168 | 190 | 0.601202 | 5.173421 | false | false | false | false |
resmio/TastyTomato
|
TastyTomato/Code/Types/BaseClasses/BaseButton.swift
|
1
|
2914
|
//
// BaseButton.swift
// TastyTomato
//
// Created by Jan Nash on 7/27/16.
// Copyright © 2016 resmio. All rights reserved.
//
import UIKit
// MARK: // Public
// MARK: Interface
public extension BaseButton {
// ReadWrite
var adjustsWidthOnTitleSet: Bool {
get {
return self._adjustsWidthOnTitleSet
}
set(newAdjustsWidthOnTitleSet) {
self._adjustsWidthOnTitleSet = newAdjustsWidthOnTitleSet
}
}
var xPadding: CGFloat {
get {
return self._xPadding
}
set(newXPadding) {
self._xPadding = newXPadding
}
}
var yPadding: CGFloat {
get {
return self._yPadding
}
set(newYPadding) {
self._yPadding = newYPadding
}
}
}
// MARK: Class Declaration
public class BaseButton: UIButton {
// Required Init
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setup()
}
// Override Init
public override init(frame: CGRect) {
super.init(frame: frame)
self.setup()
}
public convenience init() {
self.init(frame: .zero)
self.setup()
}
// Private Constants
private let _minimumSideLength: CGFloat = 40
// Private Variables
private var _adjustsWidthOnTitleSet: Bool = true
private var _xPadding: CGFloat = 5
private var _yPadding: CGFloat = 5
// Layout Overrides
public override func sizeThatFits(_ size: CGSize) -> CGSize {
return self._sizeThatFits(size)
}
// setTitle Overrides
public func setTitle(_ title: String) {
self.setTitle(title, for: .normal)
}
public override func setTitle(_ title: String?, for state: State) {
self._setTitle(title, for: state)
}
// Setup
public func setup() {
self._setup()
}
}
// MARK: // Private
// MARK: Setup Implementation
private extension BaseButton {
func _setup() {
self.layer.cornerRadius = 4
self.clipsToBounds = true
}
}
// MARK: Layout Override Implementations
private extension BaseButton {
func _sizeThatFits(_ size: CGSize) -> CGSize {
var size: CGSize = super.sizeThatFits(size)
let widthWithPadding: CGFloat = size.width + (2 * self.xPadding)
let heightWithPadding: CGFloat = size.height + (2 * self.yPadding)
size.width = max(widthWithPadding, self._minimumSideLength)
size.height = max(heightWithPadding, self._minimumSideLength)
return size
}
}
// MARK: setTitle Override Implementation
private extension BaseButton {
func _setTitle(_ title: String?, for state: State) {
super.setTitle(title, for: state)
if self.adjustsWidthOnTitleSet {
self.width = self.sizeThatFits(.zero).width
}
}
}
|
mit
|
426bfbcaa560084af6ea26b5fb71e221
| 22.491935 | 74 | 0.599382 | 4.283824 | false | false | false | false |
ktmswzw/FeelingClientBySwift
|
FeelingClient/MVC/CenterViewController.swift
|
1
|
11757
|
//
// CenterViewController.swift
// FeelingClient
//
// Created by vincent on 14/2/16.
// Copyright © 2016 xecoder. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
import IBAnimatable
import MediaPlayer
import MobileCoreServices
import SwiftyJSON
import Alamofire
import ImagePickerSheetController
class CenterViewController: DesignableViewController,MessageViewModelDelegate , MKMapViewDelegate, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
@IBOutlet var mapView: MKMapView!
@IBOutlet var address: AnimatableTextField!
@IBOutlet var textView: UITextView!
var lockDate:String = ""
@IBOutlet var openUser: UITextField!
@IBOutlet var question: UITextField!
@IBOutlet var answer: UITextField!
@IBOutlet var readFire: UISwitch!
@IBOutlet var limitDate: UIDatePicker!
@IBOutlet var stackView: UIStackView!
@IBOutlet var photoCollectionView: UICollectionView!
@IBOutlet var switchHidden: UISwitch!
@IBOutlet var hidden0: UIView!
@IBOutlet var hidden1: UIView!
@IBOutlet var hidden2: UIView!
@IBOutlet var hidden3: UIView!
@IBOutlet var hidden4: UIView!
@IBOutlet var hidden5: UIView!
@IBOutlet var hidden6: UIView!
@IBOutlet var sendButton: UIBarButtonItem!
@IBAction func chagenSwitch(sender: AnyObject) {
if switchHidden.on {
hiddenView(false)
}
else
{
hiddenView(true)
}
}
var picker = UIImagePickerController()
var viewModel: MessageViewModel!
override func viewDidLoad() {
super.viewDidLoad()
viewModel = MessageViewModel(delegate: self)
self.openUser.text = viewModel.to
let image = UIImage(named: "lonely-children")//lonely-children
let blurredImage = image!.imageByApplyingBlurWithRadius(15)
self.view.layer.contents = blurredImage.CGImage
//地图初始化
self.locationManager.delegate = self
self.locationManager.distanceFilter = 1;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
self.navigationController!.navigationBar.tintColor = UIColor.whiteColor()
self.mapView.showsUserLocation = true
self.photoCollectionView.delegate = self
self.photoCollectionView.dataSource = self
}
//这样将避免约束错误
override func viewDidAppear(animated: Bool) {
hiddenView(true)
//self.sendButton.enabled = false
}
@IBAction func sendMsg(sender: AnyObject) {
// if !self.address.notEmpty {
// self.view.makeToast("定位中,请开启GPS,或在空旷地带,以精确定位", duration: 2, position: .Top)
// return
// }
if !self.openUser.notEmpty {
self.view.makeToast("开启人必须填写", duration: 2, position: .Center)
return
}
if self.textView.text.length == 0 {
self.view.makeToast("必须填写内容", duration: 2, position: .Center)
return
}
viewModel.to = self.openUser.text!
viewModel.limitDate = self.limitDate.date.formatted
viewModel.content = self.textView.text!
viewModel.burnAfterReading = readFire.on
sendMessage()
}
func sendMessage()
{
viewModel.sendMessage()
}
func searchMessage(){}
func hiddenView(flag:Bool){
hidden0.hidden = flag
hidden1.hidden = flag
hidden2.hidden = flag
hidden3.hidden = flag
hidden4.hidden = flag
hidden5.hidden = flag
hidden6.hidden = flag
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
let location = locations.last
viewModel.latitude = location!.coordinate.latitude
viewModel.longitude = location!.coordinate.longitude
let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05))
self.mapView.setRegion(region, animated: true)
CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {
(placemarks, error) -> Void in
if (error != nil) {
print("Reverse geocoder failed with error" + error!.localizedDescription)
return
}
if placemarks!.count > 0 {
let pm = placemarks![0] as CLPlacemark
self.displayLocationInfo(pm)
} else {
print("Problem with the data received from geocoder")
}
})
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError)
{
print("Error: " + error.localizedDescription)
}
func displayLocationInfo(placemark: CLPlacemark) {
//stop updating location to save battery life
locationManager.stopUpdatingLocation()
// print(placemark.locality)
// print(placemark.administrativeArea)
// print(placemark.country)
if let locationName = placemark.addressDictionary!["Name"] as? NSString {
address.text = locationName as String
}
}
func pickerImage() {
let alertController = UIAlertController(title: "选择照片", message: "从相机或者照片中选择", preferredStyle:UIAlertControllerStyle.ActionSheet)
let cameraAction = UIAlertAction(title: "相机", style: .Default) { (action:UIAlertAction!) in
self.picker.sourceType = UIImagePickerControllerSourceType.Camera
//to select only camera controls, not video controls
self.picker.mediaTypes = [kUTTypeImage as String]
self.picker.showsCameraControls = true
self.picker.allowsEditing = true
self.presentViewController(self.picker, animated: true, completion: nil)
}
alertController.addAction(cameraAction)
let albumAction = UIAlertAction(title: "相册", style: .Default) { (action:UIAlertAction!) in
self.picker.delegate = self
self.presentViewController(self.picker, animated: true, completion: nil)
}
alertController.addAction(albumAction)
let cancelAction = UIAlertAction(title: "取消", style: .Cancel) { (action:UIAlertAction!) in
print("you have pressed the Cancel button");
}
alertController.addAction(cancelAction)
self.presentViewController(alertController, animated: true, completion:{ () -> Void in
print("y11111");
})
}
func presentImagePickerSheet() {
let presentImagePickerController: UIImagePickerControllerSourceType -> () = { source in
let controller = UIImagePickerController()
controller.delegate = self
var sourceType = source
if (!UIImagePickerController.isSourceTypeAvailable(sourceType)) {
sourceType = .PhotoLibrary
print("Fallback to camera roll as a source since the simulator doesn't support taking pictures")
}
controller.sourceType = sourceType
self.presentViewController(controller, animated: true, completion: nil)
}
let controller = ImagePickerSheetController(mediaType: .ImageAndVideo)
controller.addAction(ImagePickerAction(title: NSLocalizedString("拍摄", comment: "标题"),handler: { _ in
presentImagePickerController(.Camera)
}, secondaryHandler: { _, numberOfPhotos in
for ass in controller.selectedImageAssets
{
let image = getAssetThumbnail(ass)
self.viewModel.imageData.append(image)
}
self.photoCollectionView.reloadData()
}))
controller.addAction(ImagePickerAction(title: NSLocalizedString("相册", comment: "标题"), secondaryTitle: { NSString.localizedStringWithFormat(NSLocalizedString("ImagePickerSheet.button1.Send %lu Photo", comment: "Action Title"), $0) as String}, handler: { _ in
presentImagePickerController(.PhotoLibrary)
}, secondaryHandler: { _, numberOfPhotos in
//print("Send \(controller.selectedImageAssets)")
for ass in controller.selectedImageAssets
{
let image = getAssetThumbnail(ass)
self.viewModel.imageData.append(image)
}
self.photoCollectionView.reloadData()
}))
controller.addAction(ImagePickerAction(title: NSLocalizedString("取消", comment: "Action Title"), style: .Cancel, handler: { _ in
//print("Cancelled")
}))
if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
controller.modalPresentationStyle = .Popover
controller.popoverPresentationController?.sourceView = view
controller.popoverPresentationController?.sourceRect = CGRect(origin: view.center, size: CGSize())
}
presentViewController(controller, animated: true, completion: nil)
}
}
extension CenterViewController: UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.viewModel.imageData.count + 1
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
//pickerImage()
presentImagePickerSheet()
//self.presentViewController(picker, animated: true, completion: nil)
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
var cell: UICollectionViewCell
switch indexPath.row {
case self.viewModel.imageData.count:
cell = collectionView.dequeueReusableCellWithReuseIdentifier("newCell", forIndexPath: indexPath)
default:
cell = collectionView.dequeueReusableCellWithReuseIdentifier("photo", forIndexPath: indexPath)
let imgV = UIImageView(image: self.viewModel.imageData[indexPath.row])
imgV.frame = cell.frame
cell.backgroundView = imgV
cell.layer.cornerRadius = 5
}
return cell
}
}
extension CenterViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
self.viewModel.imageData.append(image)
photoCollectionView.reloadData()
dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
dismissViewControllerAnimated(true, completion: nil)
}
}
|
mit
|
ad01673a3f62359bece50e9ee0718b64
| 37.039344 | 265 | 0.641786 | 5.60754 | false | false | false | false |
RainbowMango/UISwitchDemo
|
UISwitchDemo/UISwitchDemo/AppDelegate.swift
|
1
|
6124
|
//
// AppDelegate.swift
// UISwitchDemo
//
// Created by ruby on 14-12-25.
// Copyright (c) 2014年 ruby. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.ruby.UISwitchDemo" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("UISwitchDemo", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("UISwitchDemo.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
let dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
|
apache-2.0
|
53a19844452947543bce25e9d4f1cb0f
| 54.153153 | 290 | 0.716433 | 5.780925 | false | false | false | false |
kstaring/swift
|
test/IDE/complete_associated_types.swift
|
3
|
18402
|
// RUN: sed -n -e '1,/NO_ERRORS_UP_TO_HERE$/ p' %s > %t_no_errors.swift
// RUN: %target-swift-frontend -parse -verify %t_no_errors.swift
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=STRUCT_AS_TYPE > %t.types.txt
// RUN: %FileCheck %s -check-prefix=STRUCT_TYPE_COUNT < %t.types.txt
// RUN: %FileCheck %s -check-prefix=STRUCT_TYPES < %t.types.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=STRUCT_AS_EXPR > %t.types.txt
// RUN: %FileCheck %s -check-prefix=STRUCT_TYPES < %t.types.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=STRUCT_INSTANCE > %t.types.txt
// RUN: %FileCheck %s -check-prefix=STRUCT_INSTANCE < %t.types.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ASSOCIATED_TYPES_UNQUAL_1 > %t.types.txt
// RUN: %FileCheck %s -check-prefix=ASSOCIATED_TYPES_UNQUAL < %t.types.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ASSOCIATED_TYPES_UNQUAL_2 > %t.types.txt
// RUN: %FileCheck %s -check-prefix=ASSOCIATED_TYPES_UNQUAL < %t.types.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=BROKEN_CONFORMANCE_1 > %t.types.txt
// RUN: %FileCheck %s -check-prefix=BROKEN_CONFORMANCE_1 < %t.types.txt
// FIXME: extensions that introduce conformances?
protocol FooBaseProtocolWithAssociatedTypes {
associatedtype DefaultedTypeCommonA = Int
associatedtype DefaultedTypeCommonB = Int
associatedtype DefaultedTypeCommonC = Int
associatedtype DefaultedTypeCommonD = Int
associatedtype FooBaseDefaultedTypeA = Int
associatedtype FooBaseDefaultedTypeB = Int
associatedtype FooBaseDefaultedTypeC = Int
associatedtype DeducedTypeCommonA
associatedtype DeducedTypeCommonB
associatedtype DeducedTypeCommonC
associatedtype DeducedTypeCommonD
func deduceCommonA() -> DeducedTypeCommonA
func deduceCommonB() -> DeducedTypeCommonB
func deduceCommonC() -> DeducedTypeCommonC
func deduceCommonD() -> DeducedTypeCommonD
associatedtype FooBaseDeducedTypeA
associatedtype FooBaseDeducedTypeB
associatedtype FooBaseDeducedTypeC
associatedtype FooBaseDeducedTypeD
func deduceFooBaseA() -> FooBaseDeducedTypeA
func deduceFooBaseB() -> FooBaseDeducedTypeB
func deduceFooBaseC() -> FooBaseDeducedTypeC
func deduceFooBaseD() -> FooBaseDeducedTypeD
}
protocol FooProtocolWithAssociatedTypes : FooBaseProtocolWithAssociatedTypes {
// From FooBase.
associatedtype DefaultedTypeCommonA = Int
associatedtype DefaultedTypeCommonB = Int
associatedtype FooBaseDefaultedTypeB = Double
associatedtype DeducedTypeCommonA
associatedtype DeducedTypeCommonB
func deduceCommonA() -> DeducedTypeCommonA
func deduceCommonB() -> DeducedTypeCommonB
func deduceFooBaseB() -> Int
// New decls.
associatedtype FooDefaultedType = Int
associatedtype FooDeducedTypeB
associatedtype FooDeducedTypeC
associatedtype FooDeducedTypeD
func deduceFooB() -> FooDeducedTypeB
func deduceFooC() -> FooDeducedTypeC
func deduceFooD() -> FooDeducedTypeD
}
protocol BarBaseProtocolWithAssociatedTypes {
// From FooBase.
associatedtype DefaultedTypeCommonA = Int
associatedtype DefaultedTypeCommonC = Int
associatedtype DeducedTypeCommonA
associatedtype DeducedTypeCommonC
func deduceCommonA() -> DeducedTypeCommonA
func deduceCommonC() -> DeducedTypeCommonC
func deduceFooBaseC() -> Int
// From Foo.
func deduceFooC() -> Int
// New decls.
associatedtype BarBaseDefaultedType = Int
associatedtype BarBaseDeducedTypeC
associatedtype BarBaseDeducedTypeD
func deduceBarBaseC() -> BarBaseDeducedTypeC
func deduceBarBaseD() -> BarBaseDeducedTypeD
}
protocol BarProtocolWithAssociatedTypes : BarBaseProtocolWithAssociatedTypes {
// From FooBase.
associatedtype DefaultedTypeCommonA = Int
associatedtype DefaultedTypeCommonD = Int
associatedtype DeducedTypeCommonA
associatedtype DeducedTypeCommonD
func deduceCommonA() -> DeducedTypeCommonA
func deduceCommonD() -> DeducedTypeCommonD
func deduceFooBaseD() -> Int
// From Foo.
func deduceFooD() -> Int
// From BarBase.
func deduceBarBaseD() -> Int
// New decls.
associatedtype BarDefaultedTypeA = Int
associatedtype BarDeducedTypeD
func deduceBarD() -> BarDeducedTypeD
}
struct StructWithAssociatedTypes : FooProtocolWithAssociatedTypes, BarProtocolWithAssociatedTypes {
typealias FooBaseDefaultedTypeC = Double
func deduceCommonA() -> Int { return 0 }
func deduceCommonB() -> Int { return 0 }
func deduceCommonC() -> Int { return 0 }
func deduceCommonD() -> Int { return 0 }
func deduceFooBaseA() -> Int { return 0 }
func deduceFooBaseB() -> Int { return 0 }
func deduceFooBaseC() -> Int { return 0 }
func deduceFooBaseD() -> Int { return 0 }
func deduceFooB() -> Int { return 0 }
func deduceFooC() -> Int { return 0 }
func deduceFooD() -> Int { return 0 }
func deduceBarBaseC() -> Int { return 0 }
func deduceBarBaseD() -> Int { return 0 }
func deduceBarD() -> Int { return 0 }
}
class ClassWithAssociatedTypes : FooProtocolWithAssociatedTypes, BarProtocolWithAssociatedTypes {
typealias FooBaseDefaultedTypeC = Double
func deduceCommonA() -> Int { return 0 }
func deduceCommonB() -> Int { return 0 }
func deduceCommonC() -> Int { return 0 }
func deduceCommonD() -> Int { return 0 }
func deduceFooBaseA() -> Int { return 0 }
func deduceFooBaseB() -> Int { return 0 }
func deduceFooBaseC() -> Int { return 0 }
func deduceFooBaseD() -> Int { return 0 }
func deduceFooB() -> Int { return 0 }
func deduceFooC() -> Int { return 0 }
func deduceFooD() -> Int { return 0 }
func deduceBarBaseC() -> Int { return 0 }
func deduceBarBaseD() -> Int { return 0 }
func deduceBarD() -> Int { return 0 }
}
// NO_ERRORS_UP_TO_HERE
func testStruct1() {
var x: StructWithAssociatedTypes#^STRUCT_AS_TYPE^#
}
func testStruct2() {
StructWithAssociatedTypes#^STRUCT_AS_EXPR^#
}
func testStruct3(a: StructWithAssociatedTypes) {
a.#^STRUCT_INSTANCE^#
}
// STRUCT_TYPE_COUNT: Begin completions, 26 items
// STRUCT_INSTANCE: Begin completions, 14 items
// STRUCT_INSTANCE-DAG: Decl[InstanceMethod]/CurrNominal: deduceCommonA()[#Int#]
// STRUCT_INSTANCE-DAG: Decl[InstanceMethod]/CurrNominal: deduceCommonB()[#Int#]
// STRUCT_INSTANCE-DAG: Decl[InstanceMethod]/CurrNominal: deduceCommonC()[#Int#]
// STRUCT_INSTANCE-DAG: Decl[InstanceMethod]/CurrNominal: deduceCommonD()[#Int#]
// STRUCT_INSTANCE-DAG: Decl[InstanceMethod]/CurrNominal: deduceFooBaseA()[#Int#]
// STRUCT_INSTANCE-DAG: Decl[InstanceMethod]/CurrNominal: deduceFooBaseB()[#Int#]
// STRUCT_INSTANCE-DAG: Decl[InstanceMethod]/CurrNominal: deduceFooBaseC()[#Int#]
// STRUCT_INSTANCE-DAG: Decl[InstanceMethod]/CurrNominal: deduceFooBaseD()[#Int#]
// STRUCT_INSTANCE-DAG: Decl[InstanceMethod]/CurrNominal: deduceFooB()[#Int#]
// STRUCT_INSTANCE-DAG: Decl[InstanceMethod]/CurrNominal: deduceFooC()[#Int#]
// STRUCT_INSTANCE-DAG: Decl[InstanceMethod]/CurrNominal: deduceFooD()[#Int#]
// STRUCT_INSTANCE-DAG: Decl[InstanceMethod]/CurrNominal: deduceBarBaseC()[#Int#]
// STRUCT_INSTANCE-DAG: Decl[InstanceMethod]/CurrNominal: deduceBarBaseD()[#Int#]
// STRUCT_INSTANCE-DAG: Decl[InstanceMethod]/CurrNominal: deduceBarD()[#Int#]
// STRUCT_INSTANCE: End completions
// STRUCT_TYPES: Begin completions
// STRUCT_TYPES-DAG: Decl[TypeAlias]/CurrNominal: .DefaultedTypeCommonA[#Int#]{{; name=.+$}}
// STRUCT_TYPES-DAG: Decl[TypeAlias]/CurrNominal: .DefaultedTypeCommonD[#Int#]{{; name=.+$}}
// STRUCT_TYPES-DAG: Decl[TypeAlias]/CurrNominal: .DeducedTypeCommonA[#Int#]{{; name=.+$}}
// STRUCT_TYPES-DAG: Decl[TypeAlias]/CurrNominal: .DeducedTypeCommonD[#Int#]{{; name=.+$}}
// STRUCT_TYPES-DAG: Decl[TypeAlias]/CurrNominal: .BarDefaultedTypeA[#Int#]{{; name=.+$}}
// STRUCT_TYPES-DAG: Decl[TypeAlias]/CurrNominal: .BarDeducedTypeD[#Int#]{{; name=.+$}}
// STRUCT_TYPES-DAG: Decl[TypeAlias]/CurrNominal: .DefaultedTypeCommonC[#Int#]{{; name=.+$}}
// STRUCT_TYPES-DAG: Decl[TypeAlias]/CurrNominal: .DeducedTypeCommonC[#Int#]{{; name=.+$}}
// STRUCT_TYPES-DAG: Decl[TypeAlias]/CurrNominal: .BarBaseDefaultedType[#Int#]{{; name=.+$}}
// STRUCT_TYPES-DAG: Decl[TypeAlias]/CurrNominal: .BarBaseDeducedTypeC[#Int#]{{; name=.+$}}
// STRUCT_TYPES-DAG: Decl[TypeAlias]/CurrNominal: .BarBaseDeducedTypeD[#Int#]{{; name=.+$}}
// STRUCT_TYPES-DAG: Decl[TypeAlias]/CurrNominal: .DefaultedTypeCommonB[#Int#]{{; name=.+$}}
// STRUCT_TYPES-DAG: Decl[TypeAlias]/CurrNominal: .FooBaseDefaultedTypeB[#Double#]{{; name=.+$}}
// STRUCT_TYPES-DAG: Decl[TypeAlias]/CurrNominal: .DeducedTypeCommonB[#Int#]{{; name=.+$}}
// STRUCT_TYPES-DAG: Decl[TypeAlias]/CurrNominal: .FooDefaultedType[#Int#]{{; name=.+$}}
// STRUCT_TYPES-DAG: Decl[TypeAlias]/CurrNominal: .FooDeducedTypeB[#Int#]{{; name=.+$}}
// STRUCT_TYPES-DAG: Decl[TypeAlias]/CurrNominal: .FooDeducedTypeC[#Int#]{{; name=.+$}}
// STRUCT_TYPES-DAG: Decl[TypeAlias]/CurrNominal: .FooDeducedTypeD[#Int#]{{; name=.+$}}
// STRUCT_TYPES-DAG: Decl[TypeAlias]/CurrNominal: .FooBaseDefaultedTypeA[#Int#]{{; name=.+$}}
// STRUCT_TYPES-DAG: Decl[TypeAlias]/CurrNominal: .FooBaseDeducedTypeA[#Int#]{{; name=.+$}}
// STRUCT_TYPES-DAG: Decl[TypeAlias]/CurrNominal: .FooBaseDeducedTypeB[#Int#]{{; name=.+$}}
// STRUCT_TYPES-DAG: Decl[TypeAlias]/CurrNominal: .FooBaseDeducedTypeC[#Int#]{{; name=.+$}}
// STRUCT_TYPES-DAG: Decl[TypeAlias]/CurrNominal: .FooBaseDeducedTypeD[#Int#]{{; name=.+$}}
// STRUCT_TYPES-DAG: Decl[TypeAlias]/CurrNominal: .FooBaseDefaultedTypeC[#Double#]{{; name=.+$}}
// STRUCT_TYPES: End completions
class DerivedFromClassWithAssociatedTypes : ClassWithAssociatedTypes {
func test() {
#^ASSOCIATED_TYPES_UNQUAL_1^#
}
}
class MoreDerivedFromClassWithAssociatedTypes : DerivedFromClassWithAssociatedTypes {
func test() {
#^ASSOCIATED_TYPES_UNQUAL_2^#
}
}
// ASSOCIATED_TYPES_UNQUAL: Begin completions
// ASSOCIATED_TYPES_UNQUAL-DAG: Decl[TypeAlias]/Super: DefaultedTypeCommonA[#Int#]{{; name=.+$}}
// ASSOCIATED_TYPES_UNQUAL-DAG: Decl[TypeAlias]/Super: DefaultedTypeCommonD[#Int#]{{; name=.+$}}
// ASSOCIATED_TYPES_UNQUAL-DAG: Decl[TypeAlias]/Super: DeducedTypeCommonA[#Int#]{{; name=.+$}}
// ASSOCIATED_TYPES_UNQUAL-DAG: Decl[TypeAlias]/Super: DeducedTypeCommonD[#Int#]{{; name=.+$}}
// ASSOCIATED_TYPES_UNQUAL-DAG: Decl[TypeAlias]/Super: BarDefaultedTypeA[#Int#]{{; name=.+$}}
// ASSOCIATED_TYPES_UNQUAL-DAG: Decl[TypeAlias]/Super: BarDeducedTypeD[#Int#]{{; name=.+$}}
// ASSOCIATED_TYPES_UNQUAL-DAG: Decl[TypeAlias]/Super: DefaultedTypeCommonC[#Int#]{{; name=.+$}}
// ASSOCIATED_TYPES_UNQUAL-DAG: Decl[TypeAlias]/Super: DeducedTypeCommonC[#Int#]{{; name=.+$}}
// ASSOCIATED_TYPES_UNQUAL-DAG: Decl[TypeAlias]/Super: BarBaseDefaultedType[#Int#]{{; name=.+$}}
// ASSOCIATED_TYPES_UNQUAL-DAG: Decl[TypeAlias]/Super: BarBaseDeducedTypeC[#Int#]{{; name=.+$}}
// ASSOCIATED_TYPES_UNQUAL-DAG: Decl[TypeAlias]/Super: BarBaseDeducedTypeD[#Int#]{{; name=.+$}}
// ASSOCIATED_TYPES_UNQUAL-DAG: Decl[TypeAlias]/Super: DefaultedTypeCommonB[#Int#]{{; name=.+$}}
// ASSOCIATED_TYPES_UNQUAL-DAG: Decl[TypeAlias]/Super: FooBaseDefaultedTypeB[#Double#]{{; name=.+$}}
// ASSOCIATED_TYPES_UNQUAL-DAG: Decl[TypeAlias]/Super: DeducedTypeCommonB[#Int#]{{; name=.+$}}
// ASSOCIATED_TYPES_UNQUAL-DAG: Decl[TypeAlias]/Super: FooDefaultedType[#Int#]{{; name=.+$}}
// ASSOCIATED_TYPES_UNQUAL-DAG: Decl[TypeAlias]/Super: FooDeducedTypeB[#Int#]{{; name=.+$}}
// ASSOCIATED_TYPES_UNQUAL-DAG: Decl[TypeAlias]/Super: FooDeducedTypeC[#Int#]{{; name=.+$}}
// ASSOCIATED_TYPES_UNQUAL-DAG: Decl[TypeAlias]/Super: FooDeducedTypeD[#Int#]{{; name=.+$}}
// ASSOCIATED_TYPES_UNQUAL-DAG: Decl[TypeAlias]/Super: FooBaseDefaultedTypeA[#Int#]{{; name=.+$}}
// ASSOCIATED_TYPES_UNQUAL-DAG: Decl[TypeAlias]/Super: FooBaseDefaultedTypeB[#Double#]{{; name=.+$}}
// ASSOCIATED_TYPES_UNQUAL-DAG: Decl[TypeAlias]/Super: FooBaseDeducedTypeA[#Int#]{{; name=.+$}}
// ASSOCIATED_TYPES_UNQUAL-DAG: Decl[TypeAlias]/Super: FooBaseDeducedTypeB[#Int#]{{; name=.+$}}
// ASSOCIATED_TYPES_UNQUAL-DAG: Decl[TypeAlias]/Super: FooBaseDeducedTypeC[#Int#]{{; name=.+$}}
// ASSOCIATED_TYPES_UNQUAL-DAG: Decl[TypeAlias]/Super: FooBaseDeducedTypeD[#Int#]{{; name=.+$}}
// ASSOCIATED_TYPES_UNQUAL: End completions
struct StructWithBrokenConformance : FooProtocolWithAssociatedTypes {
// Does not conform.
}
func testBrokenConformances1() {
StructWithBrokenConformance.#^BROKEN_CONFORMANCE_1^#
}
// BROKEN_CONFORMANCE_1: Begin completions, 34 items
// BROKEN_CONFORMANCE_1-DAG: Decl[TypeAlias]/CurrNominal: DefaultedTypeCommonA[#StructWithBrokenConformance.DefaultedTypeCommonA#]; name=DefaultedTypeCommonA
// BROKEN_CONFORMANCE_1-DAG: Decl[TypeAlias]/CurrNominal: DefaultedTypeCommonB[#StructWithBrokenConformance.DefaultedTypeCommonB#]; name=DefaultedTypeCommonB
// BROKEN_CONFORMANCE_1-DAG: Decl[TypeAlias]/CurrNominal: FooBaseDefaultedTypeB[#StructWithBrokenConformance.FooBaseDefaultedTypeB#]; name=FooBaseDefaultedTypeB
// BROKEN_CONFORMANCE_1-DAG: Decl[TypeAlias]/CurrNominal: DeducedTypeCommonA[#StructWithBrokenConformance.DeducedTypeCommonA#]; name=DeducedTypeCommonA
// BROKEN_CONFORMANCE_1-DAG: Decl[TypeAlias]/CurrNominal: DeducedTypeCommonB[#StructWithBrokenConformance.DeducedTypeCommonB#]; name=DeducedTypeCommonB
// BROKEN_CONFORMANCE_1-DAG: Decl[InstanceMethod]/Super: deduceCommonA({#self: StructWithBrokenConformance#})[#() -> StructWithBrokenConformance.DeducedTypeCommonA#]{{; name=.+$}}
// BROKEN_CONFORMANCE_1-DAG: Decl[InstanceMethod]/Super: deduceCommonB({#self: StructWithBrokenConformance#})[#() -> StructWithBrokenConformance.DeducedTypeCommonB#]{{; name=.+$}}
// BROKEN_CONFORMANCE_1-DAG: Decl[InstanceMethod]/Super: deduceFooBaseB({#self: StructWithBrokenConformance#})[#() -> Int#]{{; name=.+$}}
// BROKEN_CONFORMANCE_1-DAG: Decl[TypeAlias]/CurrNominal: FooDefaultedType[#StructWithBrokenConformance.FooDefaultedType#]; name=FooDefaultedType
// BROKEN_CONFORMANCE_1-DAG: Decl[TypeAlias]/CurrNominal: FooDeducedTypeB[#StructWithBrokenConformance.FooDeducedTypeB#]; name=FooDeducedTypeB
// BROKEN_CONFORMANCE_1-DAG: Decl[TypeAlias]/CurrNominal: FooDeducedTypeC[#StructWithBrokenConformance.FooDeducedTypeC#]; name=FooDeducedTypeC
// BROKEN_CONFORMANCE_1-DAG: Decl[TypeAlias]/CurrNominal: FooDeducedTypeD[#StructWithBrokenConformance.FooDeducedTypeD#]; name=FooDeducedTypeD
// BROKEN_CONFORMANCE_1-DAG: Decl[InstanceMethod]/Super: deduceFooB({#self: StructWithBrokenConformance#})[#() -> StructWithBrokenConformance.FooDeducedTypeB#]{{; name=.+$}}
// BROKEN_CONFORMANCE_1-DAG: Decl[InstanceMethod]/Super: deduceFooC({#self: StructWithBrokenConformance#})[#() -> StructWithBrokenConformance.FooDeducedTypeC#]{{; name=.+$}}
// BROKEN_CONFORMANCE_1-DAG: Decl[InstanceMethod]/Super: deduceFooD({#self: StructWithBrokenConformance#})[#() -> StructWithBrokenConformance.FooDeducedTypeD#]{{; name=.+$}}
// BROKEN_CONFORMANCE_1-DAG: Decl[TypeAlias]/CurrNominal: DefaultedTypeCommonC[#StructWithBrokenConformance.DefaultedTypeCommonC#]; name=DefaultedTypeCommonC
// BROKEN_CONFORMANCE_1-DAG: Decl[TypeAlias]/CurrNominal: DefaultedTypeCommonD[#StructWithBrokenConformance.DefaultedTypeCommonD#]; name=DefaultedTypeCommonD
// BROKEN_CONFORMANCE_1-DAG: Decl[TypeAlias]/CurrNominal: FooBaseDefaultedTypeA[#StructWithBrokenConformance.FooBaseDefaultedTypeA#]; name=FooBaseDefaultedTypeA
// BROKEN_CONFORMANCE_1-DAG: Decl[TypeAlias]/CurrNominal: FooBaseDefaultedTypeC[#StructWithBrokenConformance.FooBaseDefaultedTypeC#]; name=FooBaseDefaultedTypeC
// BROKEN_CONFORMANCE_1-DAG: Decl[TypeAlias]/CurrNominal: DeducedTypeCommonC[#StructWithBrokenConformance.DeducedTypeCommonC#]; name=DeducedTypeCommonC
// BROKEN_CONFORMANCE_1-DAG: Decl[TypeAlias]/CurrNominal: DeducedTypeCommonD[#StructWithBrokenConformance.DeducedTypeCommonD#]; name=DeducedTypeCommonD
// BROKEN_CONFORMANCE_1-DAG: Decl[InstanceMethod]/Super: deduceCommonA({#self: StructWithBrokenConformance#})[#() -> StructWithBrokenConformance.DeducedTypeCommonA#]{{; name=.+$}}
// BROKEN_CONFORMANCE_1-DAG: Decl[InstanceMethod]/Super: deduceCommonB({#self: StructWithBrokenConformance#})[#() -> StructWithBrokenConformance.DeducedTypeCommonB#]{{; name=.+$}}
// BROKEN_CONFORMANCE_1-DAG: Decl[InstanceMethod]/Super: deduceCommonC({#self: StructWithBrokenConformance#})[#() -> StructWithBrokenConformance.DeducedTypeCommonC#]{{; name=.+$}}
// BROKEN_CONFORMANCE_1-DAG: Decl[InstanceMethod]/Super: deduceCommonD({#self: StructWithBrokenConformance#})[#() -> StructWithBrokenConformance.DeducedTypeCommonD#]{{; name=.+$}}
// BROKEN_CONFORMANCE_1-DAG: Decl[TypeAlias]/CurrNominal: FooBaseDeducedTypeA[#StructWithBrokenConformance.FooBaseDeducedTypeA#]; name=FooBaseDeducedTypeA
// BROKEN_CONFORMANCE_1-DAG: Decl[TypeAlias]/CurrNominal: FooBaseDeducedTypeB[#StructWithBrokenConformance.FooBaseDeducedTypeB#]; name=FooBaseDeducedTypeB
// BROKEN_CONFORMANCE_1-DAG: Decl[TypeAlias]/CurrNominal: FooBaseDeducedTypeC[#StructWithBrokenConformance.FooBaseDeducedTypeC#]; name=FooBaseDeducedTypeC
// BROKEN_CONFORMANCE_1-DAG: Decl[TypeAlias]/CurrNominal: FooBaseDeducedTypeD[#StructWithBrokenConformance.FooBaseDeducedTypeD#]; name=FooBaseDeducedTypeD
// BROKEN_CONFORMANCE_1-DAG: Decl[InstanceMethod]/Super: deduceFooBaseA({#self: StructWithBrokenConformance#})[#() -> StructWithBrokenConformance.FooBaseDeducedTypeA#]{{; name=.+$}}
// BROKEN_CONFORMANCE_1-DAG: Decl[InstanceMethod]/Super: deduceFooBaseB({#self: StructWithBrokenConformance#})[#() -> StructWithBrokenConformance.FooBaseDeducedTypeB#]{{; name=.+$}}
// BROKEN_CONFORMANCE_1-DAG: Decl[InstanceMethod]/Super: deduceFooBaseC({#self: StructWithBrokenConformance#})[#() -> StructWithBrokenConformance.FooBaseDeducedTypeC#]{{; name=.+$}}
// BROKEN_CONFORMANCE_1-DAG: Decl[InstanceMethod]/Super: deduceFooBaseD({#self: StructWithBrokenConformance#})[#() -> StructWithBrokenConformance.FooBaseDeducedTypeD#]{{; name=.+$}}
// BROKEN_CONFORMANCE_1: End completions
|
apache-2.0
|
9169d8c511c91d31fb774e85e75edba2
| 59.732673 | 189 | 0.740463 | 3.774769 | false | false | false | false |
elysiumd/ios-wallet
|
BreadWallet/BRHTTPServer.swift
|
2
|
24331
|
//
// BRHTTPServer.swift
// BreadWallet
//
// Created by Samuel Sutch on 2/8/16.
// Copyright (c) 2016 breadwallet LLC
//
// 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
enum BRHTTPServerError: Error {
case socketCreationFailed
case socketBindFailed
case socketListenFailed
case socketRecvFailed
case socketWriteFailed
case invalidHttpRequest
case invalidRangeHeader
}
@objc public protocol BRHTTPMiddleware {
func handle(_ request: BRHTTPRequest, next: @escaping (BRHTTPMiddlewareResponse) -> Void)
}
@objc open class BRHTTPMiddlewareResponse: NSObject {
var request: BRHTTPRequest
var response: BRHTTPResponse?
init(request: BRHTTPRequest, response: BRHTTPResponse?) {
self.request = request
self.response = response
}
}
@objc open class BRHTTPServer: NSObject {
var fd: Int32 = -1
var clients: Set<Int32> = []
var middleware: [BRHTTPMiddleware] = [BRHTTPMiddleware]()
var isStarted: Bool { return fd != -1 }
var port: in_port_t = 0
var listenAddress: String = "127.0.0.1"
var _Q: DispatchQueue? = nil
var Q: DispatchQueue {
if _Q == nil {
_Q = DispatchQueue(label: "br_http_server", attributes: DispatchQueue.Attributes.concurrent)
}
return _Q!
}
func prependMiddleware(middleware mw: BRHTTPMiddleware) {
middleware.insert(mw, at: 0)
}
func appendMiddleware(middle mw: BRHTTPMiddleware) {
middleware.append(mw)
}
func resetMiddleware() {
middleware.removeAll()
}
func start() throws {
for _ in 0 ..< 100 {
// get a random port
let port = in_port_t(arc4random() % (49152 - 1024) + 1024)
do {
try listenServer(port)
self.port = port
// backgrounding
NotificationCenter.default.addObserver(
self, selector: #selector(BRHTTPServer.suspend(_:)),
name: NSNotification.Name.UIApplicationWillResignActive, object: nil
)
NotificationCenter.default.addObserver(
self, selector: #selector(BRHTTPServer.suspend(_:)),
name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil)
// foregrounding
NotificationCenter.default.addObserver(
self, selector: #selector(BRHTTPServer.resume(_:)),
name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil)
NotificationCenter.default.addObserver(
self, selector: #selector(BRHTTPServer.resume(_:)),
name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil
)
return
} catch {
continue
}
}
throw BRHTTPServerError.socketBindFailed
}
func listenServer(_ port: in_port_t, maxPendingConnections: Int32 = SOMAXCONN) throws {
shutdownServer()
let sfd = socket(AF_INET, SOCK_STREAM, 0)
if sfd == -1 {
throw BRHTTPServerError.socketCreationFailed
}
var v: Int32 = 1
if setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &v, socklen_t(MemoryLayout<Int32>.size)) == -1 {
_ = Darwin.shutdown(sfd, SHUT_RDWR)
close(sfd)
throw BRHTTPServerError.socketCreationFailed
}
v = 1
setsockopt(sfd, SOL_SOCKET, SO_NOSIGPIPE, &v, socklen_t(MemoryLayout<Int32>.size))
var addr = sockaddr_in()
addr.sin_len = __uint8_t(MemoryLayout<sockaddr_in>.size)
addr.sin_family = sa_family_t(AF_INET)
addr.sin_port = Int(OSHostByteOrder()) == OSLittleEndian ? _OSSwapInt16(port) : port
addr.sin_addr = in_addr(s_addr: inet_addr(listenAddress))
addr.sin_zero = (0, 0, 0, 0, 0, 0, 0 ,0)
var bind_addr = sockaddr()
memcpy(&bind_addr, &addr, Int(MemoryLayout<sockaddr_in>.size))
if bind(sfd, &bind_addr, socklen_t(MemoryLayout<sockaddr_in>.size)) == -1 {
perror("bind error");
_ = Darwin.shutdown(sfd, SHUT_RDWR)
close(sfd)
throw BRHTTPServerError.socketBindFailed
}
if listen(sfd, maxPendingConnections) == -1 {
perror("listen error");
_ = Darwin.shutdown(sfd, SHUT_RDWR)
close(sfd)
throw BRHTTPServerError.socketListenFailed
}
fd = sfd
acceptClients()
print("[BRHTTPServer] listening on \(port)")
}
func shutdownServer() {
_ = Darwin.shutdown(fd, SHUT_RDWR)
close(fd)
fd = -1
objc_sync_enter(self)
defer { objc_sync_exit(self) }
for cli_fd in self.clients {
_ = Darwin.shutdown(cli_fd, SHUT_RDWR)
}
self.clients.removeAll(keepingCapacity: true)
print("[BRHTTPServer] no longer listening")
}
func stop() {
shutdownServer()
// background
NotificationCenter.default.removeObserver(
self, name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil)
NotificationCenter.default.removeObserver(
self, name: NSNotification.Name.UIApplicationWillResignActive, object: nil)
// foreground
NotificationCenter.default.removeObserver(
self, name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil)
NotificationCenter.default.removeObserver(
self, name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
}
func suspend(_: Notification) {
if isStarted {
shutdownServer()
print("[BRHTTPServer] suspended")
} else {
print("[BRHTTPServer] already suspended")
}
}
func resume(_: Notification) {
if !isStarted {
do {
try listenServer(port)
print("[BRHTTPServer] resumed")
} catch let e {
print("[BRHTTPServer] unable to start \(e)")
}
} else {
print("[BRHTTPServer] already resumed")
}
}
func addClient(_ cli_fd: Int32) {
objc_sync_enter(self)
defer { objc_sync_exit(self) }
clients.insert(cli_fd)
}
func rmClient(_ cli_fd: Int32) {
objc_sync_enter(self)
defer { objc_sync_exit(self) }
clients.remove(cli_fd)
}
fileprivate func acceptClients() {
Q.async { () -> Void in
while true {
var addr = sockaddr(sa_len: 0, sa_family: 0, sa_data: (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))
var len: socklen_t = 0
let cli_fd = accept(self.fd, &addr, &len)
if cli_fd == -1 {
break
}
var v: Int32 = 1
setsockopt(cli_fd, SOL_SOCKET, SO_NOSIGPIPE, &v, socklen_t(MemoryLayout<Int32>.size))
self.addClient(cli_fd)
// print("startup: \(cli_fd)")
self.Q.async { () -> Void in
while let req = try? BRHTTPRequestImpl(readFromFd: cli_fd, queue: self.Q) {
self.dispatch(middleware: self.middleware, req: req) { resp in
_ = Darwin.shutdown(cli_fd, SHUT_RDWR)
// print("shutdown: \(cli_fd)")
close(cli_fd)
self.rmClient(cli_fd)
}
if !req.isKeepAlive { break }
}
}
}
// self.shutdownServer()
}
}
fileprivate func dispatch(middleware mw: [BRHTTPMiddleware], req: BRHTTPRequest, finish: @escaping (BRHTTPResponse) -> Void) {
var newMw = mw
if let curMw = newMw.popLast() {
curMw.handle(req, next: { (mwResp) -> Void in
// print("[BRHTTPServer] trying \(req.path) \(curMw)")
if let httpResp = mwResp.response {
httpResp.done {
do {
try httpResp.send()
self.logline(req, response: httpResp)
} catch let e {
print("[BRHTTPServer] error sending response. request: \(req) error: \(e)")
}
finish(httpResp)
}
} else {
self.dispatch(middleware: newMw, req: mwResp.request, finish: finish)
}
})
} else {
let resp = BRHTTPResponse(
request: req, statusCode: 404, statusReason: "Not Found", headers: nil, body: nil)
logline(req, response: resp)
_ = try? resp.send()
finish(resp)
}
}
fileprivate func logline(_ request: BRHTTPRequest, response: BRHTTPResponse) {
let ms = Double(round((request.start.timeIntervalSinceNow * -1000.0)*1000)/1000)
let b = response.body?.count ?? 0
let c = response.statusCode ?? -1
let s = response.statusReason ?? "Unknown"
print("[BRHTTPServer] \(request.method) \(request.path) -> \(c) \(s) \(b)b in \(ms)ms")
}
}
@objc public protocol BRHTTPRequest {
var fd: Int32 { get }
var queue: DispatchQueue { get }
var method: String { get }
var path: String { get }
var queryString: String { get }
var query: [String: [String]] { get }
var headers: [String: [String]] { get }
var isKeepAlive: Bool { get }
func body() -> Data?
var hasBody: Bool { get }
var contentType: String { get }
var contentLength: Int { get }
var start: Date { get }
@objc optional func json() -> AnyObject?
}
@objc open class BRHTTPRequestImpl: NSObject, BRHTTPRequest {
open var fd: Int32
open var queue: DispatchQueue
open var method = "GET"
open var path = "/"
open var queryString = ""
open var query = [String: [String]]()
open var headers = [String: [String]]()
open var start = Date()
open var isKeepAlive: Bool {
return (headers["connection"] != nil
&& headers["connection"]?.count ?? 0 > 0
&& headers["connection"]![0] == "keep-alive")
}
static let rangeRe = try! NSRegularExpression(pattern: "bytes=(\\d*)-(\\d*)", options: .caseInsensitive)
public required init(fromRequest r: BRHTTPRequest) {
fd = r.fd
queue = r.queue
method = r.method
path = r.path
queryString = r.queryString
query = r.query
headers = r.headers
if let ri = r as? BRHTTPRequestImpl {
_bodyRead = ri._bodyRead
_body = ri._body
}
}
public required init(readFromFd: Int32, queue: DispatchQueue) throws {
fd = readFromFd
self.queue = queue
super.init()
let status = try readLine()
let statusParts = status.components(separatedBy: " ")
if statusParts.count < 3 {
throw BRHTTPServerError.invalidHttpRequest
}
method = statusParts[0]
path = statusParts[1]
// parse query string
if path.range(of: "?") != nil {
let parts = path.components(separatedBy: "?")
path = parts[0]
queryString = parts[1..<parts.count].joined(separator: "?")
let pairs = queryString.components(separatedBy: "&")
for pair in pairs {
let pairSides = pair.components(separatedBy: "=")
if pairSides.count == 2 {
if query[pairSides[0]] != nil {
query[pairSides[0]]?.append(pairSides[1])
} else {
query[pairSides[0]] = [pairSides[1]]
}
}
}
}
// parse headers
while true {
let hdr = try readLine()
if hdr.isEmpty { break }
let hdrParts = hdr.components(separatedBy: ":")
if hdrParts.count >= 2 {
let name = hdrParts[0].lowercased()
let hdrVal = hdrParts[1..<hdrParts.count].joined(separator: ":").trimmingCharacters(
in: CharacterSet.whitespaces)
if headers[name] != nil {
headers[name]?.append(hdrVal)
} else {
headers[name] = [hdrVal]
}
}
}
}
func readLine() throws -> String {
var chars: String = ""
var n = 0
repeat {
n = self.read()
if (n > 13 /* CR */) { chars.append(Character(UnicodeScalar(n)!)) }
} while n > 0 && n != 10 /* NL */
if n == -1 {
throw BRHTTPServerError.socketRecvFailed
}
return chars
}
func read() -> Int {
var buf = [UInt8](repeating: 0, count: 1)
let n = recv(fd, &buf, 1, 0)
if n <= 0 {
return n
}
return Int(buf[0])
}
open var hasBody: Bool {
return method == "POST" || method == "PATCH" || method == "PUT"
}
open var contentLength: Int {
if let hdrs = headers["content-length"] , hasBody && hdrs.count > 0 {
if let i = Int(hdrs[0]) {
return i
}
}
return 0
}
open var contentType: String {
if let hdrs = headers["content-type"] , hdrs.count > 0 { return hdrs[0] }
return "application/octet-stream"
}
fileprivate var _body: [UInt8]?
fileprivate var _bodyRead: Bool = false
open func body() -> Data? {
if _bodyRead && _body != nil {
let bp = UnsafeMutablePointer<UInt8>(UnsafeMutablePointer(mutating: _body!))
return Data(bytesNoCopy: bp, count: contentLength, deallocator: .none)
}
if _bodyRead {
return nil
}
var buf = [UInt8](repeating: 0, count: contentLength)
let n = recv(fd, &buf, contentLength, 0)
if n <= 0 {
_bodyRead = true
return nil
}
_body = buf
let bp = UnsafeMutablePointer<UInt8>(UnsafeMutablePointer(mutating: _body!))
return Data(bytesNoCopy: bp, count: contentLength, deallocator: .none)
}
open func json() -> AnyObject? {
if let b = body() {
return try! JSONSerialization.jsonObject(with: b, options: []) as AnyObject?
}
return nil
}
func rangeHeader() throws -> (Int, Int)? {
if headers["range"] == nil {
return nil
}
guard let rngHeader = headers["range"]?[0],
let match = BRHTTPRequestImpl.rangeRe.matches(in: rngHeader, options: .anchored, range:
NSRange(location: 0, length: rngHeader.characters.count)).first
, match.numberOfRanges == 3 else {
throw BRHTTPServerError.invalidRangeHeader
}
let startStr = (rngHeader as NSString).substring(with: match.rangeAt(1))
let endStr = (rngHeader as NSString).substring(with: match.rangeAt(2))
guard let start = Int(startStr), let end = Int(endStr) else {
throw BRHTTPServerError.invalidRangeHeader
}
return (start, end)
}
}
@objc open class BRHTTPResponse: NSObject {
var request: BRHTTPRequest
var statusCode: Int?
var statusReason: String?
var headers: [String: [String]]?
var body: [UInt8]?
var async = false
var onDone: (() -> Void)?
var isDone = false
var isKilled = false
static var reasonMap: [Int: String] = [
100: "Continue",
101: "Switching Protocols",
200: "OK",
201: "Created",
202: "Accepted",
203: "Non-Authoritative Information",
204: "No Content",
205: "Reset Content",
206: "Partial Content",
207: "Multi Status",
208: "Already Reported",
226: "IM Used",
300: "Multiple Choices",
301: "Moved Permanently",
302: "Found",
303: "See Other",
304: "Not Modified",
305: "Use Proxy",
306: "Switch Proxy", // unused in spec
307: "Temporary Redirect",
308: "Permanent Redirect",
400: "Bad Request",
401: "Unauthorized",
402: "Payment Required",
403: "Forbidden",
404: "Not Found",
405: "Method Not Allowed",
406: "Not Acceptable",
407: "Proxy Authentication Required",
408: "Request Timeout",
409: "Conflict",
410: "Gone",
411: "Length Required",
412: "Precondition Failed",
413: "Request Entity Too Large",
414: "Request-URI Too Long",
415: "Unsupported Media Type",
416: "Request Range Not Satisfiable",
417: "Expectation Failed",
418: "I'm a teapot",
421: "Misdirected Request",
422: "Unprocessable Entity",
423: "Locked",
424: "Failed Dependency",
426: "Upgrade Required",
428: "Precondition Required",
429: "Too Many Requests",
431: "Request Header Fields Too Large",
451: "Unavailable For Leagal Reasons",
500: "Internal Server Error",
501: "Not Implemented",
502: "Bad Gateway",
503: "Service Unavailable",
504: "Gateway Timeout",
505: "HTTP Version Not Supported",
506: "Variant Also Negotiates",
507: "Insufficient Storage",
508: "Loop Detected",
510: "Not Extended",
511: "Network Authentication Required",
]
init(request: BRHTTPRequest, statusCode: Int?, statusReason: String?, headers: [String: [String]]?, body: [UInt8]?) {
self.request = request
self.statusCode = statusCode
self.statusReason = statusReason
self.headers = headers
self.body = body
self.isDone = true
super.init()
}
init(async request: BRHTTPRequest) {
self.request = request
self.async = true
}
convenience init(request: BRHTTPRequest, code: Int) {
self.init(
request: request, statusCode: code, statusReason: BRHTTPResponse.reasonMap[code], headers: nil, body: nil)
}
convenience init(request: BRHTTPRequest, code: Int, json j: Any) throws {
let jsonData = try JSONSerialization.data(withJSONObject: j, options: [])
let bp = (jsonData as NSData).bytes.bindMemory(to: UInt8.self, capacity: jsonData.count)
let bodyBuffer = UnsafeBufferPointer<UInt8>(start: bp, count: jsonData.count)
self.init(
request: request, statusCode: code, statusReason: BRHTTPResponse.reasonMap[code],
headers: ["Content-Type": ["application/json"]], body: Array(bodyBuffer))
}
func send() throws {
if isKilled {
return // do nothing... the connection should just be closed
}
let status = statusCode ?? 200
let reason = statusReason ?? "OK"
try writeUTF8("HTTP/1.1 \(status) \(reason)\r\n")
let length = body?.count ?? 0
try writeUTF8("Content-Length: \(length)\r\n")
if request.isKeepAlive {
try writeUTF8("Connection: keep-alive\r\n")
}
let hdrs = headers ?? [String: [String]]()
for (n, v) in hdrs {
for yv in v {
try writeUTF8("\(n): \(yv)\r\n")
}
}
try writeUTF8("\r\n")
if let b = body {
try writeUInt8(b)
}
}
func writeUTF8(_ s: String) throws {
try writeUInt8([UInt8](s.utf8))
}
func writeUInt8(_ data: [UInt8]) throws {
try data.withUnsafeBufferPointer { pointer in
var sent = 0
while sent < data.count {
let s = write(request.fd, pointer.baseAddress! + sent, Int(data.count - sent))
if s <= 0 {
throw BRHTTPServerError.socketWriteFailed
}
sent += s
}
}
}
func provide(_ status: Int) {
objc_sync_enter(self)
if isDone {
print("ERROR: can not call provide() on async HTTP response more than once!")
return
}
isDone = true
objc_sync_exit(self)
statusCode = status
statusReason = BRHTTPResponse.reasonMap[status]
objc_sync_enter(self)
isDone = true
if self.onDone != nil {
self.onDone!()
}
objc_sync_exit(self)
}
func provide(_ status: Int, json: Any?) {
objc_sync_enter(self)
if isDone {
print("ERROR: can not call provide() on async HTTP response more than once!")
return
}
isDone = true
objc_sync_exit(self)
do {
if let json = json {
let jsonData = try JSONSerialization.data(withJSONObject: json, options: [])
let bp = (jsonData as NSData).bytes.bindMemory(to: UInt8.self, capacity: jsonData.count)
let bodyBuffer = UnsafeBufferPointer<UInt8>(start: bp, count: jsonData.count)
headers = ["Content-Type": ["application/json"]]
body = Array(bodyBuffer)
}
statusCode = status
statusReason = BRHTTPResponse.reasonMap[status]
} catch let e {
print("Async http response provider threw exception \(e)")
statusCode = 500
statusReason = BRHTTPResponse.reasonMap[500]
}
objc_sync_enter(self)
isDone = true
if self.onDone != nil {
self.onDone!()
}
objc_sync_exit(self)
}
func provide(_ status: Int, data: [UInt8], contentType: String) {
objc_sync_enter(self)
if isDone {
print("ERROR: can not call provide() on async HTTP response more than once!")
return
}
isDone = true
objc_sync_exit(self)
headers = ["Content-Type": [contentType]]
body = data
statusCode = status
statusReason = BRHTTPResponse.reasonMap[status]
objc_sync_enter(self)
isDone = true
if self.onDone != nil {
self.onDone!()
}
objc_sync_exit(self)
}
func kill() {
objc_sync_enter(self)
if isDone {
print("ERROR: can not call kill() on async HTTP response more than once!")
return
}
isDone = true
isKilled = true
if self.onDone != nil {
self.onDone!()
}
objc_sync_exit(self)
}
func done(_ onDone: @escaping () -> Void) {
objc_sync_enter(self)
self.onDone = onDone
if self.isDone {
self.onDone!()
}
objc_sync_exit(self)
}
}
|
mit
|
40369fd79a16c958acbdf0cb3c342df4
| 33.512057 | 130 | 0.544696 | 4.439153 | false | false | false | false |
DDSSwiftTech/SwiftMine
|
Sources/SwiftMineCore/src/Network/Packets/AdventureSettingsPacket.swift
|
1
|
1983
|
//
// AdventureSettingsPacket.swift
// SwiftMine
//
// Created by David Schwartz on 2/2/17.
//
//
import Foundation
final class AdventureSettingsPacket: MCPacket {
private enum Permission: UInt32 {
case NORMAL = 0
case OPERATOR = 1
case HOST = 2
case AUTOMATION = 3
case ADMIN = 4
}
private enum FlagMask: UInt32 {
case WORLD_IMMUTABLE = 0x00000001
case NO_PVP = 0x00000002
case NO_PVM = 0x00000004
case NO_MVP = 0x00000008
case UNKNOWN = 0x00000010
case AUTO_JUMP = 0x00000020
case ALLOW_FLIGHT = 0x00000040
case NO_CLIP = 0x00000080
case WORLD_BUILDER = 0x00000100
case IS_FLYING = 0x00000200
case MUTED = 0x00000400
}
init(worldImmutable: Bool,
noPVP: Bool,
noPVM: Bool,
noMVP: Bool,
autoJump: Bool,
allowFlight: Bool,
noClip: Bool,
isFlying: Bool) {
var flags = UInt32()
flags |= worldImmutable ? FlagMask.WORLD_IMMUTABLE.rawValue : 0
flags |= noPVP ? FlagMask.NO_PVP.rawValue : 0
flags |= noPVM ? FlagMask.NO_PVM.rawValue : 0
flags |= noMVP ? FlagMask.NO_MVP.rawValue : 0
flags |= autoJump ? FlagMask.AUTO_JUMP.rawValue : 0
flags |= allowFlight ? FlagMask.ALLOW_FLIGHT.rawValue : 0
flags |= noClip ? FlagMask.NO_CLIP.rawValue : 0
flags |= isFlying ? FlagMask.IS_FLYING.rawValue : 0
var _buffer = Data()
_buffer.push(varUInt: flags)
_buffer.push(varUInt: Permission.NORMAL.rawValue)
_buffer.push(varUInt: UInt32.max) // flags2
_buffer.push(varUInt: 1)
_buffer.push(varUInt: 0)
_buffer.push(value: 1 as UInt64)
super.init(packetType: .ADVENTURE_SETTINGS_PACKET, buffer: _buffer)
}
}
|
apache-2.0
|
2c72c421b5158631ba6c80ba4925a516
| 29.045455 | 75 | 0.557741 | 3.665434 | false | false | false | false |
viviancrs/fanboy
|
FanBoy/Source/Business/Item/ItemBusiness.swift
|
1
|
4990
|
//
// ItemBusiness.swift
// FanBoy
//
// Created by Vivian Cristhine da Rosa Soares on 16/07/17.
// Copyright © 2017 CI&T. All rights reserved.
//
import Foundation
struct ItemBusiness {
//MARK: - Constants
private let kName = "name"
private let kTitle = "title"
private let kNext = "next"
private let kResults = "results"
var provider: ItemServiceSessionProtocol = ItemServiceSession()
/**
Get list of Item objects
- parameter url: pagined or not
- parameter completion: person list or an error
*/
func getItemFromUrl(_ url: String, completion: @escaping ItemResultCallback) {
provider.getItemFromUrl(url, completion: { (result) in
do {
guard let itemResult = try result() else { return }
guard let propertiesArray = itemResult[self.kResults] as? [Dictionary<String, AnyObject>] else { throw BusinessError.parse(self.kResults) }
var items = [Item]()
for properties in propertiesArray {
do {
let item = try Item(itemDictionary: properties)
items.append(item)
} catch let error {
completion { throw error }
}
}
completion { items }
if let next = itemResult[self.kNext] as? String {
self.getItemFromUrl(next, completion: completion)
}
} catch let error {
completion { throw error }
}
})
}
/**
Fill name in sub linked details from item
- parameter detail: detail
- parameter completion: name or an error
*/
func loadLinkedSubDetail(_ detail: Detail, completion: @escaping LinkedSubDetailResultCallback) {
switch detail.type {
case .subdetail:
var subdetails = detail.subdetails
for i in 0 ..< subdetails.count {
var subdetail = subdetails[i]
if subdetail.name.isEmpty {
loadNameFromLinkedDetail(subdetail.url, completion: { (result) in
do {
guard let nameResult = try result() else { return }
subdetail.name = nameResult
subdetails.remove(at: i)
subdetails.insert(subdetail, at: i)
completion { subdetails }
} catch let error {
completion { throw error }
}
})
}
}
break
default:
break
}
}
/**
Fill name in linked details from item
- parameter item: item
- parameter completion: name or an error
*/
func loadLinkedDetail(_ item: Item, completion: @escaping LinkedDetailResultCallback) {
var details = item.details
for i in 0 ..< details.count {
var detail = details[i]
switch detail.type {
case .linked:
if detail.value.isEmpty {
loadNameFromLinkedDetail(detail.url, completion: { (result) in
do {
guard let valueResult = try result() else { return }
detail.value = valueResult
details.remove(at: i)
details.insert(detail, at: i)
completion { details }
} catch let error {
completion { throw error }
}
})
}
break
default:
break
}
}
}
/**
Fill name from linked detail
- parameter url: url from detail
- parameter completion: name or an error
*/
fileprivate func loadNameFromLinkedDetail(_ url: String, completion: @escaping DetailResultCallback) {
provider.loadLinkedDetail(url, completion: { (result) in
do {
guard let detailResult = try result() else { return }
if detailResult.keys.contains(self.kName) {
guard let propertie = detailResult[self.kName] as? String else { throw BusinessError.parse(self.kName) }
completion { propertie }
} else {
guard let propertie = detailResult[self.kTitle] as? String else { throw BusinessError.parse(self.kTitle) }
completion { propertie }
}
} catch let error {
completion { throw error }
}
})
}
}
|
gpl-3.0
|
60401739340deca88307407faa50c768
| 34.635714 | 155 | 0.482862 | 5.422826 | false | false | false | false |
eKasztany/4ania
|
ios/Queue/Queue/ViewControllers/DialogViewController.swift
|
1
|
667
|
//
// Created by Aleksander Grzyb on 25/09/16.
// Copyright © 2016 Aleksander Grzyb. All rights reserved.
//
import UIKit
class DialogViewController: UIViewController {
@IBOutlet weak var numberLabel: UILabel!
@IBOutlet weak var ticketLabel: UILabel!
var ticketNumber: Int?
var number: Int?
override func viewDidLoad() {
super.viewDidLoad()
guard let ticketNumber = ticketNumber else { return }
ticketLabel.text = "\(ticketNumber)"
number = 1
}
@IBAction func stepperTapped(_ sender: UIStepper) {
numberLabel.text = "\(Int(sender.value + 1))"
number = Int(sender.value + 1)
}
}
|
apache-2.0
|
c5abdf51f028d5c5629c20f08f833bdd
| 23.666667 | 61 | 0.647147 | 4.242038 | false | false | false | false |
TouchInstinct/LeadKit
|
Sources/Classes/Views/DefaultPlaceholders/TextPlaceholderView.swift
|
1
|
1974
|
//
// Copyright (c) 2018 Touch Instinct
//
// 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
internal final class TextPlaceholderView: UIView {
enum PlaceholderText: String {
case empty = "There is nothing here"
case error = "An error has occurred"
case loading = "Loading..."
case retry = "Retry"
case retryLoadMore = "Retry load more"
}
init(title: PlaceholderText) {
super.init(frame: .zero)
let label = UILabel()
label.text = title.rawValue
label.translatesAutoresizingMaskIntoConstraints = false
addSubview(label)
NSLayoutConstraint.activate([
label.centerXAnchor.constraint(equalTo: centerXAnchor),
label.centerYAnchor.constraint(equalTo: centerYAnchor)
])
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
apache-2.0
|
a09c207e4559c23fb0e6873dc8f10b92
| 35.555556 | 81 | 0.702634 | 4.65566 | false | false | false | false |
Ryan-Vanderhoef/Antlers
|
AppIdea/Frameworks/Bond/Bond/Bond+UICollectionView.swift
|
1
|
7015
|
//
// Bond+UICollectionView.swift
// Bond
//
// Created by Srđan Rašić on 06/03/15.
// Copyright (c) 2015 Bond. All rights reserved.
//
import UIKit
@objc class CollectionViewDynamicArrayDataSource: NSObject, UICollectionViewDataSource {
weak var dynamic: DynamicArray<DynamicArray<UICollectionViewCell>>?
@objc weak var nextDataSource: UICollectionViewDataSource?
init(dynamic: DynamicArray<DynamicArray<UICollectionViewCell>>) {
self.dynamic = dynamic
super.init()
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return self.dynamic?.count ?? 0
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.dynamic?[section].count ?? 0
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
return self.dynamic?[indexPath.section][indexPath.item] ?? UICollectionViewCell()
}
// Forwards
func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
if let result = self.nextDataSource?.collectionView?(collectionView, viewForSupplementaryElementOfKind: kind, atIndexPath: indexPath) {
return result
} else {
fatalError("Defining Supplementary view either in Storyboard or by registering a class or nib file requires you to implement method collectionView:viewForSupplementaryElementOfKind:indexPath in your data soruce! To provide data source, make a class (usually your view controller) adhere to protocol UICollectionViewDataSource and implement method collectionView:viewForSupplementaryElementOfKind:indexPath. Register instance of your class as next data source with UICollectionViewDataSourceBond object by setting its nextDataSource property. Make sure you set it before binding takes place!")
}
}
}
private class UICollectionViewDataSourceSectionBond<T>: ArrayBond<UICollectionViewCell> {
weak var collectionView: UICollectionView?
var section: Int
init(collectionView: UICollectionView?, section: Int) {
self.collectionView = collectionView
self.section = section
super.init()
self.didInsertListener = { [unowned self] a, i in
if let collectionView: UICollectionView = self.collectionView {
collectionView.performBatchUpdates({
collectionView.insertItemsAtIndexPaths(i.map { NSIndexPath(forItem: $0, inSection: self.section) })
}, completion: nil)
}
}
self.didRemoveListener = { [unowned self] a, i in
if let collectionView = self.collectionView {
collectionView.performBatchUpdates({
collectionView.deleteItemsAtIndexPaths(i.map { NSIndexPath(forItem: $0, inSection: self.section) })
}, completion: nil)
}
}
self.didUpdateListener = { [unowned self] a, i in
if let collectionView = self.collectionView {
collectionView.performBatchUpdates({
collectionView.reloadItemsAtIndexPaths(i.map { NSIndexPath(forItem: $0, inSection: self.section) })
}, completion: nil)
}
}
}
deinit {
self.unbindAll()
}
}
public class UICollectionViewDataSourceBond<T>: ArrayBond<DynamicArray<UICollectionViewCell>> {
weak var collectionView: UICollectionView?
private var dataSource: CollectionViewDynamicArrayDataSource?
private var sectionBonds: [UICollectionViewDataSourceSectionBond<Void>] = []
public weak var nextDataSource: UICollectionViewDataSource? {
didSet(newValue) {
dataSource?.nextDataSource = newValue
}
}
public init(collectionView: UICollectionView) {
self.collectionView = collectionView
super.init()
self.didInsertListener = { [weak self] array, i in
if let s = self {
if let collectionView: UICollectionView = self?.collectionView {
collectionView.performBatchUpdates({
collectionView.insertSections(NSIndexSet(array: i))
}, completion: nil)
for section in sorted(i, <) {
let sectionBond = UICollectionViewDataSourceSectionBond<Void>(collectionView: collectionView, section: section)
let sectionDynamic = array[section]
sectionDynamic.bindTo(sectionBond)
s.sectionBonds.insert(sectionBond, atIndex: section)
for var idx = section + 1; idx < s.sectionBonds.count; idx++ {
s.sectionBonds[idx].section += 1
}
}
}
}
}
self.didRemoveListener = { [weak self] array, i in
if let s = self {
if let collectionView = s.collectionView {
collectionView.performBatchUpdates({
collectionView.deleteSections(NSIndexSet(array: i))
}, completion: nil)
for section in sorted(i, >) {
s.sectionBonds[section].unbindAll()
s.sectionBonds.removeAtIndex(section)
for var idx = section; idx < s.sectionBonds.count; idx++ {
s.sectionBonds[idx].section -= 1
}
}
}
}
}
self.didUpdateListener = { [weak self] array, i in
if let collectionView = self?.collectionView {
collectionView.performBatchUpdates({
collectionView.reloadSections(NSIndexSet(array: i))
}, completion: nil)
for section in i {
let sectionBond = UICollectionViewDataSourceSectionBond<Void>(collectionView: collectionView, section: section)
let sectionDynamic = array[section]
sectionDynamic.bindTo(sectionBond)
self?.sectionBonds[section].unbindAll()
self?.sectionBonds[section] = sectionBond
}
}
}
}
public func bind(dynamic: DynamicArray<UICollectionViewCell>) {
bind(DynamicArray([dynamic]))
}
public override func bind(dynamic: Dynamic<Array<DynamicArray<UICollectionViewCell>>>, fire: Bool, strongly: Bool) {
super.bind(dynamic, fire: false, strongly: strongly)
if let dynamic = dynamic as? DynamicArray<DynamicArray<UICollectionViewCell>> {
for section in 0..<dynamic.count {
let sectionBond = UICollectionViewDataSourceSectionBond<Void>(collectionView: self.collectionView, section: section)
let sectionDynamic = dynamic[section]
sectionDynamic.bindTo(sectionBond)
sectionBonds.append(sectionBond)
}
dataSource = CollectionViewDynamicArrayDataSource(dynamic: dynamic)
dataSource?.nextDataSource = self.nextDataSource
collectionView?.dataSource = dataSource
collectionView?.reloadData()
}
}
deinit {
self.unbindAll()
collectionView?.dataSource = nil
self.dataSource = nil
}
}
public func ->> <T>(left: DynamicArray<UICollectionViewCell>, right: UICollectionViewDataSourceBond<T>) {
right.bind(left)
}
|
mit
|
00f108f57f7c967bf284f0982699af8c
| 36.698925 | 598 | 0.688962 | 5.144534 | false | false | false | false |
DonMag/ScratchPad
|
Swift3/scratchy/XC8.playground/Pages/UsingVC.xcplaygroundpage/Contents.swift
|
1
|
4492
|
import UIKit
import PlaygroundSupport
class myPgVC: UIPageViewController, UIPageViewControllerDataSource
{
var arrPageTitle = [String]()
var arrOfControllers = [UIViewController]()
override func viewDidLoad() {
super.viewDidLoad()
arrPageTitle = ["A", "B", "C", "D", "E"];
for i in 0..<arrPageTitle.count {
arrOfControllers.append(getViewControllerAtIndex(i))
}
self.dataSource = self
self.setViewControllers([arrOfControllers[0]] as [UIViewController], direction: UIPageViewControllerNavigationDirection.forward, animated: false, completion: nil)
}
func changeBKG(_ toColor: UIColor) {
for vc in arrOfControllers {
vc.view.backgroundColor = toColor
}
}
func gotoPageByIndex(_ index: Int) {
if index < arrOfControllers.count {
self.setViewControllers([arrOfControllers[index]] as [UIViewController], direction: UIPageViewControllerNavigationDirection.forward, animated: false, completion: nil)
}
}
// MARK:- UIPageViewControllerDataSource Methods
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController?
{
var index: Int = arrOfControllers.index(of: viewController)!
if ((index == 0) || (index == NSNotFound))
{
index = arrOfControllers.count
}
index -= 1
return arrOfControllers[index]
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController?
{
var index: Int = arrOfControllers.index(of: viewController)!
if (index == NSNotFound)
{
return nil;
}
index += 1;
if (index == arrOfControllers.count)
{
index = 0
}
return arrOfControllers[index]
}
// MARK:- Other Methods
func getViewControllerAtIndex(_ index: NSInteger) -> UIViewController
{
let vc = UIViewController()
let r = self.view.bounds // CGRect(x: 20, y: 20, width: 120, height: 200)
print(r)
let v = vc.view
v?.backgroundColor = UIColor.orange
v?.frame = r
let l = UILabel(frame: r.insetBy(dx: 20, dy: 20))
l.backgroundColor = UIColor.lightGray
v?.addSubview(l)
l.text = arrPageTitle[index]
l.textAlignment = .center
return vc
}
}
class MyViewController: UIViewController {
var vccA: myPgVC?
var vccB: myPgVC?
init(frame: CGRect) {
super.init(nibName: nil, bundle: nil)
self.view = UIView(frame: frame)
self.view.backgroundColor = UIColor.white
vccA = myPgVC(transitionStyle: UIPageViewControllerTransitionStyle.scroll, navigationOrientation: UIPageViewControllerNavigationOrientation.horizontal)
self.addChildViewController(vccA!)
let vvA = vccA!.view
vvA?.frame = CGRect(x: 260, y: 20, width: 200, height: 200)
vvA?.isUserInteractionEnabled = false
self.view.addSubview(vvA!)
vccA?.didMove(toParentViewController: self)
vccB?.changeBKG(UIColor.green)
vccB = myPgVC(transitionStyle: UIPageViewControllerTransitionStyle.scroll, navigationOrientation: UIPageViewControllerNavigationOrientation.horizontal)
self.addChildViewController(vccB!)
let vvB = vccB!.view
vvB?.frame = CGRect(x: 260, y: 240, width: 200, height: 200)
self.view.addSubview(vvB!)
vccB?.didMove(toParentViewController: self)
vccB?.changeBKG(UIColor.cyan)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func addPageVCs() {
let vcA = myPgVC(transitionStyle: UIPageViewControllerTransitionStyle.scroll, navigationOrientation: UIPageViewControllerNavigationOrientation.horizontal)
let vA = vcA.view
vA?.frame = CGRect(x: 20, y: 20, width: 200, height: 200)
vA?.isUserInteractionEnabled = false
self.view.addSubview(vA!)
let vcB = myPgVC(transitionStyle: UIPageViewControllerTransitionStyle.scroll, navigationOrientation: UIPageViewControllerNavigationOrientation.horizontal)
let vB = vcB.view
vB?.frame = CGRect(x: 20, y: 240, width: 200, height: 200)
self.view.addSubview(vB!)
vcB.changeBKG(UIColor.blue)
}
}
let rootVC = MyViewController(frame: CGRect(x: 0, y: 0, width: 600, height: 600))
//rootVC.addPageVCs()
PlaygroundPage.current.liveView = rootVC.view
//let container = UIView(frame: CGRect(x: 0, y: 0, width: 600, height: 400))
////
//container.backgroundColor = UIColor.green
//
//
//PlaygroundPage.current.liveView = container
//PlaygroundPage.current.needsIndefiniteExecution = true
|
mit
|
1608cdf9c7ec8f45e2c033802f6122a7
| 23.413043 | 169 | 0.720614 | 3.902693 | false | false | false | false |
netguru/inbbbox-ios
|
Inbbbox/Source Files/ViewModels/StreamSourceViewModel.swift
|
1
|
906
|
//
// StreamSourceViewModel.swift
// Inbbbox
//
// Copyright © 2016 Netguru Sp. z o.o. All rights reserved.
//
struct StreamSourceViewModel {
var isFollowingStreamSelected: Bool {
return Settings.StreamSource.SelectedStreamSource == .following
}
var isNewTodayStreamSelected: Bool {
return Settings.StreamSource.SelectedStreamSource == .newToday
}
var isPopularTodayStreamSelected: Bool {
return Settings.StreamSource.SelectedStreamSource == .popularToday
}
var isDebutsStreamSelected: Bool {
return Settings.StreamSource.SelectedStreamSource == .debuts
}
var isMySetStreamSelected: Bool {
return Settings.StreamSource.SelectedStreamSource == .mySet
}
func didSelectStreamSource(streamSource: ShotsSource) {
Settings.StreamSource.SelectedStreamSource = streamSource
}
}
|
gpl-3.0
|
1324b99f2c2071abccc6e7da1f90244d
| 25.617647 | 74 | 0.692818 | 4.525 | false | false | false | false |
klundberg/swift-corelibs-foundation
|
Foundation/NSXMLNode.swift
|
1
|
30463
|
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//import libxml2
import CoreFoundation
// initWithKind options
// NSXMLNodeOptionsNone
// NSXMLNodePreserveAll
// NSXMLNodePreserveNamespaceOrder
// NSXMLNodePreserveAttributeOrder
// NSXMLNodePreserveEntities
// NSXMLNodePreservePrefixes
// NSXMLNodeIsCDATA
// NSXMLNodeExpandEmptyElement
// NSXMLNodeCompactEmptyElement
// NSXMLNodeUseSingleQuotes
// NSXMLNodeUseDoubleQuotes
// Output options
// NSXMLNodePrettyPrint
/*!
@class NSXMLNode
@abstract The basic unit of an XML document.
*/
public class XMLNode: NSObject, NSCopying {
public enum Kind : UInt {
case invalid
case document
case element
case attribute
case namespace
case processingInstruction
case comment
case text
case dtd
case entityDeclaration
case attributeDeclaration
case elementDeclaration
case notationDeclaration
}
public override func copy() -> AnyObject {
return copy(with: nil)
}
internal let _xmlNode: _CFXMLNodePtr
public func copy(with zone: NSZone? = nil) -> AnyObject {
let newNode = _CFXMLCopyNode(_xmlNode, true)
return XMLNode._objectNodeForNode(newNode)
}
/*!
@method initWithKind:
@abstract Invokes @link initWithKind:options: @/link with options set to NSXMLNodeOptionsNone
*/
public convenience init(kind: Kind) {
self.init(kind: kind, options: NSXMLNodeOptionsNone)
}
/*!
@method initWithKind:options:
@abstract Inits a node with fidelity options as description NSXMLNodeOptions.h
*/
public init(kind: Kind, options: Int) {
switch kind {
case .document:
let docPtr = _CFXMLNewDoc("1.0")
_CFXMLDocSetStandalone(docPtr, false) // same default as on Darwin
_xmlNode = _CFXMLNodePtr(docPtr)
case .element:
_xmlNode = _CFXMLNewNode(nil, "")
case .attribute:
_xmlNode = _CFXMLNodePtr(_CFXMLNewProperty(nil, "", ""))
case .dtd:
_xmlNode = _CFXMLNewDTD(nil, "", "", "")
default:
fatalError("invalid node kind for this initializer")
}
super.init()
withUnretainedReference {
_CFXMLNodeSetPrivateData(_xmlNode, $0)
}
}
/*!
@method document:
@abstract Returns an empty document.
*/
public class func document() -> AnyObject {
return XMLDocument(rootElement: nil)
}
/*!
@method documentWithRootElement:
@abstract Returns a document
@param element The document's root node.
*/
public class func document(withRootElement element: XMLElement) -> AnyObject {
return XMLDocument(rootElement: element)
}
/*!
@method elementWithName:
@abstract Returns an element <tt><name></name></tt>.
*/
public class func elementWithName(_ name: String) -> AnyObject {
return XMLElement(name: name)
}
/*!
@method elementWithName:URI:
@abstract Returns an element whose full QName is specified.
*/
public class func element(withName name: String, uri: String) -> AnyObject {
return XMLElement(name: name, uri: uri)
}
/*!
@method elementWithName:stringValue:
@abstract Returns an element with a single text node child <tt><name>string</name></tt>.
*/
public class func element(withName name: String, stringValue string: String) -> AnyObject {
return XMLElement(name: name, stringValue: string)
}
/*!
@method elementWithName:children:attributes:
@abstract Returns an element children and attributes <tt><name attr1="foo" attr2="bar"><-- child1 -->child2</name></tt>.
*/
public class func element(withName name: String, children: [XMLNode]?, attributes: [XMLNode]?) -> AnyObject {
let element = XMLElement(name: name)
element.setChildren(children)
element.attributes = attributes
return element
}
/*!
@method attributeWithName:stringValue:
@abstract Returns an attribute <tt>name="stringValue"</tt>.
*/
public class func attributeWithName(_ name: String, stringValue: String) -> AnyObject {
let attribute = _CFXMLNewProperty(nil, name, stringValue)
return XMLNode(ptr: attribute)
}
/*!
@method attributeWithLocalName:URI:stringValue:
@abstract Returns an attribute whose full QName is specified.
*/
public class func attribute(withName name: String, uri: String, stringValue: String) -> AnyObject {
let attribute = XMLNode.attributeWithName(name, stringValue: stringValue) as! XMLNode
// attribute.URI = URI
return attribute
}
/*!
@method namespaceWithName:stringValue:
@abstract Returns a namespace <tt>xmlns:name="stringValue"</tt>.
*/
public class func namespace(withName name: String, stringValue: String) -> AnyObject { NSUnimplemented() }
/*!
@method processingInstructionWithName:stringValue:
@abstract Returns a processing instruction <tt><?name stringValue></tt>.
*/
public class func processingInstruction(withName name: String, stringValue: String) -> AnyObject {
let node = _CFXMLNewProcessingInstruction(name, stringValue)
return XMLNode(ptr: node)
}
/*!
@method commentWithStringValue:
@abstract Returns a comment <tt><--stringValue--></tt>.
*/
public class func comment(withStringValue stringValue: String) -> AnyObject {
let node = _CFXMLNewComment(stringValue)
return XMLNode(ptr: node)
}
/*!
@method textWithStringValue:
@abstract Returns a text node.
*/
public class func text(withStringValue stringValue: String) -> AnyObject {
let node = _CFXMLNewTextNode(stringValue)
return XMLNode(ptr: node)
}
/*!
@method DTDNodeWithXMLString:
@abstract Returns an element, attribute, entity, or notation DTD node based on the full XML string.
*/
public class func dtdNode(withXMLString string: String) -> AnyObject? {
guard let node = _CFXMLParseDTDNode(string) else { return nil }
return XMLDTDNode(ptr: node)
}
/*!
@method kind
@abstract Returns an element, attribute, entity, or notation DTD node based on the full XML string.
*/
public var kind: Kind {
switch _CFXMLNodeGetType(_xmlNode) {
case _kCFXMLTypeElement:
return .element
case _kCFXMLTypeAttribute:
return .attribute
case _kCFXMLTypeDocument:
return .document
case _kCFXMLTypeDTD:
return .dtd
case _kCFXMLDTDNodeTypeElement:
return .elementDeclaration
case _kCFXMLDTDNodeTypeEntity:
return .entityDeclaration
case _kCFXMLDTDNodeTypeNotation:
return .notationDeclaration
case _kCFXMLDTDNodeTypeAttribute:
return .attributeDeclaration
default:
return .invalid
}
} //primitive
/*!
@method name
@abstract Sets the nodes name. Applicable for element, attribute, namespace, processing-instruction, document type declaration, element declaration, attribute declaration, entity declaration, and notation declaration.
*/
public var name: String? {
get {
if let ptr = _CFXMLNodeGetName(_xmlNode) {
return String(cString: ptr)
} else {
return nil
}
}
set {
if let newName = newValue {
_CFXMLNodeSetName(_xmlNode, newName)
} else {
_CFXMLNodeSetName(_xmlNode, "")
}
}
}
private var _objectValue: AnyObject? = nil
/*!
@method objectValue
@abstract Sets the content of the node. Setting the objectValue removes all existing children including processing instructions and comments. Setting the object value on an element creates a single text node child.
*/
public var objectValue: AnyObject? {
get {
if let value = _objectValue {
return value
} else {
return stringValue?._bridgeToObject()
}
}
set {
_objectValue = newValue
if let describableValue = newValue as? CustomStringConvertible {
stringValue = "\(describableValue.description)"
} else if let value = newValue {
stringValue = "\(value)"
} else {
stringValue = nil
}
}
}//primitive
/*!
@method stringValue:
@abstract Sets the content of the node. Setting the stringValue removes all existing children including processing instructions and comments. Setting the string value on an element creates a single text node child. The getter returns the string value of the node, which may be either its content or child text nodes, depending on the type of node. Elements are recursed and text nodes concatenated in document order with no intervening spaces.
*/
public var stringValue: String? {
get {
switch kind {
case .entityDeclaration:
return _CFXMLGetEntityContent(_CFXMLEntityPtr(_xmlNode))?._swiftObject
default:
return _CFXMLNodeGetContent(_xmlNode)?._swiftObject
}
}
set {
_removeAllChildNodesExceptAttributes() // in case anyone is holding a reference to any of these children we're about to destroy
if let string = newValue {
let newContent = _CFXMLEncodeEntities(_CFXMLNodeGetDocument(_xmlNode), string)?._swiftObject ?? ""
_CFXMLNodeSetContent(_xmlNode, newContent)
} else {
_CFXMLNodeSetContent(_xmlNode, nil)
}
}
}
private func _removeAllChildNodesExceptAttributes() {
for node in _childNodes {
if node.kind != .attribute {
_CFXMLUnlinkNode(node._xmlNode)
_childNodes.remove(node)
}
}
}
internal func _removeAllChildren() {
var nextChild = _CFXMLNodeGetFirstChild(_xmlNode)
while let child = nextChild {
_CFXMLUnlinkNode(child)
nextChild = _CFXMLNodeGetNextSibling(child)
}
_childNodes.removeAll(keepingCapacity: true)
}
/*!
@method setStringValue:resolvingEntities:
@abstract Sets the content as with @link setStringValue: @/link, but when "resolve" is true, character references, predefined entities and user entities available in the document's dtd are resolved. Entities not available in the dtd remain in their entity form.
*/
public func setStringValue(_ string: String, resolvingEntities resolve: Bool) {
guard resolve else {
stringValue = string
return
}
_removeAllChildNodesExceptAttributes()
var entities: [(Range<Int>, String)] = []
var entityChars: [Character] = []
var inEntity = false
var startIndex = 0
for (index, char) in string.characters.enumerated() {
if char == "&" {
inEntity = true
startIndex = index
continue
}
if char == ";" && inEntity {
inEntity = false
let min = startIndex
let max = index + 1
entities.append((min..<max, String(entityChars)))
startIndex = 0
entityChars.removeAll()
}
if inEntity {
entityChars.append(char)
}
}
var result: [Character] = Array(string.characters)
let doc = _CFXMLNodeGetDocument(_xmlNode)!
for (range, entity) in entities {
var entityPtr = _CFXMLGetDocEntity(doc, entity)
if entityPtr == nil {
entityPtr = _CFXMLGetDTDEntity(doc, entity)
}
if entityPtr == nil {
entityPtr = _CFXMLGetParameterEntity(doc, entity)
}
if let validEntity = entityPtr {
let replacement = _CFXMLGetEntityContent(validEntity)?._swiftObject ?? ""
result.replaceSubrange(range, with: replacement.characters)
} else {
result.replaceSubrange(range, with: []) // This appears to be how Darwin Foundation does it
}
}
stringValue = String(result)
} //primitive
/*!
@method index
@abstract A node's index amongst its siblings.
*/
public var index: Int {
if let siblings = self.parent?.children,
let index = siblings.index(of: self) {
return index
}
return 0
} //primitive
/*!
@method level
@abstract The depth of the node within the tree. Documents and standalone nodes are level 0.
*/
public var level: Int {
var result = 0
var nextParent = _CFXMLNodeGetParent(_xmlNode)
while let parent = nextParent {
result += 1
nextParent = _CFXMLNodeGetParent(parent)
}
return result
}
/*!
@method rootDocument
@abstract The encompassing document or nil.
*/
public var rootDocument: XMLDocument? {
guard let doc = _CFXMLNodeGetDocument(_xmlNode) else { return nil }
return XMLNode._objectNodeForNode(_CFXMLNodePtr(doc)) as? XMLDocument
}
/*!
@method parent
@abstract The parent of this node. Documents and standalone Nodes have a nil parent; there is not a 1-to-1 relationship between parent and children, eg a namespace cannot be a child but has a parent element.
*/
/*@NSCopying*/ public var parent: XMLNode? {
guard let parentPtr = _CFXMLNodeGetParent(_xmlNode) else { return nil }
return XMLNode._objectNodeForNode(parentPtr)
} //primitive
/*!
@method childCount
@abstract The amount of children, relevant for documents, elements, and document type declarations. Use this instead of [[self children] count].
*/
public var childCount: Int {
return _CFXMLNodeGetElementChildCount(_xmlNode)
} //primitive
/*!
@method children
@abstract An immutable array of child nodes. Relevant for documents, elements, and document type declarations.
*/
public var children: [XMLNode]? {
switch kind {
case .document:
fallthrough
case .element:
fallthrough
case .dtd:
return Array<XMLNode>(self as XMLNode)
default:
return nil
}
} //primitive
/*!
@method childAtIndex:
@abstract Returns the child node at a particular index.
*/
public func childAtIndex(_ index: Int) -> XMLNode? {
precondition(index >= 0)
precondition(index < childCount)
return self[self.index(startIndex, offsetBy: index)]
} //primitive
/*!
@method previousSibling:
@abstract Returns the previous sibling, or nil if there isn't one.
*/
/*@NSCopying*/ public var previousSibling: XMLNode? {
guard let prev = _CFXMLNodeGetPrevSibling(_xmlNode) else { return nil }
return XMLNode._objectNodeForNode(prev)
}
/*!
@method nextSibling:
@abstract Returns the next sibling, or nil if there isn't one.
*/
/*@NSCopying*/ public var nextSibling: XMLNode? {
guard let next = _CFXMLNodeGetNextSibling(_xmlNode) else { return nil }
return XMLNode._objectNodeForNode(next)
}
/*!
@method previousNode:
@abstract Returns the previous node in document order. This can be used to walk the tree backwards.
*/
/*@NSCopying*/ public var previousNode: XMLNode? {
if let previousSibling = self.previousSibling {
if let lastChild = _CFXMLNodeGetLastChild(previousSibling._xmlNode) {
return XMLNode._objectNodeForNode(lastChild)
} else {
return previousSibling
}
} else if let parent = self.parent {
return parent
} else {
return nil
}
}
/*!
@method nextNode:
@abstract Returns the next node in document order. This can be used to walk the tree forwards.
*/
/*@NSCopying*/ public var nextNode: XMLNode? {
if let children = _CFXMLNodeGetFirstChild(_xmlNode) {
return XMLNode._objectNodeForNode(children)
} else if let next = nextSibling {
return next
} else if let parent = self.parent {
return parent.nextSibling
} else {
return nil
}
}
/*!
@method detach:
@abstract Detaches this node from its parent.
*/
public func detach() {
guard let parentPtr = _CFXMLNodeGetParent(_xmlNode) else { return }
_CFXMLUnlinkNode(_xmlNode)
guard let parentNodePtr = _CFXMLNodeGetPrivateData(parentPtr) else { return }
let parent: XMLNode = NSObject.unretainedReference(parentNodePtr)
parent._childNodes.remove(self)
} //primitive
/*!
@method XPath
@abstract Returns the XPath to this node, for example foo/bar[2]/baz.
*/
public var XPath: String? {
guard _CFXMLNodeGetDocument(_xmlNode) != nil else { return nil }
var pathComponents: [String?] = []
var parent = _CFXMLNodeGetParent(_xmlNode)
if parent != nil {
let parentObj = XMLNode._objectNodeForNode(parent!)
let siblingsWithSameName = parentObj.filter { $0.name == self.name }
if siblingsWithSameName.count > 1 {
guard let index = siblingsWithSameName.index(of: self) else { return nil }
pathComponents.append("\(self.name ?? "")[\(index + 1)]")
} else {
pathComponents.append(self.name)
}
} else {
return self.name
}
while true {
if let parentNode = _CFXMLNodeGetParent(parent!) {
let grandparent = XMLNode._objectNodeForNode(parentNode)
let possibleParentNodes = grandparent.filter { $0.name == self.parent?.name }
let count = possibleParentNodes.reduce(0) {
return $0.0 + 1
}
if count <= 1 {
pathComponents.append(XMLNode._objectNodeForNode(parent!).name)
} else {
var parentNumber = 1
for possibleParent in possibleParentNodes {
if possibleParent == self.parent {
break
}
parentNumber += 1
}
pathComponents.append("\(self.parent?.name ?? "")[\(parentNumber)]")
}
parent = _CFXMLNodeGetParent(parent!)
} else {
pathComponents.append(XMLNode._objectNodeForNode(parent!).name)
break
}
}
return pathComponents.reversed().flatMap({ return $0 }).joined(separator: "/")
}
/*!
@method localName
@abstract Returns the local name bar if this attribute or element's name is foo:bar
*/
public var localName: String? {
return _CFXMLNodeLocalName(_xmlNode)?._swiftObject
} //primitive
/*!
@method prefix
@abstract Returns the prefix foo if this attribute or element's name if foo:bar
*/
public var prefix: String? {
return _CFXMLNodePrefix(_xmlNode)?._swiftObject
} //primitive
/*!
@method URI
@abstract Set the URI of this element, attribute, or document. For documents it is the URI of document origin. Getter returns the URI of this element, attribute, or document. For documents it is the URI of document origin and is automatically set when using initWithContentsOfURL.
*/
public var URI: String? { //primitive
get {
return _CFXMLNodeURI(_xmlNode)?._swiftObject
}
set {
if let URI = newValue {
_CFXMLNodeSetURI(_xmlNode, URI)
} else {
_CFXMLNodeSetURI(_xmlNode, nil)
}
}
}
/*!
@method localNameForName:
@abstract Returns the local name bar in foo:bar.
*/
public class func localName(forName name: String) -> String {
// return name.withCString {
// var length: Int32 = 0
// let result = xmlSplitQName3(UnsafePointer<xmlChar>($0), &length)
// return String.fromCString(UnsafePointer<CChar>(result)) ?? ""
// }
NSUnimplemented()
}
/*!
@method localNameForName:
@abstract Returns the prefix foo in the name foo:bar.
*/
public class func prefix(forName name: String) -> String? {
// return name.withCString {
// var result: UnsafeMutablePointer<xmlChar> = nil
// let unused = xmlSplitQName2(UnsafePointer<xmlChar>($0), &result)
// defer {
// xmlFree(result)
// xmlFree(UnsafeMutablePointer<xmlChar>(unused))
// }
// return String.fromCString(UnsafePointer<CChar>(result))
// }
NSUnimplemented()
}
/*!
@method predefinedNamespaceForPrefix:
@abstract Returns the namespace belonging to one of the predefined namespaces xml, xs, or xsi
*/
public class func predefinedNamespace(forPrefix name: String) -> XMLNode? { NSUnimplemented() }
/*!
@method description
@abstract Used for debugging. May give more information than XMLString.
*/
public override var description: String {
return xmlString
}
/*!
@method XMLString
@abstract The representation of this node as it would appear in an XML document.
*/
public var xmlString: String {
return xmlString(withOptions: NSXMLNodeOptionsNone)
}
/*!
@method XMLStringWithOptions:
@abstract The representation of this node as it would appear in an XML document, with various output options available.
*/
public func xmlString(withOptions options: Int) -> String {
return _CFXMLStringWithOptions(_xmlNode, UInt32(options))._swiftObject
}
/*!
@method canonicalXMLStringPreservingComments:
@abstract W3 canonical form (http://www.w3.org/TR/xml-c14n). The input option NSXMLNodePreserveWhitespace should be set for true canonical form.
*/
public func canonicalXMLStringPreservingComments(_ comments: Bool) -> String { NSUnimplemented() }
/*!
@method nodesForXPath:error:
@abstract Returns the nodes resulting from applying an XPath to this node using the node as the context item ("."). normalizeAdjacentTextNodesPreservingCDATA:NO should be called if there are adjacent text nodes since they are not allowed under the XPath/XQuery Data Model.
@returns An array whose elements are a kind of NSXMLNode.
*/
public func nodes(forXPath xpath: String) throws -> [XMLNode] {
guard let nodes = _CFXMLNodesForXPath(_xmlNode, xpath) else {
NSUnimplemented()
}
var result: [XMLNode] = []
for i in 0..<CFArrayGetCount(nodes) {
let nodePtr = CFArrayGetValueAtIndex(nodes, i)!
result.append(XMLNode._objectNodeForNode(_CFXMLNodePtr(nodePtr)))
}
return result
}
/*!
@method objectsForXQuery:constants:error:
@abstract Returns the objects resulting from applying an XQuery to this node using the node as the context item ("."). Constants are a name-value dictionary for constants declared "external" in the query. normalizeAdjacentTextNodesPreservingCDATA:NO should be called if there are adjacent text nodes since they are not allowed under the XPath/XQuery Data Model.
@returns An array whose elements are kinds of NSArray, NSData, NSDate, NSNumber, NSString, NSURL, or NSXMLNode.
*/
public func objects(forXQuery xquery: String, constants: [String : AnyObject]?) throws -> [AnyObject] { NSUnimplemented() }
public func objects(forXQuery xquery: String) throws -> [AnyObject] { NSUnimplemented() }
internal var _childNodes: Set<XMLNode> = []
deinit {
for node in _childNodes {
node.detach()
}
switch kind {
case .document:
_CFXMLFreeDocument(_CFXMLDocPtr(_xmlNode))
case .dtd:
_CFXMLFreeDTD(_CFXMLDTDPtr(_xmlNode))
case .attribute:
_CFXMLFreeProperty(_xmlNode)
default:
_CFXMLFreeNode(_xmlNode)
}
}
internal init(ptr: _CFXMLNodePtr) {
precondition(_CFXMLNodeGetPrivateData(ptr) == nil, "Only one XMLNode per xmlNodePtr allowed")
_xmlNode = ptr
super.init()
if let parent = _CFXMLNodeGetParent(_xmlNode) {
let parentNode = XMLNode._objectNodeForNode(parent)
parentNode._childNodes.insert(self)
}
withUnretainedReference {
_CFXMLNodeSetPrivateData(_xmlNode, $0)
}
}
internal class func _objectNodeForNode(_ node: _CFXMLNodePtr) -> XMLNode {
switch _CFXMLNodeGetType(node) {
case _kCFXMLTypeElement:
return XMLElement._objectNodeForNode(node)
case _kCFXMLTypeDocument:
return XMLDocument._objectNodeForNode(node)
case _kCFXMLTypeDTD:
return XMLDTD._objectNodeForNode(node)
case _kCFXMLDTDNodeTypeEntity:
fallthrough
case _kCFXMLDTDNodeTypeElement:
fallthrough
case _kCFXMLDTDNodeTypeNotation:
fallthrough
case _kCFXMLDTDNodeTypeAttribute:
return XMLDTDNode._objectNodeForNode(node)
default:
if let _private = _CFXMLNodeGetPrivateData(node) {
return XMLNode.unretainedReference(_private)
}
return XMLNode(ptr: node)
}
}
// libxml2 believes any node can have children, though XMLNode disagrees.
// Nevertheless, this belongs here so that NSXMLElement and NSXMLDocument can share
// the same implementation.
internal func _insertChild(_ child: XMLNode, atIndex index: Int) {
precondition(index >= 0)
precondition(index <= childCount)
precondition(child.parent == nil)
_childNodes.insert(child)
if index == 0 {
let first = _CFXMLNodeGetFirstChild(_xmlNode)!
_CFXMLNodeAddPrevSibling(first, child._xmlNode)
} else {
let currChild = childAtIndex(index - 1)!._xmlNode
_CFXMLNodeAddNextSibling(currChild, child._xmlNode)
}
} //primitive
// see above
internal func _insertChildren(_ children: [XMLNode], atIndex index: Int) {
for (childIndex, node) in children.enumerated() {
_insertChild(node, atIndex: index + childIndex)
}
}
/*!
@method removeChildAtIndex:atIndex:
@abstract Removes a child at a particular index.
*/
// See above!
internal func _removeChildAtIndex(_ index: Int) {
guard let child = childAtIndex(index) else {
fatalError("index out of bounds")
}
_childNodes.remove(child)
_CFXMLUnlinkNode(child._xmlNode)
} //primitive
// see above
internal func _setChildren(_ children: [XMLNode]?) {
_removeAllChildren()
guard let children = children else {
return
}
for child in children {
_addChild(child)
}
} //primitive
/*!
@method addChild:
@abstract Adds a child to the end of the existing children.
*/
// see above
internal func _addChild(_ child: XMLNode) {
precondition(child.parent == nil)
_CFXMLNodeAddChild(_xmlNode, child._xmlNode)
_childNodes.insert(child)
}
/*!
@method replaceChildAtIndex:withNode:
@abstract Replaces a child at a particular index with another child.
*/
// see above
internal func _replaceChildAtIndex(_ index: Int, withNode node: XMLNode) {
let child = childAtIndex(index)!
_childNodes.remove(child)
_CFXMLNodeReplaceNode(child._xmlNode, node._xmlNode)
_childNodes.insert(node)
}
}
internal protocol _NSXMLNodeCollectionType: Collection { }
extension XMLNode: _NSXMLNodeCollectionType {
public struct Index: Comparable {
private let node: _CFXMLNodePtr?
private let offset: Int?
}
public subscript(index: Index) -> XMLNode {
return XMLNode._objectNodeForNode(index.node!)
}
public var startIndex: Index {
let node = _CFXMLNodeGetFirstChild(_xmlNode)
return Index(node: node, offset: node.map { _ in 0 })
}
public var endIndex: Index {
return Index(node: nil, offset: nil)
}
public func index(after i: Index) -> Index {
precondition(i.node != nil, "can't increment endIndex")
let nextNode = _CFXMLNodeGetNextSibling(i.node!)
return Index(node: nextNode, offset: nextNode.map { _ in i.offset! + 1 } )
}
}
public func ==(lhs: XMLNode.Index, rhs: XMLNode.Index) -> Bool {
return lhs.offset == rhs.offset
}
public func <(lhs: XMLNode.Index, rhs: XMLNode.Index) -> Bool {
switch (lhs.offset, rhs.offset) {
case (nil, nil):
return false
case (nil, _):
return false
case (_, nil):
return true
case (let lhsOffset, let rhsOffset):
return lhsOffset < rhsOffset
}
}
|
apache-2.0
|
1a082a5a447291624152da2aa9a9387e
| 31.932973 | 451 | 0.606966 | 4.771026 | false | false | false | false |
KosyanMedia/Aviasales-iOS-SDK
|
AviasalesSDKTemplate/Source/HotelsSource/HotelDetails/Items/Rating/GoodToKnowItem.swift
|
1
|
814
|
class GoodToKnowItem: NamedHotelDetailsItem {
var score: Int = 0
init(name: String, score: Int) {
super.init(name: name)
self.score = score
}
override func cellHeight(tableWidth: CGFloat) -> CGFloat {
return HLHotelDetailsUsefullInfoCell.estimatedHeight(tableWidth, text: name, first: first, last: last)
}
override func cell(tableView: UITableView, indexPath: IndexPath) -> UITableViewCell {
let usefullInfoCell = tableView.dequeueReusableCell(withIdentifier: HLHotelDetailsUsefullInfoCell.hl_reuseIdentifier(), for: indexPath) as! HLHotelDetailsUsefullInfoCell
usefullInfoCell.labelText = name
usefullInfoCell.score = score
usefullInfoCell.first = first
usefullInfoCell.last = last
return usefullInfoCell
}
}
|
mit
|
e9b6d23d2f54cd028fbb459488811e67
| 36 | 177 | 0.708845 | 4.497238 | false | false | false | false |
iCrany/iOSExample
|
iOSExample/Module/CoreTextExample/View/ICBenchMarkCell.swift
|
1
|
2085
|
//
// ICBenchMarkCell.swift
// iOSExample
//
// Created by iCrany on 2018/10/11.
// Copyright © 2018 iCrany. All rights reserved.
//
import Foundation
class ICBenchMarkCell: UITableViewCell {
struct Constant {
static let kFont: UIFont = UIFont.systemFont(ofSize: 10)
static let kContentInsets: UIEdgeInsets = UIEdgeInsets(top: 10, left: 0, bottom: 10, right: 0)
}
private var icLabel: ICLabel = {
let v = ICLabel()
v.font = Constant.kFont
v.lineSpacing = 10
v.backgroundColor = UIColor.lightGray
return v
}()
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.setupUI()
}
private func setupUI() {
self.contentView.addSubview(self.icLabel)
self.icLabel.snp.makeConstraints { (maker) in
maker.top.equalToSuperview().offset(Constant.kContentInsets.top)
maker.bottom.equalToSuperview().offset(-Constant.kContentInsets.bottom)
maker.left.equalToSuperview().offset(Constant.kContentInsets.left)
maker.right.equalToSuperview().offset(-Constant.kContentInsets.right)
}
}
func update(str: String) {
let attrStr = NSMutableAttributedString(string: str)
attrStr.ic_setFont(Constant.kFont)
self.icLabel.attributedString = attrStr
}
class func getCellSize(str: String) -> CGSize {
let attrStr = NSMutableAttributedString(string: str)
attrStr.ic_setFont(Constant.kFont)
let icLabel: ICLabel = ICLabel()
icLabel.attributedString = attrStr
let size = icLabel.sizeThatFits(CGSize(width: kScreenWidth, height: CGFloat.greatestFiniteMagnitude))
return CGSize(width: Constant.kContentInsets.left + size.width + Constant.kContentInsets.right, height: Constant.kContentInsets.top + size.height + Constant.kContentInsets.bottom)
}
}
|
mit
|
22954f4909cbbe79f12ad4586d571b9c
| 33.733333 | 187 | 0.676583 | 4.452991 | false | false | false | false |
RevenueCat/purchases-ios
|
Tests/UnitTests/Networking/BaseErrorTests.swift
|
1
|
1800
|
//
// Copyright RevenueCat Inc. All Rights Reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/MIT
//
// BaseErrorTests.swift
//
// Created by Nacho Soto on 4/7/22.
// swiftlint:disable multiline_parameters
import Nimble
@testable import RevenueCat
import XCTest
class BaseErrorTests: TestCase {
/// Compares the result of calling `asPurchasesError` on a `PurchasesErrorConvertible`
/// against the expected `ErrorCode`.
final func verifyPurchasesError(
_ error: PurchasesErrorConvertible,
expectedCode: ErrorCode,
underlyingError: Error? = nil,
userInfoKeys: [NSError.UserInfoKey]? = nil,
file: FileString = #file, line: UInt = #line
) {
let nsError = error.asPurchasesError as NSError
expect(
file: file, line: line,
nsError.domain
) == RCPurchasesErrorCodeDomain
expect(
file: file, line: line,
nsError.code
) == expectedCode.rawValue
if let underlyingError = underlyingError {
expect(
file: file, line: line,
nsError.userInfo[NSUnderlyingErrorKey] as? NSError
).to(matchError(underlyingError),
description: "Invalid underlying error")
} else {
expect(
file: file, line: line,
nsError.userInfo[NSUnderlyingErrorKey]
).to(beNil(), description: "Expected no underlying error")
}
if let userInfoKeys = userInfoKeys {
expect(nsError.userInfo.keys).to(contain(userInfoKeys as [String]))
}
}
}
|
mit
|
169629e40e7a50b13bd351a1212db776
| 29 | 90 | 0.613889 | 4.736842 | false | true | false | false |
blockchain/My-Wallet-V3-iOS
|
Modules/FeatureTransaction/Sources/FeatureTransactionUI/Transaction/TransactionFlow/TransactionFlowDescriptor.swift
|
1
|
13217
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Localization
import MoneyKit
import PlatformKit
import ToolKit
enum TransactionFlowDescriptor {
private typealias LocalizedString = LocalizationConstants.Transaction
enum EnterAmountScreen {
private static func formatForHeader(moneyValue: MoneyValue) -> String {
moneyValue.displayString
}
static func headerTitle(state: TransactionState) -> String {
switch state.action {
case .swap:
let prefix = "\(LocalizedString.Swap.swap): "
guard let moneyValue = try? state.moneyValueFromSource().get() else {
return prefix
}
return prefix + formatForHeader(moneyValue: moneyValue)
case .send:
let prefix = "\(LocalizedString.Send.from): "
guard let source = state.source else {
return prefix
}
return prefix + source.label
case .withdraw:
return LocalizedString.Withdraw.availableToWithdrawTitle
case .interestTransfer,
.interestWithdraw:
guard let account = state.source else {
return ""
}
return LocalizedString.from + ": \(account.label)"
case .deposit:
return LocalizedString.Deposit.dailyLimit
case .buy:
guard let source = state.source, let destination = state.destination else {
return LocalizedString.Buy.title
}
return "\(LocalizedString.Buy.title) \(destination.currencyType.displayCode) using \(source.label)"
case .sell:
return [
LocalizedString.Sell.headerTitlePrefix,
state.source?.label
].compactMap { $0 }.joined(separator: " ")
case .sign,
.receive,
.viewActivity,
.linkToDebitCard:
unimplemented()
}
}
static func headerSubtitle(state: TransactionState) -> String {
switch state.action {
case .swap:
let prefix = "\(LocalizedString.receive): "
guard let moneyValue = try? state.moneyValueFromDestination().get() else {
return prefix
}
return prefix + formatForHeader(moneyValue: moneyValue)
case .send:
let prefix = "\(LocalizedString.Send.to): "
guard let destination = state.destination else {
return prefix
}
return prefix + destination.label
case .withdraw:
return formatForHeader(moneyValue: state.maxSpendable)
case .interestTransfer,
.interestWithdraw:
guard let destination = state.destination else {
return ""
}
guard let account = destination as? BlockchainAccount else {
return ""
}
return LocalizedString.to + ": \(account.label)"
case .deposit:
return state.maxDaily.displayString
case .buy:
let prefix = "\(LocalizedString.Buy.title):"
guard let destination = state.destination else {
return prefix
}
return "\(prefix) \(destination.currencyType.displayCode) \(destination.label)"
case .sell:
return [
LocalizedString.Sell.headerSubtitlePrefix,
state.destination?.label
].compactMap { $0 }.joined(separator: " ")
case .sign,
.receive,
.linkToDebitCard,
.viewActivity:
unimplemented()
}
}
}
enum AccountPicker {
static func sourceTitle(action: AssetAction) -> String {
switch action {
case .swap:
return LocalizedString.Swap.swap
case .deposit:
return LocalizedString.Deposit.linkedBanks
case .buy:
return LocalizedString.Buy.selectSourceTitle
case .sell:
return LocalizedString.Sell.selectSourceTitle
case .interestWithdraw:
return LocalizedString.Withdraw.withdrawTo
case .interestTransfer:
return LocalizedString.Transfer.addFrom
case .sign,
.receive,
.send,
.viewActivity,
.linkToDebitCard,
.withdraw:
return ""
}
}
static func sourceSubtitle(action: AssetAction) -> String {
switch action {
case .swap:
return LocalizedString.Swap.sourceAccountPicketSubtitle
case .sell:
return LocalizedString.Sell.selectSourceSubtitle
case .sign,
.withdraw,
.deposit,
.receive,
.buy,
.send,
.viewActivity,
.interestWithdraw,
.linkToDebitCard,
.interestTransfer:
return ""
}
}
static func destinationTitle(action: AssetAction) -> String {
switch action {
case .swap:
return LocalizedString.receive
case .withdraw,
.interestWithdraw:
return LocalizedString.Withdraw.withdrawTo
case .buy:
return LocalizedString.Buy.selectDestinationTitle
case .sell:
return LocalizedString.Sell.title
case .interestTransfer:
return LocalizedString.Transfer.addFrom
case .sign,
.deposit,
.receive,
.linkToDebitCard,
.send,
.viewActivity:
return ""
}
}
static func destinationSubtitle(action: AssetAction) -> String {
switch action {
case .swap:
return LocalizedString.Swap.destinationAccountPicketSubtitle
case .sell:
return LocalizedString.Sell.selectDestinationTitle
case .sign,
.deposit,
.receive,
.buy,
.send,
.viewActivity,
.withdraw,
.linkToDebitCard,
.interestWithdraw,
.interestTransfer:
return ""
}
}
}
enum TargetSelection {
static func navigationTitle(action: AssetAction) -> String {
switch action {
case .swap:
return LocalizedString.newSwap
case .send:
return LocalizedString.Send.send
case .withdraw,
.interestWithdraw:
return LocalizedString.Withdraw.withdraw
case .interestTransfer:
return LocalizedString.transfer
case .sign,
.deposit,
.receive,
.buy,
.sell,
.linkToDebitCard,
.viewActivity:
unimplemented()
}
}
}
static let networkFee = LocalizedString.networkFee
static let availableBalanceTitle = LocalizedString.available
static let maxButtonTitle = LocalizedString.Swap.swapMax
static func maxButtonTitle(action: AssetAction) -> String {
// Somtimes a `transfer` is referred to as `Add`.
// This is to avoid confusion as a transfer and a withdraw
// can sometimes sound the same to users. We do not always
// call a transfer `Add` though so that's why we have
// this if-statement.
if action == .interestTransfer {
return LocalizedString.add + " \(LocalizedString.max)"
}
return action.name + " \(LocalizedString.max)"
}
static func confirmDisclaimerVisibility(action: AssetAction) -> Bool {
switch action {
case .swap,
.withdraw,
.interestWithdraw,
.deposit,
.buy,
.sell:
return true
case .sign,
.receive,
.linkToDebitCard,
.send,
.viewActivity,
.interestTransfer:
return false
}
}
static func confirmDisclaimerText(
action: AssetAction,
currencyCode: String = "",
accountLabel: String = "",
isSafeConnect: Bool? = nil
) -> NSAttributedString {
switch action {
case .swap:
return addRefundPolicyLink(LocalizedString.Swap.confirmationDisclaimer)
case .sell:
return addRefundPolicyLink(LocalizedString.Sell.confirmationDisclaimer)
case .withdraw:
return LocalizedString.Withdraw.confirmationDisclaimer.attributed
case .buy:
if isSafeConnect == true {
return addSafeConnectTermsAndPolicyLink(
String(
format: LocalizedString.Buy.safeConnectConfirmationDisclaimer,
currencyCode,
LocalizedString.termsOfService,
LocalizedString.privacyPolicy
)
)
} else {
return "".attributed
}
case .interestWithdraw:
return String(
format: LocalizedString.InterestWithdraw.confirmationDisclaimer,
currencyCode,
accountLabel
).attributed
case .deposit:
if isSafeConnect == true {
return addSafeConnectTermsAndPolicyLink(
String(
format: LocalizedString.Deposit.safeConnectConfirmationDisclaimer,
LocalizedString.termsOfService,
LocalizedString.privacyPolicy
)
)
} else {
return "".attributed
}
case .sign,
.receive,
.send,
.viewActivity,
.linkToDebitCard,
.interestTransfer:
return "".attributed
}
}
private static func addRefundPolicyLink(_ string: String) -> NSAttributedString {
let attributedString = NSMutableAttributedString(
string: String(
format: string,
LocalizedString.refundPolicy
)
)
// swiftlint:disable:next line_length
let refundPolicyLink = "https://support.blockchain.com/hc/en-us/articles/4417063009172-Will-I-be-refunded-if-my-Swap-or-Sell-from-a-Private-Key-Wallet-fails-"
let refundPolicyRange = (attributedString.string as NSString).range(of: LocalizedString.refundPolicy)
attributedString.addAttribute(.link, value: refundPolicyLink, range: refundPolicyRange)
return attributedString
}
private static func addSafeConnectTermsAndPolicyLink(_ string: String) -> NSAttributedString {
let attributedString = NSMutableAttributedString(string: string)
let termsLink = "https://drive.google.com/file/d/11mNukqbBA_EbEBJd7bn9Idj1iiG8QWIL/view"
let termsRange = (attributedString.string as NSString).range(of: LocalizedString.termsOfService)
attributedString.addAttribute(.link, value: termsLink, range: termsRange)
let privacyPolicyLink = "https://www.yapily.com/legal/privacy-policy/"
let privacyPolicyRange = (attributedString.string as NSString).range(of: LocalizedString.privacyPolicy)
attributedString.addAttribute(.link, value: privacyPolicyLink, range: privacyPolicyRange)
return attributedString
}
static func confirmDisclaimerForBuy(paymentMethod: PaymentMethod?, lockDays: Int) -> String {
switch lockDays {
case 0:
return [LocalizedString.Buy.confirmationDisclaimer, LocalizedString.Buy.noLockInfo].joined(separator: " ")
default:
let paymentMethodName = paymentMethod?.label ?? ""
let lockDaysString = [
"\(lockDays)",
lockDays > 1 ? LocalizedString.Buy.days : LocalizedString.Buy.day
].joined(separator: " ")
return [
LocalizedString.Buy.confirmationDisclaimer,
String(
format: LocalizedString.Buy.lockInfo,
paymentMethodName,
lockDaysString
)
].joined(separator: " ")
}
}
}
extension String {
var attributed: NSAttributedString {
NSAttributedString(string: self)
}
}
|
lgpl-3.0
|
71c2a6fc928e1654127914d4f804a356
| 35.407713 | 166 | 0.534201 | 5.863354 | false | false | false | false |
slavapestov/swift
|
test/1_stdlib/SpriteKit.swift
|
2
|
892
|
// RUN: %target-run-simple-swift | FileCheck %s
// REQUIRES: executable_test
// REQUIRES: objc_interop
// watchOS does not have SpriteKit.
// UNSUPPORTED: OS=watchos
import Foundation
import SpriteKit
// Check that the subscript is there.
@available(OSX,introduced=10.10)
@available(iOS,introduced=8.0)
@available(tvOS,introduced=8.0)
@available(watchOS,introduced=2.0)
func testSubscript(node: SKNode) {
var nodes: [SKNode] = node["me"]
}
// SKColor is NSColor on OS X and UIColor on iOS.
var r = CGFloat(0)
var g = CGFloat(0)
var b = CGFloat(0)
var a = CGFloat(0)
var color = SKColor.redColor()
color.getRed(&r, green:&g, blue:&b, alpha:&a)
print("color \(r) \(g) \(b) \(a)")
// CHECK: color 1.0 0.0 0.0 1.0
#if os(OSX)
func f(c: NSColor) {
print("colortastic")
}
#endif
#if os(iOS) || os(tvOS)
func f(c: UIColor) {
print("colortastic")
}
#endif
f(color)
// CHECK: colortastic
|
apache-2.0
|
81b3b913d83057505ee906a85ca28448
| 19.744186 | 49 | 0.681614 | 2.822785 | false | false | false | false |
StanZabroda/Hydra
|
Hydra/MenuController.swift
|
1
|
14099
|
//
// MenuController.swift
// Hydra
//
// Created by Evgeny Abramov on 7/1/15.
// Copyright (c) 2015 Evgeny Abramov. All rights reserved.
//
import UIKit
class MenuHeader: UIView {
var firstNameLabel : UILabel!
var lastNameLabel : UILabel!
var avatarImage : UIImageView!
override init(frame: CGRect) {
super.init(frame: frame)
self.avatarImage = UIImageView()
self.avatarImage.frame = CGRectMake(15, 20, 60, 60)
self.avatarImage.layer.masksToBounds = true
self.avatarImage.layer.cornerRadius = 30.0
self.addSubview(self.avatarImage)
self.firstNameLabel = UILabel()
self.firstNameLabel.frame = CGRectMake(90, 30, screenSizeWidth-100, 20)
self.firstNameLabel.textColor = UIColor.whiteColor()
self.firstNameLabel.textAlignment = NSTextAlignment.Left
self.firstNameLabel.font = UIFont(name: "HelveticaNeue-Medium", size: 17)
self.addSubview(self.firstNameLabel)
self.lastNameLabel = UILabel()
self.lastNameLabel.frame = CGRectMake(90, 50, screenSizeWidth-100, 20)
self.lastNameLabel.textColor = UIColor.whiteColor()
self.lastNameLabel.textAlignment = NSTextAlignment.Left
self.lastNameLabel.font = UIFont(name: "HelveticaNeue-Light", size: 17)
self.addSubview(self.lastNameLabel)
let separator = UIView(frame: CGRectMake(0, 105, screenSizeWidth, 1))
separator.backgroundColor = UIColor(red: 255/255, green: 255/255, blue: 255/255, alpha: 0.2)
self.addSubview(separator)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class MenuPlayer: UIView {
var artistLabel : MarqueeLabel!
var songLabel : MarqueeLabel!
var albumCoverImage : UIImageView!
var blurEffectViewZZ : UIVisualEffectView!
var songSlider : UISlider!
var leftSongTimeLabel : UILabel!
var rightSongTimeLabel : UILabel!
var nextButton : UIButton!
var prevButton : UIButton!
var playButton : UIButton!
var pauseButton : UIButton!
var tapedView : UIView!
override init(frame: CGRect) {
super.init(frame: frame)
let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark)
self.blurEffectViewZZ = UIVisualEffectView(effect: blurEffect)
self.blurEffectViewZZ.frame = CGRectMake(0, 0, screenSizeWidth, 100)
self.blurEffectViewZZ.alpha = 0.5
self.blurEffectViewZZ.userInteractionEnabled = true
self.addSubview(self.blurEffectViewZZ)
self.songLabel = MarqueeLabel()
self.songLabel.frame = CGRectMake(50, 8, 200, 15)
self.songLabel.font = UIFont(name: "HelveticaNeue-Medium", size: 14)
self.songLabel.textColor = UIColor.whiteColor()
self.songLabel.text = "No song title"
self.addSubview(self.songLabel)
self.artistLabel = MarqueeLabel()
self.artistLabel.frame = CGRectMake(50, 27, 200, 15)
self.artistLabel.font = UIFont(name: "HelveticaNeue-Light", size: 12)
self.artistLabel.textColor = UIColor.grayColor()
self.artistLabel.text = "No artist"
self.addSubview(self.artistLabel)
self.albumCoverImage = UIImageView()
self.albumCoverImage.frame = CGRectMake(7, 7, 36, 36)
self.albumCoverImage.image = UIImage(named: "placeholder")
self.albumCoverImage.userInteractionEnabled = true
self.addSubview(self.albumCoverImage)
let separator = UIView(frame: CGRectMake(0, 50, screenSizeWidth, 1))
separator.backgroundColor = UIColor(red: 255/255, green: 255/255, blue: 255/255, alpha: 0.15)
self.addSubview(separator)
self.songSlider = UISlider()
self.songSlider.frame = CGRectMake(40, 60, (screenSizeWidth-60)-90, 40)
let insets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
let thumbImageNormal = UIImage(named: "ThumbVolume")
songSlider.setThumbImage(thumbImageNormal, forState: .Normal)
let trackLeftImage = UIImage(named: "minTrack")!
let trackLeftResizable = trackLeftImage.resizableImageWithCapInsets(insets)
songSlider.setMinimumTrackImage(trackLeftResizable, forState: .Normal)
let trackRightImage = UIImage(named: "maxTrack")!
let trackRightResizable = trackRightImage.resizableImageWithCapInsets(insets)
songSlider.setMaximumTrackImage(trackRightResizable, forState: .Normal)
self.addSubview(self.songSlider)
self.leftSongTimeLabel = UILabel()
self.leftSongTimeLabel.frame = CGRectMake(5, 70, 30, 20)
self.leftSongTimeLabel.textColor = UIColor.grayColor()
self.leftSongTimeLabel.font = UIFont(name: "HelveticaNeue-Light", size: 11)
self.leftSongTimeLabel.text = "00:00"
self.addSubview(self.leftSongTimeLabel)
self.rightSongTimeLabel = UILabel()
self.rightSongTimeLabel.frame = CGRectMake(((screenSizeWidth-60)-80)+40, 70, 30, 20)
self.rightSongTimeLabel.textColor = UIColor.grayColor()
self.rightSongTimeLabel.font = UIFont(name: "HelveticaNeue-Light", size: 11)
self.rightSongTimeLabel.text = "00:00"
self.addSubview(self.rightSongTimeLabel)
self.userInteractionEnabled = true
let gestureRec = UITapGestureRecognizer(target: self, action: "tapOnView")
self.tapedView = UIView(frame: CGRectMake(0, 0, screenSizeWidth, 49))
self.tapedView.backgroundColor = UIColor.clearColor()
self.tapedView.userInteractionEnabled = true
self.addSubview(tapedView)
self.tapedView.addGestureRecognizer(gestureRec)
}
func tapOnView() {
if HRPlayerManager.sharedInstance.items.count != 0 {
HRInterfaceManager.sharedInstance.openPlayer()
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class MenuController: UITableViewController {
var menuBackground : UIImageView!
var blurEffectView : UIVisualEffectView!
var menuHeader : MenuHeader!
var footerPlayer : MenuPlayer!
var selectedIndex = 0
override func viewDidLoad() {
super.viewDidLoad()
self.menuHeader = MenuHeader(frame: CGRectMake(0, 0, screenSizeWidth, 120))
self.addSubscribes()
self.tableView.backgroundColor = UIColor.clearColor()
self.tableView.tableFooterView = UIView(frame: CGRectZero)
self.tableView.tableHeaderView = self.menuHeader
self.tableView.separatorStyle = UITableViewCellSeparatorStyle.None
self.tableView.registerClass(HRMenuCell.self, forCellReuseIdentifier: "HRMenuCell")
let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark)
self.blurEffectView = UIVisualEffectView(effect: blurEffect)
self.blurEffectView.frame = self.view.frame
self.tableView.backgroundView = self.blurEffectView
HRDataManager.sharedInstance.getCurrentUserInfo()
self.footerPlayer = MenuPlayer(frame: CGRectMake(0, screenSizeHeight-100, screenSizeWidth, 100))
// shadow
let shadowPath = UIBezierPath(rect: self.footerPlayer.bounds)
self.footerPlayer.layer.masksToBounds = false
self.footerPlayer.layer.shadowColor = UIColor.blackColor().CGColor
self.footerPlayer.layer.shadowOffset = CGSizeMake(0.0, 5.0)
self.footerPlayer.layer.shadowOpacity = 0.5
self.footerPlayer.layer.shadowPath = shadowPath.CGPath
// actions
self.footerPlayer.songSlider.addTarget(self, action: "seekToSliderValue", forControlEvents: UIControlEvents.ValueChanged)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.navigationController!.view.addSubview(self.footerPlayer)
if selectedIndex > 0 {
self.tableView.selectRowAtIndexPath(NSIndexPath(forRow: selectedIndex-1, inSection: 0), animated: false, scrollPosition: UITableViewScrollPosition.None)
}
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
// MARK: - UI
// MARK: - Tableview delegate
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 6
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = HRMenuCell()
if indexPath.row == 0 {
cell.iconImage.image = UIImage(named: "my_music")
cell.menuTextLabel.text = "My music"
} else if indexPath.row == 1 {
cell.iconImage.image = UIImage(named: "menuDownloads")
cell.menuTextLabel.text = "Downloads"
} else if indexPath.row == 2 {
cell.iconImage.image = UIImage(named: "albums")
cell.menuTextLabel.text = "Albums"
} else if indexPath.row == 3 {
cell.iconImage.image = UIImage(named: "friendsIcon")
cell.menuTextLabel.text = "Friends"
} else if indexPath.row == 4 {
cell.iconImage.image = UIImage(named: "groupsIcon")
cell.menuTextLabel.text = "Groups"
} else if indexPath.row == 5 {
cell.iconImage.image = UIImage(named: "menuSettings")
cell.menuTextLabel.text = "Settings"
}
cell.backgroundColor = UIColor.clearColor()
return cell
}
override func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
return UITableViewCellEditingStyle.None
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.selectedIndex = indexPath.row+1
if indexPath.row == 0 {
HRInterfaceManager.sharedInstance.openMusicList()
} else if indexPath.row == 1 {
HRInterfaceManager.sharedInstance.openDownloads()
} else if indexPath.row == 2 {
HRInterfaceManager.sharedInstance.openAlbums()
} else if indexPath.row == 3 {
HRInterfaceManager.sharedInstance.openFriends()//openFriends
} else if indexPath.row == 4 {
HRInterfaceManager.sharedInstance.openGroups()
} else if indexPath.row == 5 {
HRInterfaceManager.sharedInstance.openSettings()
}
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 60
}
func addSubscribes() {
HRDataManager.sharedInstance.currentUserInfo.listen(self) { (userModel) -> Void in
dispatch.async.main({ () -> Void in
self.menuHeader.firstNameLabel.text = userModel.first_name
self.menuHeader.lastNameLabel.text = userModel.last_name
self.menuHeader.avatarImage.hnk_setImageFromURL(NSURL(string: userModel.photoURL)!)
})
}
// HRPlayerManager.sharedInstance.playSignal.listen(self) { (played) -> Void in
//
// dispatch.async.main({ () -> Void in
// if (played == true) {
// self.footerPlayer.hidden = false
// } else {
// self.footerPlayer.hidden = true
// }
// })
//
// }
HRPlayerManager.sharedInstance.currentSongChange.listen(self, callback: { (audioItem) -> Void in
dispatch.async.main({ () -> Void in
self.footerPlayer.artistLabel.text = audioItem.artist
self.footerPlayer.songLabel.text = audioItem.title
})
})
HRPlayerManager.sharedInstance.currentSongTimePlayed.listen(self, callback: { (duration, timePlayed) -> Void in
dispatch.async.main({ () -> Void in
self.footerPlayer.songSlider.value = Float(timePlayed)/Float(duration)
self.footerPlayer.leftSongTimeLabel.text = self.getTimeString(timePlayed)
self.footerPlayer.rightSongTimeLabel.text = self.getTimeString(duration)
})
})
HRPlayerManager.sharedInstance.coverChanged.listen(self) { (image) -> Void in
dispatch.async.main({ () -> Void in
self.footerPlayer.albumCoverImage.image = image
})
}
}
func getTimeString(totalSeconds:Int) -> String {
let seconds = Int(totalSeconds % 60)
let minutes = Int((totalSeconds / 60) % 60)
if minutes < 10 {
if seconds < 10 {
return "0\(minutes):0\(seconds)"
} else {
return "0\(minutes):\(seconds)"
}
} else {
if seconds < 10 {
return "\(minutes):0\(seconds)"
} else {
return "\(minutes):\(seconds)"
}
}
}
func seekToSliderValue() {
let song = HRPlayerManager.sharedInstance.currentItem
if song != nil {
let second = Int(Float(self.footerPlayer.songSlider.value) * Float(song.duration))
HRPlayerManager.sharedInstance.queue.queuePlayer.playAtSecond(second)
}
}
}
|
mit
|
0178397878dd31828c1d6defec18516c
| 35.81201 | 164 | 0.621533 | 4.900591 | false | false | false | false |
sadawi/ModelKit
|
ModelKit/ModelStore/ModelStore.swift
|
1
|
3493
|
//
// Server.swift
// APIKit
//
// Created by Sam Williams on 11/7/15.
// Copyright © 2015 Sam Williams. All rights reserved.
//
import Foundation
import PromiseKit
let ModelStoreErrorDomain = "ModelStore"
public protocol ListableModelStore {
/**
Retrieves a list of all models of the specified type.
*/
func list<T: Model>(_ modelClass:T.Type) -> Promise<[T]>
func list<T : Model>(_ field: ModelArrayField<T>) -> Promise<[T]>
}
public enum ModelStoreError: Error {
case noIdentifier(model: Model)
var description: String {
switch(self) {
case .noIdentifier(let model):
return "No identifier for model of type \(type(of: model))"
}
}
}
public protocol ModelStore: ListableModelStore {
/**
Inserts a record. May give the object an identifier.
// TODO: Decide on strict id semantics. Do we leave an existing identifier alone, or replace it with a new one?
The returned object should be a new instance, different from the provided one.
*/
func create<T:Model>(_ model: T, fields: [FieldType]?) -> Promise<T>
/**
Updates an existing record
*/
func update<T:Model>(_ model: T, fields: [FieldType]?) -> Promise<T>
/**
Deletes a record.
*/
func delete<T:Model>(_ model:T) -> Promise<T>
/**
Deletes all dependent records of another record.
*/
func deleteAll<T : Model>(_ field: ModelArrayField<T>) -> Promise<Void>
/**
Loads updated data for a model.
*/
func read<T: Model>(_ model: T) -> Promise<T>
var delegate:ModelStoreDelegate? { get set }
}
public protocol ClearableModelStore {
/**
Removes all stored instances of a model class, without fetching them.
*/
func deleteAll<T: Model>(_ modelClass:T.Type) -> Promise<Void>
func deleteAll() -> Promise<Void>
}
public extension ModelStore {
/**
Determines whether a model has been persisted to this data store.
This version is very dumb and just checks for the presence of an identifier.
But the signature is Promise-based, so a ModelStore implementation might actually do something asynchronous here.
*/
public func containsModel(_ model:Model) -> Promise<Bool> {
return Promise(value: model.identifier != nil)
}
func create<T:Model>(_ model:T) -> Promise<T> {
return self.create(model, fields: nil)
}
public func update<T:Model>(_ model: T) -> Promise<T> {
return self.update(model, fields: nil)
}
/**
Upsert. Creates a new record or updates an existing one, depending on whether we think it's been persisted.
*/
public func save<T: Model>(_ model:T, fields:[FieldType]?=nil) -> Promise<T> {
return self.containsModel(model).then(on: .global()) { (result:Bool) -> Promise<T> in
if result {
return self.update(model, fields: fields)
} else {
return self.create(model, fields: fields)
}
}
}
/**
Retrieves a record with the specified identifier. The Promise should fail if the record can't be found.
*/
func read<T: Model>(_ modelClass:T.Type, identifier:String) -> Promise<T> {
let model = modelClass.init() as T
model.identifier = identifier
return self.read(model)
}
}
func <<(left:ModelStore, right:Model) -> Promise<Model> {
return left.save(right)
}
|
mit
|
ceb95fd2ca6c32aa75f66062adf2918d
| 28.344538 | 118 | 0.621993 | 4.055749 | false | false | false | false |
gouyz/GYZBaking
|
baking/baking/ViewController.swift
|
1
|
3233
|
//
// ViewController.swift
// baking
// 新特性引导页
// Created by gouyz on 2017/3/22.
// Copyright © 2017年 gouyz. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
fileprivate var scrollView: UIScrollView!
fileprivate let numOfPages = 3
fileprivate var currPage = 0
override func viewDidLoad() {
super.viewDidLoad()
let frame = self.view.bounds
scrollView = UIScrollView(frame: frame)
scrollView.isPagingEnabled = true
scrollView.showsHorizontalScrollIndicator = false
scrollView.showsVerticalScrollIndicator = false
scrollView.scrollsToTop = false
scrollView.bounces = false
scrollView.contentOffset = CGPoint.zero
// 将 scrollView 的 contentSize 设为屏幕宽度的3倍(根据实际情况改变)
scrollView.contentSize = CGSize(width: frame.size.width * CGFloat(numOfPages), height: frame.size.height)
scrollView.delegate = self
for index in 0..<numOfPages {
let imageView = UIImageView(image: UIImage(named: "icon_guide\(index)"))
imageView.frame = CGRect(x: frame.size.width * CGFloat(index), y: 0, width: frame.size.width, height: frame.size.height)
scrollView.addSubview(imageView)
}
///放到最底层
self.view.insertSubview(scrollView, at: 0)
view.addSubview(startButton)
startButton.snp.makeConstraints { (make) in
make.bottom.equalTo(-50)
make.centerX.equalTo(view)
make.size.equalTo(CGSize.init(width: 300, height: 120))
}
// 隐藏开始按钮
startButton.alpha = 0.0
}
/// 登录按钮
fileprivate lazy var startButton : UIButton = {
let btn = UIButton.init(type: .custom)
btn.backgroundColor = UIColor.clear
btn.addTarget(self, action: #selector(clickedStartBtn), for: .touchUpInside)
return btn
}()
///进入主页
func clickedStartBtn(){
/// 获取当前版本号
let currentVersion = GYZUpdateVersionTool.getCurrVersion()
userDefaults.set(currentVersion, forKey: LHSBundleShortVersionString)
KeyWindow.rootViewController = GYZMainTabBarVC()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
// MARK: - UIScrollViewDelegate
extension ViewController: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offset = scrollView.contentOffset
// 随着滑动改变pageControl的状态
// pageControl.currentPage = Int(offset.x / view.bounds.width)
currPage = Int(offset.x / view.bounds.width)
// 因为currentPage是从0开始,所以numOfPages减1
if currPage == numOfPages - 1 {
UIView.animate(withDuration: 0.5, animations: {
self.startButton.alpha = 1.0
})
} else {
UIView.animate(withDuration: 0.2, animations: {
self.startButton.alpha = 0.0
})
}
}
}
|
mit
|
c350f57f568a20b722a1bab6ba3311aa
| 31.208333 | 132 | 0.625162 | 4.66365 | false | false | false | false |
PJayRushton/StarvingStudentGuide
|
StarvingStudentGuide/MarshaledObject.swift
|
1
|
5344
|
//
// M A R S H A L
//
// ()
// /\
// ()--' '--()
// `. .'
// / .. \
// ()' '()
//
//
import Foundation
// MARK: - Types
public typealias MarshaledObject = [String: AnyObject]
// MARK: - Dictionary Extensions
extension Dictionary where Key: KeyType {
public func anyForKey(key: Key) throws -> Any {
let pathComponents = key.stringValue.characters.split(".").map(String.init)
var accumulator: Any = self
for component in pathComponents {
if let componentData = accumulator as? [Key: Value], value = componentData[component as! Key] {
accumulator = value
continue
}
throw Error.KeyNotFound(key: key.stringValue)
}
if let _ = accumulator as? NSNull {
throw Error.NullValue(key: key.stringValue)
}
return accumulator
}
public func valueForKey<A: ValueType>(key: Key) throws -> A {
let any = try anyForKey(key)
do {
guard let result = try A.value(any) as? A else {
throw Error.TypeMismatchWithKey(key: key.stringValue, expected: A.self, actual: any.dynamicType)
}
return result
}
catch let Error.TypeMismatch(expected: expected, actual: actual) {
throw Error.TypeMismatchWithKey(key: key.stringValue, expected: expected, actual: actual)
}
}
public func valueForKey<A: ValueType>(key: Key) throws -> [A] {
let any = try anyForKey(key)
do {
return try Array<A>.value(any)
}
catch let Error.TypeMismatch(expected: expected, actual: actual) {
throw Error.TypeMismatchWithKey(key: key.stringValue, expected: expected, actual: actual)
}
}
public func valueForKey<A: ValueType>(key: Key) throws -> [A]? {
do {
return try self.valueForKey(key) as [A]
}
catch Error.KeyNotFound {
return nil
}
catch Error.NullValue {
return nil
}
}
public func valueForKey<A: ValueType>(key: Key) throws -> A? {
do {
return try self.valueForKey(key) as A
}
catch Error.KeyNotFound {
return nil
}
catch Error.NullValue {
return nil
}
}
public func valueForKey<A: ValueType>(key: Key) throws -> Set<A> {
let any = try anyForKey(key)
do {
return try Set<A>.value(any)
}
catch let Error.TypeMismatch(expected: expected, actual: actual) {
throw Error.TypeMismatchWithKey(key: key.stringValue, expected: expected, actual: actual)
}
}
public func valueForKey<A: ValueType>(key: Key) throws -> Set<A>? {
do {
return try self.valueForKey(key) as Set<A>
}
catch Error.KeyNotFound {
return nil
}
catch Error.NullValue {
return nil
}
}
}
extension Dictionary where Key: KeyType {
public func valueForKey<A: RawRepresentable where A.RawValue: ValueType>(key: Key) throws -> A {
let raw = try self.valueForKey(key) as A.RawValue
guard let value = A(rawValue: raw) else {
throw Error.TypeMismatchWithKey(key: key.stringValue, expected: A.self, actual: raw)
}
return value
}
public func valueForKey<A: RawRepresentable where A.RawValue: ValueType>(key: Key) throws -> A? {
do {
return try self.valueForKey(key) as A
}
catch Error.KeyNotFound {
return nil
}
catch Error.NullValue {
return nil
}
}
public func valueForKey<A: RawRepresentable where A.RawValue: ValueType>(key: Key) throws -> [A] {
let rawArray = try self.valueForKey(key) as [A.RawValue]
return try rawArray.map({ raw in
guard let value = A(rawValue: raw) else {
throw Error.TypeMismatchWithKey(key: key.stringValue, expected: A.self, actual: raw)
}
return value
})
}
public func valueForKey<A: RawRepresentable where A.RawValue: ValueType>(key: Key) throws -> [A]? {
do {
return try self.valueForKey(key) as [A]
}
catch Error.KeyNotFound {
return nil
}
catch Error.NullValue {
return nil
}
}
public func valueForKey<A: RawRepresentable where A.RawValue: ValueType>(key: Key) throws -> Set<A> {
let rawArray = try self.valueForKey(key) as [A.RawValue]
let enumArray: [A] = try rawArray.map({ raw in
guard let value = A(rawValue: raw) else {
throw Error.TypeMismatchWithKey(key: key.stringValue, expected: A.self, actual: raw)
}
return value
})
return Set<A>(enumArray)
}
public func valueForKey<A: RawRepresentable where A.RawValue: ValueType>(key: Key) throws -> Set<A>? {
do {
return try self.valueForKey(key) as Set<A>
}
catch Error.KeyNotFound {
return nil
}
catch Error.NullValue {
return nil
}
}
}
|
mit
|
f80f1fbb2a837c48834bc99252925f00
| 28.362637 | 112 | 0.548091 | 4.460768 | false | false | false | false |
yujinjcho/movie_recommendations
|
ios_ui/MovieRec/Classes/Common/Application Logic/Manager/NetworkManager.swift
|
1
|
1577
|
//
// NetworkManager.swift
// MovieRec
//
// Created by Yujin Cho on 11/13/17.
// Copyright © 2017 Yujin Cho. All rights reserved.
//
import Foundation
class NetworkManager : NSObject {
func getRequest(endPoint: String, completionHandler: @escaping (Data)->Void) {
let url = URL(string: endPoint)
var request = URLRequest(url: url!)
request.httpMethod = "GET"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print(error?.localizedDescription ?? "No data")
return
}
completionHandler(data)
}
task.resume()
}
func postRequest(endPoint: String, postData: [String:Any], completionHandler: @escaping (Data)->Void) {
let jsonData = try? JSONSerialization.data(withJSONObject: postData)
let url = URL(string: endPoint)
var request = URLRequest(url: url!)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print(error?.localizedDescription ?? "No data")
return
}
completionHandler(data)
}
task.resume()
}
}
|
mit
|
b24077db306c3a51d43584dc07a3d653
| 32.531915 | 107 | 0.59264 | 4.718563 | false | false | false | false |
LawrenceHan/iOS-project-playground
|
iOSRACSwift/Pods/ReactiveCocoa/ReactiveCocoa/Swift/FoundationExtensions.swift
|
35
|
1577
|
//
// FoundationExtensions.swift
// ReactiveCocoa
//
// Created by Justin Spahr-Summers on 2014-10-19.
// Copyright (c) 2014 GitHub. All rights reserved.
//
import Foundation
extension NSNotificationCenter {
/// Returns a producer of notifications posted that match the given criteria.
/// This producer will not terminate naturally, so it must be explicitly
/// disposed to avoid leaks.
public func rac_notifications(name: String? = nil, object: AnyObject? = nil) -> SignalProducer<NSNotification, NoError> {
return SignalProducer { observer, disposable in
let notificationObserver = self.addObserverForName(name, object: object, queue: nil) { notification in
observer.sendNext(notification)
}
disposable.addDisposable {
self.removeObserver(notificationObserver)
}
}
}
}
private let defaultSessionError = NSError(domain: "org.reactivecocoa.ReactiveCocoa.rac_dataWithRequest", code: 1, userInfo: nil)
extension NSURLSession {
/// Returns a producer that will execute the given request once for each
/// invocation of start().
public func rac_dataWithRequest(request: NSURLRequest) -> SignalProducer<(NSData, NSURLResponse), NSError> {
return SignalProducer { observer, disposable in
let task = self.dataTaskWithRequest(request) { data, response, error in
if let data = data, response = response {
observer.sendNext((data, response))
observer.sendCompleted()
} else {
observer.sendFailed(error ?? defaultSessionError)
}
}
disposable.addDisposable {
task.cancel()
}
task.resume()
}
}
}
|
mit
|
625a1f7a0f85ea166e859380c3f823dc
| 30.54 | 128 | 0.729233 | 4.15 | false | false | false | false |
niceagency/Contentful
|
Contentful/Contentful/Contentful.swift
|
1
|
15451
|
//
// Contentful.swift
// DeviceManagement
//
// Created by Sam Woolf on 17/10/2017.
// Copyright © 2017 Nice Agency. All rights reserved.
//
import Foundation
private typealias StringDict = [String:String?]
private typealias IntDict = [String:Int?]
private typealias DoubleDict = [String:Double?]
private typealias BoolDict = [String:Bool?]
private typealias OneRefDict = [String: [String:StringDict]?]
private typealias ManyRefDict = [String: [[String:StringDict]]? ]
public struct PageRequest {
public static func prepareRequest(forContent contentType: String, fromSpace spaceId: String, page: Page) -> (endpoint: String, query: [URLQueryItem]) {
let endpoint = "/spaces/\(spaceId)/entries"
let contentQuery = URLQueryItem(name: "content_type", value: contentType)
let selectQuery = URLQueryItem(name: "select", value: "sys.id,sys.version,fields")
let limitQuery = URLQueryItem(name: "limit", value: "\(page.itemsPerPage)")
let skipQuery = URLQueryItem(name: "skip", value: "\(page.itemsPerPage * page.currentPage)")
let queries = [contentQuery, selectQuery, limitQuery,skipQuery]
return (endpoint, queries)
}
}
public struct SingleEntryRequest {
public static func prepareRequest<T:Writeable>(forEntry entry: T, fromSpace spaceId: String) -> String {
return "/spaces/\(spaceId)/entries/\(entry.contentful_id)"
}
public static func prepareRequest(forEntryId entryId: String, fromSpace spaceId: String) -> String {
return "/spaces/\(spaceId)/entries/\(entryId)"
}
public static func prepareDeletionRequest<T: Writeable>(forEntry entry: T, fromSpace spaceId: String) -> WriteRequest {
let endpoint = "/spaces/\(spaceId)/entries/\(entry.contentful_id)"
let headers = [("X-Contentful-Version","\(entry.contentful_version)")]
return ( data: nil ,endpoint: endpoint, headers: headers, method: .delete)
}
}
public struct PageUnboxing {
public static func unboxResponse<T>(data: Data, locale: Locale?, with fieldUnboxer: @escaping (() -> (FieldMapping)), via creator: @escaping ((UnboxedFields) -> T)) -> Result<PagedResult<T>> {
let decoder = JSONDecoder()
decoder.userInfo = [CodingUserInfoKey(rawValue: "fieldUnboxer")!: fieldUnboxer, CodingUserInfoKey(rawValue: "creator")!: creator]
if let locale = locale {
decoder.userInfo.updateValue(locale, forKey: CodingUserInfoKey(rawValue: "locale")!)
}
do {
let response = try decoder.decode(Response<T>.self, from: data)
let entries = response.entries
let failures = response.failures
let page = Page(itemsPerPage: response.limit, currentPage: response.skip/response.limit, totalItemsAvailable: response.total)
return .success(PagedResult(validItems: entries, failedItems: failures, page: page))
} catch {
return .error(error as! Swift.DecodingError)
}
}
}
public struct ObjectEncoding {
public static func encode<T: Encodable>(object: T, locale: LocaleCode) -> (data: Data, sysData: SysData)? {
let encoder = JSONEncoder()
guard let jsonData = try? encoder.encode(object),
let jsonObject = try? JSONSerialization.jsonObject(with: jsonData,options: []),
let jsonDict = jsonObject as? [String: Any] else { return nil }
let sysData = SysData(id: object.contentful_id, version: object.contentful_version)
var contentfulFieldsDict: [String:Any] = [:]
for key in jsonDict.keys {
if key != "contentful_id" && key != "contentful_version" {
let nestedDict = [locale.rawValue: jsonDict[key] ?? ""]
contentfulFieldsDict.updateValue(nestedDict, forKey: key)
}
}
let contentfulDict: [String: Any] = ["fields": contentfulFieldsDict]
if let data = try? JSONSerialization.data(withJSONObject: contentfulDict, options: []) {
return (data: data, sysData: sysData)
}
return nil
}
}
public struct Publishing {
public static func preparePublishRequest<T: Writeable> (forEntry entry: T, toSpace spaceId: String ) -> WriteRequest {
let endpoint = "/spaces/\(spaceId)/entries/\(entry.contentful_id)/published"
let headers = [("X-Contentful-Version","\(entry.contentful_version)")]
return (data: nil, endpoint: endpoint, headers: headers, method: .put)
}
public static func preparePublishRequest (forEntryID entryID: String, entryVersion version: String, toSpace spaceId: String ) -> WriteRequest {
let endpoint = "/spaces/\(spaceId)/entries/\(entryID)/published"
let headers = [("X-Contentful-Version","\(version)")]
return (data: nil, endpoint: endpoint, headers: headers, method: .put)
}
public static func prepareUnpublishRequest<T: Writeable> (forEntry entry: T, toSpace spaceId: String ) -> WriteRequest {
let endpoint = "/spaces/\(spaceId)/entries/\(entry.contentful_id)/published"
let headers = [("X-Contentful-Version","\(entry.contentful_version)")]
return (data: nil, endpoint: endpoint, headers: headers, method: .delete)
}
public static func prepareUnpublishRequest (forEntryID entryID: String, entryVersion version: String, toSpace spaceId: String ) -> WriteRequest {
let endpoint = "/spaces/\(spaceId)/entries/\(entryID)/published"
let headers = [("X-Contentful-Version","\(version)")]
return (data: nil, endpoint: endpoint, headers: headers, method: .delete)
}
}
public struct Creating {
public static func prepareCreateEntryRequest<T: Readable & Encodable > ( forEntry entry: T, localeCode: LocaleCode, toSpace spaceId: String) -> WriteRequest? {
let endpoint = "/spaces/\(spaceId)/entries"
let headers = [("X-Contentful-Content-Type","\(T.contentfulEntryType())")]
guard let data = ObjectEncoding.encode(object: entry, locale: localeCode) else { return nil }
return (data: data.data, endpoint: endpoint, headers: headers, method: .post)
}
}
public struct Writing {
public static func prepareWriteRequest<T: Encodable> (forEntry entry: T, localeCode: LocaleCode, toSpace spaceId: String ) -> WriteRequest? {
let endpoint = "/spaces/\(spaceId)/entries/\(entry.contentful_id)"
let headers = [("X-Contentful-Version","\(entry.contentful_version)"),("Content-Type","application/vnd.contentful.management.v1+json") ]
guard let data = ObjectEncoding.encode(object: entry, locale: localeCode) else { return nil }
return (data: data.data, endpoint: endpoint, headers: headers, method: .put)
}
}
public struct ItemUnboxing {
public static func unbox <T>(data: Data, locale: Locale?, with fieldUnboxer: @escaping (() -> (FieldMapping)), via creator: @escaping ((UnboxedFields) -> T)) -> Result<ItemResult<T>> {
let decoder = JSONDecoder()
decoder.userInfo = [CodingUserInfoKey(rawValue: "fieldUnboxer")!: fieldUnboxer, CodingUserInfoKey(rawValue: "creator")!: creator]
if let locale = locale {
decoder.userInfo.updateValue(locale, forKey: CodingUserInfoKey(rawValue: "locale")!)
}
do {
let unboxed = try decoder.decode(Unboxable<T>.self, from: data)
return Result.success(unboxed.item)
} catch {
return Result.error(error as! Swift.DecodingError)
}
}
}
//MARK: JSON decoding keys
private struct Response<T> : Swift.Decodable {
let total: Int
let skip: Int
let limit: Int
let entries: [T]
let failures: [(Int, DecodingError)]
enum CodingKeys: String, CodingKey {
case total
case skip
case limit
case entries = "items"
}
init (from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
total = try container.decode(Int.self, forKey: .total)
skip = try container.decode(Int.self, forKey: .skip)
limit = try container.decode(Int.self, forKey: .limit)
let unboxables: [Unboxable<T>] = try container.decode([Unboxable<T>].self, forKey: .entries)
var entries: [T] = []
var failures: [(Int, DecodingError)] = []
for i in 0..<unboxables.count {
switch unboxables[i].item {
case .success(let entry):
entries.append(entry)
case .error(let error):
failures.append( (i,error))
}
}
self.entries = entries
self.failures = failures
}
}
private enum EntryCodingKeys: String, CodingKey {
case sys
case fields
}
private enum EntrySysCodingKeys: String, CodingKey {
case id
case version
}
private struct GenericCodingKeys: CodingKey {
var intValue: Int?
var stringValue: String
init?(intValue: Int) { self.intValue = intValue; self.stringValue = "\(intValue)" }
init?(stringValue: String) { self.stringValue = stringValue }
static func makeKey(name: String) -> GenericCodingKeys {
return GenericCodingKeys(stringValue: name)!
}
}
//MARK: Decoding container
private struct Unboxable<T>: Swift.Decodable {
let item: ItemResult<T>
init(from decoder: Decoder) throws {
let unboxing = decoder.userInfo[CodingUserInfoKey(rawValue: "fieldUnboxer")!] as! (() -> FieldMapping)
let creator = decoder.userInfo[CodingUserInfoKey(rawValue: "creator")!] as! ((UnboxedFields) -> T)
do {
let fields = try Unboxable.unboxableFields(fromDecoder: decoder, withUnboxing: unboxing)
item = .success(creator(fields))
} catch {
item = .error(error as! DecodingError)
}
}
static func unboxableFields(fromDecoder decoder: Decoder, withUnboxing unboxing: (() -> FieldMapping)) throws -> UnboxedFields {
func getValue<T>(fromDictionary dict: [String:T?], forLocale locale: Locale?) -> T? {
if let locale = locale {
for testKey in [locale.favouredLocale.rawValue, locale.fallbackLocale.rawValue] {
if let value = dict[testKey] {
return value
}
}
return nil
} else if let key = dict.keys.first {
return dict[key]!
}
return nil
}
var unboxedFields: UnboxedFields = [:]
let container = try decoder.container(keyedBy: EntryCodingKeys.self)
let sys = try container.nestedContainer(keyedBy: EntrySysCodingKeys.self, forKey: .sys)
unboxedFields["id"] = try sys.decode(String.self, forKey: .id)
unboxedFields["version"] = try sys.decode(Int.self, forKey: .version)
let locale = decoder.userInfo[CodingUserInfoKey(rawValue: "locale")!] as? Locale
let fields = try container.nestedContainer(keyedBy: GenericCodingKeys.self, forKey: .fields)
let fieldMapping = unboxing()
let requiredFields = fieldMapping.filter{ $0.value.1 == true }
let requiredKeys = Set(requiredFields.keys)
let fieldsReturned = Set(fields.allKeys.map { $0.stringValue })
guard requiredKeys.isSubset(of: fieldsReturned) else {
throw DecodingError.missingRequiredFields(Array(requiredKeys.subtracting(fieldsReturned)))
}
for key in fields.allKeys {
let field = key.stringValue
if let (type, required) = fieldMapping[field] {
switch type {
case .string:
let stringDict = try fields.decode(StringDict.self, forKey: key)
unboxedFields[field] = getValue(fromDictionary: stringDict, forLocale: locale)
case .int:
let intDict = try fields.decode(IntDict.self, forKey: key)
unboxedFields[field] = getValue(fromDictionary: intDict, forLocale : locale)
case .bool:
let boolDict = try fields.decode(BoolDict.self, forKey: key)
unboxedFields[field] = getValue(fromDictionary : boolDict, forLocale : locale)
case .decimal:
let doubleDict = try fields.decode(DoubleDict.self, forKey: key)
unboxedFields[field] = getValue(fromDictionary: doubleDict, forLocale : locale)
case .date:
let stringDict = try fields.decode(StringDict.self, forKey: key)
let dateString = getValue(fromDictionary: stringDict, forLocale : locale)
let formatter = ISO8601DateFormatter()
formatter.formatOptions = .withFullDate
if let ds = dateString {
if let date = formatter.date(from: ds) {
unboxedFields[field] = date
} else {
throw DecodingError.fieldFormatError(key.stringValue)
}
}
case .oneToOneRef:
let oneRefDict = try fields.decode(OneRefDict.self, forKey: key)
if let sysDict = getValue(fromDictionary: oneRefDict, forLocale: locale) {
guard let idDict = sysDict["sys"],
let id = idDict["id"], let unwrappedId = id, let type = idDict["linkType"], let unwrappedType = type else {
throw DecodingError.typeMismatch(key.stringValue, .oneToOneRef)
}
unboxedFields[field] = Reference(withId: unwrappedId, type: unwrappedType)
}
case .oneToManyRef:
let manyRefDict = try fields.decode(ManyRefDict.self, forKey: key)
if let sysDicts = getValue(fromDictionary: manyRefDict, forLocale: locale) {
let idDicts = sysDicts.flatMap { $0["sys"] }
let ids = idDicts.flatMap { $0["id"] }.flatMap {$0}
let types = idDicts.flatMap { $0["linkType"]}.flatMap{$0}
guard ids.count == types.count else { throw DecodingError.typeMismatch(key.stringValue, .oneToManyRef) }
let zipped = Array(zip(ids,types))
let references = zipped.map { Reference(withId: $0.0, type: $0.1)}
unboxedFields[field] = references
}
}
if required && unboxedFields[field] == nil {
throw DecodingError.requiredKeyMissing(key.stringValue)
}
}
}
return unboxedFields
}
}
|
mit
|
08bb13cfc9506cc07ddc79462acbba98
| 41.445055 | 197 | 0.593074 | 4.671908 | false | false | false | false |
MiniKeePass/MiniKeePass
|
MiniKeePass/Custom Field View/CustomFieldViewController.swift
|
1
|
2548
|
/*
* Copyright 2016 Jason Rush and John Flanagan. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import UIKit
class CustomFieldViewController: UITableViewController {
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var valueTextField: UITextField!
@IBOutlet weak var inMemoryProtectionSwitch: UISwitch!
@objc var stringField: StringField?
@objc var donePressed: ((_ customFieldViewController: CustomFieldViewController) -> Void)?
@objc var cancelPressed: ((_ customFieldViewController: CustomFieldViewController) -> Void)?
override func viewDidLoad() {
super.viewDidLoad()
guard let stringField = stringField else {
return
}
nameTextField.text = stringField.key
valueTextField.text = stringField.value
inMemoryProtectionSwitch.isOn = stringField.protected
}
// MARK: - UITextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if (textField == nameTextField) {
valueTextField.becomeFirstResponder()
} else if (textField == valueTextField) {
self.donePressedAction(nil)
}
return true
}
// MARK: - Actions
@IBAction func donePressedAction(_ sender: UIBarButtonItem?) {
guard let name = nameTextField.text, !(name.isEmpty) else {
self.presentAlertWithTitle(NSLocalizedString("Error", comment: ""), message: NSLocalizedString("Name cannot be empty", comment: ""))
return
}
if let stringField = stringField {
stringField.key = nameTextField.text
stringField.value = valueTextField.text
stringField.protected = inMemoryProtectionSwitch.isOn
}
donePressed?(self)
}
@IBAction func cancelPressedAction(_ sender: UIBarButtonItem) {
cancelPressed?(self)
}
}
|
gpl-3.0
|
7c804866bea863ffb02c1d0086243bf3
| 33.90411 | 144 | 0.677002 | 5.242798 | false | false | false | false |
fleurdeswift/data-structure
|
ExtraDataStructures/ReferenceCache.swift
|
1
|
2316
|
//
// ReferenceCache.swift
// ExtraDataStructures
//
// Copyright © 2015 Fleur de Swift. All rights reserved.
//
public class ReferenceCache<Key: Hashable, T: AnyObject> {
public typealias Element = T;
private var queue = dispatch_queue_create("ReferenceCache", DISPATCH_QUEUE_SERIAL);
private var entries = [Key: WeakReference<T>]();
public init() {
}
public subscript(key: Key) -> Element? {
get {
return dispatch_sync(queue) {
let ref = self.entries[key];
if let ref = ref {
return ref.value;
}
return nil;
}
}
}
public func getOrSet(key: Key, value: T) -> T {
return dispatch_sync(queue) {
let ref = self.entries[key];
if let ref = ref {
if let refValue = ref.value {
return refValue;
}
}
self.entries[key] = WeakReference<T>(value);
return value;
}
}
public func get(key: Key, creatorBlock: () -> T) -> T {
let cv = self[key];
if let v = cv {
return v;
}
return getOrSet(key, value: creatorBlock());
}
public func get(key: Key, creatorBlock: () throws -> T) throws -> T {
let cv = self[key];
if let v = cv {
return v;
}
return getOrSet(key, value: try creatorBlock());
}
public func get(key: Key, creatorBlock: () -> T?) -> T? {
var v = self[key];
if let v = v {
return v;
}
v = creatorBlock();
if let v = v {
return getOrSet(key, value: v);
}
return v;
}
public func get(key: Key, creatorBlock: () throws -> T?) throws -> T? {
var v = self[key];
if let v = v {
return v;
}
v = try creatorBlock();
if let v = v {
return getOrSet(key, value: v);
}
return v;
}
public func removeAll() {
dispatch_async(queue) {
self.entries.removeAll();
}
}
}
|
mit
|
e9774df305cc629b51b99765c6384057
| 21.475728 | 87 | 0.441901 | 4.359699 | false | false | false | false |
FuckBoilerplate/RxCache
|
watchOS/Pods/RxSwift/RxSwift/Schedulers/SchedulerServices+Emulation.swift
|
69
|
2266
|
//
// SchedulerServices+Emulation.swift
// RxSwift
//
// Created by Krunoslav Zaher on 6/6/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
enum SchedulePeriodicRecursiveCommand {
case tick
case dispatchStart
}
class SchedulePeriodicRecursive<State> {
typealias RecursiveAction = (State) -> State
typealias RecursiveScheduler = AnyRecursiveScheduler<SchedulePeriodicRecursiveCommand>
private let _scheduler: SchedulerType
private let _startAfter: RxTimeInterval
private let _period: RxTimeInterval
private let _action: RecursiveAction
private var _state: State
private var _pendingTickCount: AtomicInt = 0
init(scheduler: SchedulerType, startAfter: RxTimeInterval, period: RxTimeInterval, action: @escaping RecursiveAction, state: State) {
_scheduler = scheduler
_startAfter = startAfter
_period = period
_action = action
_state = state
}
func start() -> Disposable {
return _scheduler.scheduleRecursive(SchedulePeriodicRecursiveCommand.tick, dueTime: _startAfter, action: self.tick)
}
func tick(_ command: SchedulePeriodicRecursiveCommand, scheduler: RecursiveScheduler) -> Void {
// Tries to emulate periodic scheduling as best as possible.
// The problem that could arise is if handling periodic ticks take too long, or
// tick interval is short.
switch command {
case .tick:
scheduler.schedule(.tick, dueTime: _period)
// The idea is that if on tick there wasn't any item enqueued, schedule to perform work immediatelly.
// Else work will be scheduled after previous enqueued work completes.
if AtomicIncrement(&_pendingTickCount) == 1 {
self.tick(.dispatchStart, scheduler: scheduler)
}
case .dispatchStart:
_state = _action(_state)
// Start work and schedule check is this last batch of work
if AtomicDecrement(&_pendingTickCount) > 0 {
// This gives priority to scheduler emulation, it's not perfect, but helps
scheduler.schedule(SchedulePeriodicRecursiveCommand.dispatchStart)
}
}
}
}
|
mit
|
2932d55918fcce9c82c17c0bce1fc6ee
| 34.952381 | 137 | 0.672406 | 4.988987 | false | false | false | false |
roambotics/swift
|
test/Interop/SwiftToCxx/methods/method-in-cxx.swift
|
2
|
7486
|
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend %s -typecheck -module-name Methods -clang-header-expose-decls=all-public -emit-clang-header-path %t/methods.h
// RUN: %FileCheck %s < %t/methods.h
// RUN: %check-interop-cxx-header-in-clang(%t/methods.h)
public struct LargeStruct {
let x1, x2, x3, x4, x5, x6: Int
public func doubled() -> LargeStruct {
return LargeStruct(x1: x1 * 2, x2: x2 * 2, x3: x3 * 2, x4: x4 * 2, x5: x5 * 2, x6: x6 * 2)
}
public func dump() {
print("\(x1), \(x2), \(x3), \(x4), \(x5), \(x6)")
}
public func scaled(_ x: Int, _ y: Int) -> LargeStruct {
return LargeStruct(x1: x1 * x, x2: x2 * y, x3: x3 * x, x4: x4 * y, x5: x5 * x, x6: x6 * y)
}
public func added(_ x: LargeStruct) -> LargeStruct {
return LargeStruct(x1: x1 + x.x1, x2: x2 + x.x2, x3: x3 + x.x3, x4: x4 + x.x4, x5: x5 + x.x5, x6: x6 + x.x6)
}
}
public final class ClassWithMethods {
var field: Int
init(_ x: Int) {
field = x
}
deinit {
print("ClassWithMethods \(field) deinit")
}
public func dump() {
print("ClassWithMethods \(field);")
}
public func sameRet() -> ClassWithMethods {
return self
}
public func mutate() {
field = -field
}
public func deepCopy(_ x: Int) -> ClassWithMethods {
return ClassWithMethods(field + x)
}
}
public final class PassStructInClassMethod {
var largeStruct: LargeStruct
init() { largeStruct = LargeStruct(x1: 1, x2: 2, x3: 3, x4: 4, x5: 5, x6: 6) }
public func retStruct(_ x: Int) -> LargeStruct {
print("PassStructInClassMethod.retStruct \(x);")
return largeStruct
}
public func updateStruct(_ x: Int, _ y: LargeStruct) {
largeStruct = LargeStruct(x1: x, x2: y.x2, x3: y.x3, x4: y.x4, x5: y.x5, x6: y.x6)
}
}
// CHECK: SWIFT_EXTERN void $s7Methods09ClassWithA0C4dumpyyF(SWIFT_CONTEXT void * _Nonnull _self) SWIFT_NOEXCEPT SWIFT_CALL; // dump()
// CHECK: SWIFT_EXTERN void * _Nonnull $s7Methods09ClassWithA0C7sameRetACyF(SWIFT_CONTEXT void * _Nonnull _self) SWIFT_NOEXCEPT SWIFT_CALL; // sameRet()
// CHECK: SWIFT_EXTERN void $s7Methods09ClassWithA0C6mutateyyF(SWIFT_CONTEXT void * _Nonnull _self) SWIFT_NOEXCEPT SWIFT_CALL; // mutate()
// CHECK: SWIFT_EXTERN void * _Nonnull $s7Methods09ClassWithA0C8deepCopyyACSiF(ptrdiff_t x, SWIFT_CONTEXT void * _Nonnull _self) SWIFT_NOEXCEPT SWIFT_CALL; // deepCopy(_:)
// CHECK: SWIFT_EXTERN void $s7Methods11LargeStructV7doubledACyF(SWIFT_INDIRECT_RESULT void * _Nonnull, SWIFT_CONTEXT const void * _Nonnull _self) SWIFT_NOEXCEPT SWIFT_CALL; // doubled()
// CHECK: SWIFT_EXTERN void $s7Methods11LargeStructV4dumpyyF(SWIFT_CONTEXT const void * _Nonnull _self) SWIFT_NOEXCEPT SWIFT_CALL; // dump()
// CHECK: SWIFT_EXTERN void $s7Methods11LargeStructV6scaledyACSi_SitF(SWIFT_INDIRECT_RESULT void * _Nonnull, ptrdiff_t x, ptrdiff_t y, SWIFT_CONTEXT const void * _Nonnull _self) SWIFT_NOEXCEPT SWIFT_CALL; // scaled(_:_:)
// CHECK: SWIFT_EXTERN void $s7Methods11LargeStructV5addedyA2CF(SWIFT_INDIRECT_RESULT void * _Nonnull, const void * _Nonnull x, SWIFT_CONTEXT const void * _Nonnull _self) SWIFT_NOEXCEPT SWIFT_CALL; // added(_:)
// CHECK: SWIFT_EXTERN void $s7Methods23PassStructInClassMethodC03retC0yAA05LargeC0VSiF(SWIFT_INDIRECT_RESULT void * _Nonnull, ptrdiff_t x, SWIFT_CONTEXT void * _Nonnull _self) SWIFT_NOEXCEPT SWIFT_CALL; // retStruct(_:)
// CHECK: SWIFT_EXTERN void $s7Methods23PassStructInClassMethodC06updateC0yySi_AA05LargeC0VtF(ptrdiff_t x, const void * _Nonnull y, SWIFT_CONTEXT void * _Nonnull _self) SWIFT_NOEXCEPT SWIFT_CALL; // updateStruct(_:_:)
// CHECK: class ClassWithMethods final : public swift::_impl::RefCountedClass {
// CHECK: using RefCountedClass::RefCountedClass;
// CHECK-NEXT: using RefCountedClass::operator=;
// CHECK-NEXT: inline void dump();
// CHECK-NEXT: inline ClassWithMethods sameRet();
// CHECK-NEXT: inline void mutate();
// CHECK-NEXT: inline ClassWithMethods deepCopy(swift::Int x);
// CHECK: class LargeStruct final {
// CHECK: inline LargeStruct(LargeStruct &&)
// CHECK-NEXT: inline LargeStruct doubled() const;
// CHECK-NEXT: inline void dump() const;
// CHECK-NEXT: inline LargeStruct scaled(swift::Int x, swift::Int y) const;
// CHECK-NEXT: inline LargeStruct added(const LargeStruct& x) const;
// CHECK-NEXT: private
public func createClassWithMethods(_ x: Int) -> ClassWithMethods {
return ClassWithMethods(x)
}
public func createLargeStruct() -> LargeStruct {
return LargeStruct(x1: -1, x2: 2, x3: -100, x4: 42, x5: 67, x6: -10101)
}
public func createPassStructInClassMethod() -> PassStructInClassMethod {
return PassStructInClassMethod()
}
// CHECK: inline void ClassWithMethods::dump() {
// CHECK-NEXT: return _impl::$s7Methods09ClassWithA0C4dumpyyF(::swift::_impl::_impl_RefCountedClass::getOpaquePointer(*this));
// CHECK-NEXT: }
// CHECK-NEXT: inline ClassWithMethods ClassWithMethods::sameRet() {
// CHECK-NEXT: return _impl::_impl_ClassWithMethods::makeRetained(_impl::$s7Methods09ClassWithA0C7sameRetACyF(::swift::_impl::_impl_RefCountedClass::getOpaquePointer(*this)));
// CHECK-NEXT: }
// CHECK-NEXT: inline void ClassWithMethods::mutate() {
// CHECK-NEXT: return _impl::$s7Methods09ClassWithA0C6mutateyyF(::swift::_impl::_impl_RefCountedClass::getOpaquePointer(*this));
// CHECK-NEXT: }
// CHECK-NEXT: inline ClassWithMethods ClassWithMethods::deepCopy(swift::Int x) {
// CHECK-NEXT: return _impl::_impl_ClassWithMethods::makeRetained(_impl::$s7Methods09ClassWithA0C8deepCopyyACSiF(x, ::swift::_impl::_impl_RefCountedClass::getOpaquePointer(*this)));
// CHECK-NEXT: }
// CHECK: inline LargeStruct LargeStruct::doubled() const {
// CHECK-NEXT: return _impl::_impl_LargeStruct::returnNewValue([&](char * _Nonnull result) {
// CHECK-NEXT: _impl::$s7Methods11LargeStructV7doubledACyF(result, _getOpaquePointer());
// CHECK-NEXT: });
// CHECK-NEXT: }
// CHECK-NEXT: inline void LargeStruct::dump() const {
// CHECK-NEXT: return _impl::$s7Methods11LargeStructV4dumpyyF(_getOpaquePointer());
// CHECK-NEXT: }
// CHECK-NEXT: inline LargeStruct LargeStruct::scaled(swift::Int x, swift::Int y) const {
// CHECK-NEXT: return _impl::_impl_LargeStruct::returnNewValue([&](char * _Nonnull result) {
// CHECK-NEXT: _impl::$s7Methods11LargeStructV6scaledyACSi_SitF(result, x, y, _getOpaquePointer());
// CHECK-NEXT: });
// CHECK-NEXT: }
// CHECK-NEXT: inline LargeStruct LargeStruct::added(const LargeStruct& x) const {
// CHECK-NEXT: return _impl::_impl_LargeStruct::returnNewValue([&](char * _Nonnull result) {
// CHECK-NEXT: _impl::$s7Methods11LargeStructV5addedyA2CF(result, _impl::_impl_LargeStruct::getOpaquePointer(x), _getOpaquePointer());
// CHECK-NEXT: });
// CHECK-NEXT: }
// CHECK: inline LargeStruct PassStructInClassMethod::retStruct(swift::Int x) {
// CHECK-NEXT: return _impl::_impl_LargeStruct::returnNewValue([&](char * _Nonnull result) {
// CHECK-NEXT: _impl::$s7Methods23PassStructInClassMethodC03retC0yAA05LargeC0VSiF(result, x, ::swift::_impl::_impl_RefCountedClass::getOpaquePointer(*this));
// CHECK-NEXT: });
// CHECK-NEXT: }
// CHECK-NEXT: inline void PassStructInClassMethod::updateStruct(swift::Int x, const LargeStruct& y) {
// CHECK-NEXT: return _impl::$s7Methods23PassStructInClassMethodC06updateC0yySi_AA05LargeC0VtF(x, _impl::_impl_LargeStruct::getOpaquePointer(y), ::swift::_impl::_impl_RefCountedClass::getOpaquePointer(*this));
// CHECK-NEXT: }
|
apache-2.0
|
c823fd0b6c6bbab2c91c03b7c074601a
| 49.92517 | 221 | 0.701309 | 3.378159 | false | false | false | false |
crazypoo/PTools
|
Pods/SwifterSwift/Sources/SwifterSwift/Foundation/NSAttributedStringExtensions.swift
|
1
|
5935
|
//
// NSAttributedStringExtensions.swift
// SwifterSwift
//
// Created by Omar Albeik on 26/11/2016.
// Copyright © 2016 SwifterSwift
//
#if canImport(Foundation)
import Foundation
#if canImport(UIKit)
import UIKit
#endif
#if canImport(AppKit)
import AppKit
#endif
// MARK: - Properties
public extension NSAttributedString {
#if os(iOS)
/// SwifterSwift: Bolded string.
var bolded: NSAttributedString {
return applying(attributes: [.font: UIFont.boldSystemFont(ofSize: UIFont.systemFontSize)])
}
#endif
#if !os(Linux)
/// SwifterSwift: Underlined string.
var underlined: NSAttributedString {
return applying(attributes: [.underlineStyle: NSUnderlineStyle.single.rawValue])
}
#endif
#if os(iOS)
/// SwifterSwift: Italicized string.
var italicized: NSAttributedString {
return applying(attributes: [.font: UIFont.italicSystemFont(ofSize: UIFont.systemFontSize)])
}
#endif
#if !os(Linux)
/// SwifterSwift: Struckthrough string.
var struckthrough: NSAttributedString {
return applying(attributes: [.strikethroughStyle: NSNumber(value: NSUnderlineStyle.single.rawValue as Int)])
}
#endif
#if !os(Linux)
/// SwifterSwift: Dictionary of the attributes applied across the whole string
var attributes: [NSAttributedString.Key: Any] {
guard self.length > 0 else { return [:] }
return attributes(at: 0, effectiveRange: nil)
}
#endif
}
// MARK: - Methods
public extension NSAttributedString {
#if !os(Linux)
/// SwifterSwift: Applies given attributes to the new instance of NSAttributedString initialized with self object
///
/// - Parameter attributes: Dictionary of attributes
/// - Returns: NSAttributedString with applied attributes
fileprivate func applying(attributes: [NSAttributedString.Key: Any]) -> NSAttributedString {
let copy = NSMutableAttributedString(attributedString: self)
let range = (string as NSString).range(of: string)
copy.addAttributes(attributes, range: range)
return copy
}
#endif
#if canImport(AppKit) || canImport(UIKit)
/// SwifterSwift: Add color to NSAttributedString.
///
/// - Parameter color: text color.
/// - Returns: a NSAttributedString colored with given color.
func colored(with color: Color) -> NSAttributedString {
return applying(attributes: [.foregroundColor: color])
}
#endif
#if !os(Linux)
/// SwifterSwift: Apply attributes to substrings matching a regular expression
///
/// - Parameters:
/// - attributes: Dictionary of attributes
/// - pattern: a regular expression to target
/// - options: The regular expression options that are applied to the expression during matching. See NSRegularExpression.Options for possible values.
/// - Returns: An NSAttributedString with attributes applied to substrings matching the pattern
func applying(attributes: [NSAttributedString.Key: Any],
toRangesMatching pattern: String,
options: NSRegularExpression.Options = []) -> NSAttributedString {
guard let pattern = try? NSRegularExpression(pattern: pattern, options: options) else { return self }
let matches = pattern.matches(in: string, options: [], range: NSRange(0..<length))
let result = NSMutableAttributedString(attributedString: self)
for match in matches {
result.addAttributes(attributes, range: match.range)
}
return result
}
/// SwifterSwift: Apply attributes to occurrences of a given string
///
/// - Parameters:
/// - attributes: Dictionary of attributes
/// - target: a subsequence string for the attributes to be applied to
/// - Returns: An NSAttributedString with attributes applied on the target string
func applying<T: StringProtocol>(attributes: [NSAttributedString.Key: Any], toOccurrencesOf target: T) -> NSAttributedString {
let pattern = "\\Q\(target)\\E"
return applying(attributes: attributes, toRangesMatching: pattern)
}
#endif
}
// MARK: - Operators
public extension NSAttributedString {
/// SwifterSwift: Add a NSAttributedString to another NSAttributedString.
///
/// - Parameters:
/// - lhs: NSAttributedString to add to.
/// - rhs: NSAttributedString to add.
static func += (lhs: inout NSAttributedString, rhs: NSAttributedString) {
let string = NSMutableAttributedString(attributedString: lhs)
string.append(rhs)
lhs = string
}
/// SwifterSwift: Add a NSAttributedString to another NSAttributedString and return a new NSAttributedString instance.
///
/// - Parameters:
/// - lhs: NSAttributedString to add.
/// - rhs: NSAttributedString to add.
/// - Returns: New instance with added NSAttributedString.
static func + (lhs: NSAttributedString, rhs: NSAttributedString) -> NSAttributedString {
let string = NSMutableAttributedString(attributedString: lhs)
string.append(rhs)
return NSAttributedString(attributedString: string)
}
/// SwifterSwift: Add a NSAttributedString to another NSAttributedString.
///
/// - Parameters:
/// - lhs: NSAttributedString to add to.
/// - rhs: String to add.
static func += (lhs: inout NSAttributedString, rhs: String) {
lhs += NSAttributedString(string: rhs)
}
/// SwifterSwift: Add a NSAttributedString to another NSAttributedString and return a new NSAttributedString instance.
///
/// - Parameters:
/// - lhs: NSAttributedString to add.
/// - rhs: String to add.
/// - Returns: New instance with added NSAttributedString.
static func + (lhs: NSAttributedString, rhs: String) -> NSAttributedString {
return lhs + NSAttributedString(string: rhs)
}
}
#endif
|
mit
|
12a29795d53901692b2b331458a72138
| 33.300578 | 156 | 0.676946 | 4.986555 | false | false | false | false |
mdpianelli/ios-shopfinder
|
ShopFinder/ShopFinder/BaseController.swift
|
1
|
2380
|
//
// BaseController.swift
// ShopFinder
//
// Created by Marcos Pianelli on 14/09/15.
// Copyright (c) 2015 Barkala Studios. All rights reserved.
//
import UIKit
class BaseController: UIViewController {
func callAction(item: TableRow){
let number = item.action?.data as! String
let trimNumber = number.removeWhitespace()
if let url = NSURL(string: "tel://\(trimNumber)") {
let alertVC = UIAlertController(title:NSLocalizedString("Would you like to call?", comment: ""), message: nil, preferredStyle: .Alert)
//Create and add the Cancel action
let callAction: UIAlertAction = UIAlertAction(title: NSLocalizedString("Call", comment:""), style: .Default) { action -> Void in
UIApplication.sharedApplication().openURL(url);
}
alertVC.addAction(callAction)
self.presentViewController(alertVC, animated: true, completion: nil)
}
}
//MARK: Actions
func openDlinkAction(item: TableRow){
//open deepLink
if let dic = item.action!.data as? NSDictionary{
let dlink = NSURL(string:dic.objectForKey("dlink") as! String)
var link : NSURL?
if let lStr = dic.objectForKey("link") as? String {
link = NSURL(string:lStr)
}
if UIApplication.sharedApplication().canOpenURL(dlink!) {
UIApplication.sharedApplication().openURL(dlink!)
}else{
if link != nil {
UIApplication.sharedApplication().openURL(link!)
}
}
}
}
func openLinkAction(item: TableRow){
if let link = item.action!.data as? String {
if link.hasPrefix("http") {
//open normal link
let nav = self.storyboard?.instantiateViewControllerWithIdentifier("NavWebController") as! UINavigationController
let wc = nav.topViewController as! WebController
wc.link = NSURL(string: link)
wc.title = item.title
self.presentViewController(nav, animated: true, completion: nil)
}
}
}
}
|
mit
|
60df3eaeca1c0da52ad07cfee9371aae
| 27 | 139 | 0.543697 | 5.12931 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.