repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
wireapp/wire-ios-sync-engine | Source/Registration/Company/CompanyLoginRequester.swift | 1 | 7681 | //
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
extension URL {
enum Host {
static let connect = "connect"
static let login = "login"
static let startLogin = "start-login"
static let startSSO = "start-sso"
static let accessBackend = "access" // Used for connecting to custom backend
}
enum Path {
static let success = "success"
static let failure = "failure"
}
}
extension URLQueryItem {
enum Key {
enum Connect {
static let service = "service"
static let provider = "provider"
}
enum AccessBackend {
static let config = "config"
}
static let successRedirect = "success_redirect"
static let errorRedirect = "error_redirect"
static let cookie = "cookie"
static let userIdentifier = "userid"
static let errorLabel = "label"
static let validationToken = "validation_token"
}
enum Template {
static let cookie = "$cookie"
static let userIdentifier = "$userid"
static let errorLabel = "$label"
}
}
@objc public protocol URLSessionProtocol: AnyObject {
@objc(dataTaskWithRequest:completionHandler:)
func dataTask(with request: URLRequest, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask
}
extension URLSession: URLSessionProtocol {}
public typealias StatusCode = Int
public enum ValidationError: Equatable {
case invalidCode
case invalidStatus(StatusCode)
case unknown
init?(response: HTTPURLResponse?, error: Error?) {
switch (response?.statusCode, error) {
case (404?, _): self = .invalidCode
case ((400...599)?, _): self = .invalidStatus(response!.statusCode)
case (_, .some), (.none, _): self = .unknown
default: return nil
}
}
}
public protocol CompanyLoginRequesterDelegate: AnyObject {
/**
* The login requester asks the user to verify their identity on the given website.
*
* - parameter requester: The requester asking for validation.
* - parameter url: The URL where the user should be taken to perform validation.
*/
func companyLoginRequester(_ requester: CompanyLoginRequester, didRequestIdentityValidationAtURL url: URL)
}
/**
* An object that validates the identity of the user and creates a session using company login.
*/
public class CompanyLoginRequester {
/// The URL scheme that where the callback will be provided.
public let callbackScheme: String
/// The object that observes events and performs the required actions.
public weak var delegate: CompanyLoginRequesterDelegate?
private let defaults: UserDefaults
private let session: URLSessionProtocol
/// Creates a session requester that uses the specified parameters.
public init(
callbackScheme: String,
defaults: UserDefaults = .shared(),
session: URLSessionProtocol? = nil
) {
self.callbackScheme = callbackScheme
self.defaults = defaults
self.session = session ?? URLSession(configuration: .ephemeral)
}
// MARK: - Token Validation
/**
* Validated a company login token.
*
* This method will verify a company login token with the backend.
* The requester provided by the `enqueueProvider` passed to `init` will
* be used to perform the request.
*
* - parameter host: The backend to validate SSO code against.
* - parameter token: The user login token.
* - parameter completion: The completion closure called with the validation result.
*/
public func validate(host: String, token: UUID, completion: @escaping (ValidationError?) -> Void) {
guard let url = urlComponents(host: host, token: token).url else { fatalError("Invalid company login url.") }
var request = URLRequest(url: url)
request.httpMethod = "HEAD"
let task = session.dataTask(with: request) { _, response, error in
DispatchQueue.main.async {
completion(ValidationError(response: response as? HTTPURLResponse, error: error))
}
}
task.resume()
}
// MARK: - Identity Request
/**
* Starts the company login flow for the user with the given login token.
*
* This method constructs the login URL, and calls the `delegate`, that will
* handle opening the URL. Typically, this initiates the login flow, which will
* open Safari. The `SessionManager` will handle the callback URL.
*
* - parameter token: The user login token, constructed from the request code.
*/
public func requestIdentity(host: String, token: UUID) {
let validationToken = CompanyLoginVerificationToken()
var components = urlComponents(host: host, token: token)
components.queryItems = [
URLQueryItem(name: URLQueryItem.Key.successRedirect, value: makeSuccessCallbackString(using: validationToken)),
URLQueryItem(name: URLQueryItem.Key.errorRedirect, value: makeFailureCallbackString(using: validationToken))
]
guard let url = components.url else {
fatalError("Invalid company login URL. This is a developer error.")
}
validationToken.store(in: defaults)
delegate?.companyLoginRequester(self, didRequestIdentityValidationAtURL: url)
}
// MARK: - Utilities
private func urlComponents(host: String, token: UUID) -> URLComponents {
var components = URLComponents()
components.scheme = "https"
components.host = host
components.path = "/sso/initiate-login/\(token.uuidString)"
return components
}
private func makeSuccessCallbackString(using token: CompanyLoginVerificationToken) -> String {
var components = URLComponents()
components.scheme = callbackScheme
components.host = URL.Host.login
components.path = "/" + URL.Path.success
components.queryItems = [
URLQueryItem(name: URLQueryItem.Key.cookie, value: URLQueryItem.Template.cookie),
URLQueryItem(name: URLQueryItem.Key.userIdentifier, value: URLQueryItem.Template.userIdentifier),
URLQueryItem(name: URLQueryItem.Key.validationToken, value: token.uuid.transportString())
]
return components.url!.absoluteString
}
private func makeFailureCallbackString(using token: CompanyLoginVerificationToken) -> String {
var components = URLComponents()
components.scheme = callbackScheme
components.host = URL.Host.login
components.path = "/" + URL.Path.failure
components.queryItems = [
URLQueryItem(name: URLQueryItem.Key.errorLabel, value: URLQueryItem.Template.errorLabel),
URLQueryItem(name: URLQueryItem.Key.validationToken, value: token.uuid.transportString())
]
return components.url!.absoluteString
}
}
| gpl-3.0 | 1dd66c09974e41d1e159b5b39261a8f8 | 34.233945 | 133 | 0.671137 | 4.904853 | false | false | false | false |
google/iosched-ios | Source/Platform/Repository/Firestore/Session+Firestore.swift | 1 | 4192 | //
// Copyright (c) 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import FirebaseFirestore
extension URL {
init?(string: String?) {
guard let string = string, !string.isEmpty else {
return nil
}
self.init(string: string)
}
}
extension Session {
public init?(scheduleDetail: QueryDocumentSnapshot) {
let data = scheduleDetail.data() as [String: Any]
let id = data["id"] as? String
let title = data["title"] as? String
let description = data["description"] as? String
let startTimestamp = data["startTimestamp"] as? NSNumber
let endTimestamp = data["endTimestamp"] as? NSNumber
let room = data["room"] as? [String: Any]
let roomId = room?["id"] as? String
let roomName = room?["name"] as? String
let tags = data["tags"] as? [[String: Any]]
var eventTags: [EventTag] = []
if let tags = tags {
for tag: [String: Any] in tags {
if let eventTag = EventTag(dictionary: tag) {
eventTags.append(eventTag)
}
}
}
var speakers: [Speaker] = []
if let speakersData = data["speakers"] as? [[String: Any]] {
for speakerData in speakersData {
let speakerId = speakerData["id"] as? String
let speakerName = speakerData["name"] as? String
let speakerBio = speakerData["bio"] as? String
let speakerCompany = speakerData["company"] as? String
let speakerThumbnailURL = URL(string: speakerData["thumbnailURL"] as? String)
let speakerSocialLinks = (speakerData["socialLinks"] as? [String: Any]) ?? [String: Any]()
let speakerTwitterURL = URL(string: speakerSocialLinks["Twitter"] as? String)
let speakerGithubURL = URL(string: speakerSocialLinks["GitHub"] as? String)
let speakerLinkedInURL = URL(string: speakerSocialLinks["LinkedIn"] as? String)
let speakerWebsiteURL = URL(string: speakerSocialLinks["Website"] as? String)
if let speakerId = speakerId,
let speakerName = speakerName,
let speakerBio = speakerBio,
let speakerCompany = speakerCompany {
let speaker = Speaker(id: speakerId,
name: speakerName,
bio: speakerBio,
company: speakerCompany,
thumbnailURL: speakerThumbnailURL,
twitterURL: speakerTwitterURL,
linkedinURL: speakerGithubURL,
githubURL: speakerLinkedInURL,
websiteURL: speakerWebsiteURL)
speakers.append(speaker)
}
}
}
self.speakers = speakers
let youtubeURL = data["youtubeUrl"] as? String
// Check for required fields and abort if missing.
if let id = id,
let title = title,
let description = description,
let startTimestamp = startTimestamp,
let endTimestamp = endTimestamp,
let url = URL(string: "https://events.google.com/io/schedule/events/" + id) {
self.id = id
self.url = url
self.title = title
self.detail = description
self.startTimestamp = Date(timeIntervalSince1970: startTimestamp.doubleValue / 1000)
self.endTimestamp = Date(timeIntervalSince1970: endTimestamp.doubleValue / 1000)
self.youtubeURL = youtubeURL.flatMap(URL.init(string:))
self.tags = eventTags
self.mainTopic = eventTags.filter { $0.type == .topic } .first
self.roomId = roomId ?? "(unknown)"
self.roomName = roomName ?? "(TBA)"
} else {
print("Malformed data: \(data)")
return nil
}
}
}
| apache-2.0 | b315b204c53c5e68abb554455dfde1de | 38.92381 | 98 | 0.622376 | 4.362123 | false | false | false | false |
chenchangqing/learniosRAC | CarthageTest/CarthageTest/ViewController.swift | 1 | 3674 | //
// ViewController.swift
// CarthageTest
//
// Created by green on 15/9/2.
// Copyright (c) 2015年 RACTest. All rights reserved.
//
import UIKit
import ReactiveCocoa
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// testCancelLoginWithTakeUntil(isCancel:false)
testCancelLoginWithTakeUntilBlock(isCancel: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/**
* 模拟取消登录
*/
func testCancelLoginWithTakeUntil(#isCancel:Bool) {
var isLogined = false
// 取消登录命令
let cancelLoginCommand = RACCommand { (any:AnyObject!) -> RACSignal! in
let signal = RACSignal.createSignal({ (subscriber:RACSubscriber!) -> RACDisposable! in
subscriber.sendNext(nil)
return nil
})
return signal
}
// 登录命令
let loginCommand = RACCommand { (any:AnyObject!) -> RACSignal! in
let signal = RACSignal.createSignal({ (subscriber:RACSubscriber!) -> RACDisposable! in
let duration:UInt64 = isCancel ? 4 : 2
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(NSEC_PER_SEC * duration)), dispatch_get_main_queue()) { () -> Void in
subscriber.sendNext(nil)
}
return nil
}).takeUntil(cancelLoginCommand.executionSignals)
signal.subscribeNext({ (any:AnyObject!) -> Void in
isLogined = true
})
signal.subscribeCompleted({ () -> Void in
if isLogined {
println("登录成功")
} else {
println("取消登录")
}
})
return signal
}
loginCommand.execute(nil)
}
/**
* 模拟取消登录
*/
func testCancelLoginWithTakeUntilBlock(#isCancel:Bool) {
var isLogined = false
// 登录命令
let loginCommand = RACCommand { (any:AnyObject!) -> RACSignal! in
let signal = RACSignal.createSignal({ (subscriber:RACSubscriber!) -> RACDisposable! in
let duration:UInt64 = isCancel ? 4 : 2
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(NSEC_PER_SEC * duration)), dispatch_get_main_queue()) { () -> Void in
subscriber.sendNext("fsdf")
subscriber.sendCompleted()
}
return nil
}).takeUntilBlock({ (any:AnyObject!) -> Bool in
return true
})
signal.subscribeNext({ (any:AnyObject!) -> Void in
isLogined = true
})
signal.subscribeCompleted({ () -> Void in
if isLogined {
println("登录成功")
} else {
println("取消登录")
}
})
return signal
}
loginCommand.execute(nil)
}
}
| gpl-2.0 | 7082b7e00f2ebe754e3161e9e8fe7fac | 26.813953 | 141 | 0.455407 | 5.787097 | false | false | false | false |
NickEntin/SimPermissions | SimPermissions/PermissionMenuItem.swift | 1 | 3150 | //
// PermissionMenuItem.swift
// SimPermissions
//
// Copyright (c) 2016 Nick Entin
//
// 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 AppKit
class PermissionMenuItem : NSMenuItem {
let permission: PermissionModel
let permissionManager: PermissionManager
let refresh: ()->()
init(permission: PermissionModel, permissionManager: PermissionManager, refresh: ()->()) {
self.permission = permission
self.permissionManager = permissionManager
self.refresh = refresh
super.init(title: "", action: nil, keyEquivalent: "")
let permissionView = PermissionMenuItemView(permission: permission)
permissionView.allowButton.target = self
permissionView.allowButton.action = #selector(grantPermission)
permissionView.revokeButton.target = self
permissionView.revokeButton.action = #selector(revokePermission)
permissionView.deleteButton.target = self
permissionView.deleteButton.action = #selector(clearPermission)
view = permissionView
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(title aString: String, action aSelector: Selector, keyEquivalent charCode: String) {
fatalError("init(title:action:keyEquivalent:) has not been implemented")
}
@objc func grantPermission(sender: AnyObject) {
do {
try permissionManager.grantPermission(permission)
refresh()
} catch _ {
print("Unable to grant permission")
}
}
@objc func revokePermission(sender: AnyObject) {
do {
try permissionManager.revokePermission(permission)
refresh()
} catch _ {
print("Unable to revoke permission")
}
}
@objc func clearPermission(sender: AnyObject) {
do {
try permissionManager.deletePermission(permission)
refresh()
} catch _ {
print("Unable to clear permission")
}
}
}
| mit | 614ec0e2a7f718021bc005a95d6580df | 36.5 | 102 | 0.676508 | 4.921875 | false | false | false | false |
akkakks/firefox-ios | ThirdParty/json.swift | 2 | 11818 | //
// json.swift
// json
//
// Created by Dan Kogai on 7/15/14.
// Copyright (c) 2014 Dan Kogai. All rights reserved.
//
import Foundation
/// init
public class JSON {
private let _value:AnyObject
/// pass the object that was returned from
/// NSJSONSerialization
public init(_ obj:AnyObject) { self._value = obj }
/// pass the JSON object for another instance
public init(_ json:JSON){ self._value = json._value }
}
/// class properties
extension JSON {
public typealias NSNull = Foundation.NSNull
public typealias NSError = Foundation.NSError
public class var null:NSNull { return NSNull() }
/// constructs JSON object from data
public convenience init(data:NSData) {
var err:NSError?
var obj:AnyObject? = NSJSONSerialization.JSONObjectWithData(
data, options:nil, error:&err
)
self.init(err != nil ? err! : obj!)
}
/// constructs JSON object from string
public convenience init(string:String) {
let enc:NSStringEncoding = NSUTF8StringEncoding
self.init(data: string.dataUsingEncoding(enc)!)
}
/// parses string to the JSON object
/// same as JSON(string:String)
public class func parse(string:String)->JSON {
return JSON(string:string)
}
/// constructs JSON object from the content of NSURL
public convenience init(nsurl:NSURL) {
var enc:NSStringEncoding = NSUTF8StringEncoding
var err:NSError?
let str:String? =
NSString(
contentsOfURL:nsurl, usedEncoding:&enc, error:&err
) as String?
if err != nil { self.init(err!) }
else { self.init(string:str!) }
}
/// fetch the JSON string from NSURL and parse it
/// same as JSON(nsurl:NSURL)
public class func fromNSURL(nsurl:NSURL) -> JSON {
return JSON(nsurl:nsurl)
}
/// constructs JSON object from the content of URL
public convenience init(url:String) {
if let nsurl = NSURL(string:url) as NSURL? {
self.init(nsurl:nsurl)
} else {
self.init(NSError(
domain:"JSONErrorDomain",
code:400,
userInfo:[NSLocalizedDescriptionKey: "malformed URL"]
)
)
}
}
/// fetch the JSON string from URL in the string
public class func fromURL(url:String) -> JSON {
return JSON(url:url)
}
/// does what JSON.stringify in ES5 does.
/// when the 2nd argument is set to true it pretty prints
public class func stringify(obj:AnyObject, pretty:Bool=false) -> String! {
if !NSJSONSerialization.isValidJSONObject(obj) {
JSON(NSError(
domain:"JSONErrorDomain",
code:422,
userInfo:[NSLocalizedDescriptionKey: "not an JSON object"]
))
return nil
}
return JSON(obj).toString(pretty:pretty)
}
}
/// instance properties
extension JSON {
/// access the element like array
public subscript(idx:Int) -> JSON {
switch _value {
case let err as NSError:
return self
case let ary as NSArray:
if 0 <= idx && idx < ary.count {
return JSON(ary[idx])
}
return JSON(NSError(
domain:"JSONErrorDomain", code:404, userInfo:[
NSLocalizedDescriptionKey:
"[\(idx)] is out of range"
]))
default:
return JSON(NSError(
domain:"JSONErrorDomain", code:500, userInfo:[
NSLocalizedDescriptionKey: "not an array"
]))
}
}
/// access the element like dictionary
public subscript(key:String)->JSON {
switch _value {
case let err as NSError:
return self
case let dic as NSDictionary:
if let val:AnyObject = dic[key] { return JSON(val) }
return JSON(NSError(
domain:"JSONErrorDomain", code:404, userInfo:[
NSLocalizedDescriptionKey:
"[\"\(key)\"] not found"
]))
default:
return JSON(NSError(
domain:"JSONErrorDomain", code:500, userInfo:[
NSLocalizedDescriptionKey: "not an object"
]))
}
}
/// access json data object
public var data:AnyObject? {
return self.isError ? nil : self._value
}
/// Gives the type name as string.
/// e.g. if it returns "Double"
/// .asDouble returns Double
public var type:String {
switch _value {
case is NSError: return "NSError"
case is NSNull: return "NSNull"
case let o as NSNumber:
switch String.fromCString(o.objCType)! {
case "c", "C": return "Bool"
case "q", "l", "i", "s": return "Int"
case "Q", "L", "I", "S": return "UInt"
default: return "Double"
}
case is NSString: return "String"
case is NSArray: return "Array"
case is NSDictionary: return "Dictionary"
default: return "NSError"
}
}
/// check if self is NSError
public var isError: Bool { return _value is NSError }
/// check if self is NSNull
public var isNull: Bool { return _value is NSNull }
/// check if self is Bool
public var isBool: Bool { return type == "Bool" }
/// check if self is Int
public var isInt: Bool { return type == "Int" }
/// check if self is UInt
public var isUInt: Bool { return type == "UInt" }
/// check if self is Double
public var isDouble: Bool { return type == "Double" }
/// check if self is any type of number
public var isNumber: Bool {
if let o = _value as? NSNumber {
let t = String.fromCString(o.objCType)!
return t != "c" && t != "C"
}
return false
}
/// check if self is String
public var isString: Bool { return _value is NSString }
/// check if self is Array
public var isArray: Bool { return _value is NSArray }
/// check if self is Dictionary
public var isDictionary: Bool { return _value is NSDictionary }
/// check if self is a valid leaf node.
public var isLeaf: Bool {
return !(isArray || isDictionary || isError)
}
/// gives NSError if it holds the error. nil otherwise
public var asError:NSError? {
return _value as? NSError
}
/// gives NSNull if self holds it. nil otherwise
public var asNull:NSNull? {
return _value is NSNull ? JSON.null : nil
}
/// gives Bool if self holds it. nil otherwise
public var asBool:Bool? {
switch _value {
case let o as NSNumber:
switch String.fromCString(o.objCType)! {
case "c", "C": return Bool(o.boolValue)
default:
return nil
}
default: return nil
}
}
/// gives Int if self holds it. nil otherwise
public var asInt:Int? {
switch _value {
case let o as NSNumber:
switch String.fromCString(o.objCType)! {
case "c", "C":
return nil
default:
return Int(o.longLongValue)
}
default: return nil
}
}
/// gives Double if self holds it. nil otherwise
public var asDouble:Double? {
switch _value {
case let o as NSNumber:
switch String.fromCString(o.objCType)! {
case "c", "C":
return nil
default:
return Double(o.doubleValue)
}
default: return nil
}
}
// an alias to asDouble
public var asNumber:Double? { return asDouble }
/// gives String if self holds it. nil otherwise
public var asString:String? {
switch _value {
case let o as NSString:
return o as String
default: return nil
}
}
/// if self holds NSArray, gives a [JSON]
/// with elements therein. nil otherwise
public var asArray:[JSON]? {
switch _value {
case let o as NSArray:
var result = [JSON]()
for v:AnyObject in o { result.append(JSON(v)) }
return result
default:
return nil
}
}
/// if self holds NSDictionary, gives a [String:JSON]
/// with elements therein. nil otherwise
public var asDictionary:[String:JSON]? {
switch _value {
case let o as NSDictionary:
var result = [String:JSON]()
for (k:AnyObject, v:AnyObject) in o {
result[k as! String] = JSON(v)
}
return result
default: return nil
}
}
/// Yields date from string
public var asDate:NSDate? {
if let dateString = _value as? NSString {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZ"
return dateFormatter.dateFromString(dateString as String)
}
return nil
}
/// gives the number of elements if an array or a dictionary.
/// you can use this to check if you can iterate.
public var length:Int {
switch _value {
case let o as NSArray: return o.count
case let o as NSDictionary: return o.count
default: return 0
}
}
}
extension JSON : SequenceType {
public func generate()->GeneratorOf<(AnyObject,JSON)> {
switch _value {
case let o as NSArray:
var i = -1
return GeneratorOf<(AnyObject, JSON)> {
if ++i == o.count { return nil }
return (i, JSON(o[i]))
}
case let o as NSDictionary:
var ks = o.allKeys.reverse()
return GeneratorOf<(AnyObject, JSON)> {
if ks.isEmpty { return nil }
let k = ks.removeLast() as! String
return (k, JSON(o.valueForKey(k)!))
}
default:
return GeneratorOf<(AnyObject, JSON)>{ nil }
}
}
public func mutableCopyOfTheObject() -> AnyObject {
return _value.mutableCopy()
}
}
extension JSON : Printable {
/// stringifies self.
/// if pretty:true it pretty prints
public func toString(pretty:Bool=false)->String {
switch _value {
case is NSError: return "\(_value)"
case is NSNull: return "null"
case let o as NSNumber:
switch String.fromCString(o.objCType)! {
case "c", "C":
return o.boolValue.description
case "q", "l", "i", "s":
return o.longLongValue.description
case "Q", "L", "I", "S":
return o.unsignedLongLongValue.description
default:
switch o.doubleValue {
case 0.0/0.0: return "0.0/0.0" // NaN
case -1.0/0.0: return "-1.0/0.0" // -infinity
case +1.0/0.0: return "+1.0/0.0" // infinity
default:
return o.doubleValue.description
}
}
case let o as NSString:
return o.debugDescription
default:
let opts = pretty
? NSJSONWritingOptions.PrettyPrinted : nil
if let data = NSJSONSerialization.dataWithJSONObject(
_value, options:opts, error:nil
) as NSData? {
if let nsstring = NSString(
data:data, encoding:NSUTF8StringEncoding
) as NSString? {
return nsstring as String
}
}
return "YOU ARE NOT SUPPOSED TO SEE THIS!"
}
}
public var description:String { return toString() }
}
| mpl-2.0 | a8edbb256784a8668bf612eac9f25c0b | 32.765714 | 78 | 0.551701 | 4.527969 | false | false | false | false |
bugitapp/bugit | bugit/Extensions/xDate.swift | 1 | 3179 | //
// xUIColor.swift
//
// Created by Ernest on 9/20/16.
// Copyright © 2016 Purpleblue Pty Ltd. All rights reserved.
//
import UIKit
extension Date {
/*
How to use:
let date1 = Calendar.current.date(era: 1, year: 2014, month: 11, day: 28, hour: 5, minute: 9, second: 0, nanosecond: 0)!
let date2 = Calendar.current.date(era: 1, year: 2015, month: 8, day: 28, hour: 5, minute: 9, second: 0, nanosecond: 0)!
let years = date2.years(from: date1) // 0
let months = date2.months(from: date1) // 9
let weeks = date2.weeks(from: date1) // 39
let days = date2.days(from: date1) // 273
let hours = date2.hours(from: date1) // 6,553
let minutes = date2.minutes(from: date1) // 393,180
let seconds = date2.seconds(from: date1) // 23,590,800
let timeOffset = date2.offset(from: date1) // "9M"
let date3 = Calendar.current.date(era: 1, year: 2014, month: 11, day: 28, hour: 5, minute: 9, second: 0, nanosecond: 0)!
let date4 = Calendar.current.date(era: 1, year: 2015, month: 11, day: 28, hour: 5, minute: 9, second: 0, nanosecond: 0)!
let timeOffset2 = date4.offset(from: date3) // "1y"
*/
// Returns the amount of years from another date
func years(from date: Date) -> Int {
return Calendar.current.dateComponents([.year], from: date, to: self).year ?? 0
}
// Returns the amount of months from another date
func months(from date: Date) -> Int {
return Calendar.current.dateComponents([.month], from: date, to: self).month ?? 0
}
// Returns the amount of weeks from another date
func weeks(from date: Date) -> Int {
return Calendar.current.dateComponents([.weekOfYear], from: date, to: self).weekOfYear ?? 0
}
// Returns the amount of days from another date
func days(from date: Date) -> Int {
return Calendar.current.dateComponents([.day], from: date, to: self).day ?? 0
}
// Returns the amount of hours from another date
func hours(from date: Date) -> Int {
return Calendar.current.dateComponents([.hour], from: date, to: self).hour ?? 0
}
// Returns the amount of minutes from another date
func minutes(from date: Date) -> Int {
return Calendar.current.dateComponents([.minute], from: date, to: self).minute ?? 0
}
// Returns the amount of seconds from another date
func seconds(from date: Date) -> Int {
return Calendar.current.dateComponents([.second], from: date, to: self).second ?? 0
}
// Returns the a custom time interval description from another date
func offset(from date: Date) -> String {
if years(from: date) > 0 { return "\(years(from: date))y" }
if months(from: date) > 0 { return "\(months(from: date))M" }
if weeks(from: date) > 0 { return "\(weeks(from: date))w" }
if days(from: date) > 0 { return "\(days(from: date))d" }
if hours(from: date) > 0 { return "\(hours(from: date))h" }
if minutes(from: date) > 0 { return "\(minutes(from: date))m" }
if seconds(from: date) > 0 { return "\(seconds(from: date))s" }
return ""
}
}
| apache-2.0 | bcd6cb6dc97d47d331f2acd62e6afb13 | 38.234568 | 121 | 0.612335 | 3.5 | false | false | false | false |
optimizely/swift-sdk | Sources/Optimizely/OptimizelyError.swift | 1 | 10717 | //
// Copyright 2019-2021, Optimizely, Inc. and contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
public enum OptimizelyError: Error {
case generic
// MARK: - Decision errors
case sdkNotReady
case featureKeyInvalid(_ key: String)
case variableValueInvalid(_ key: String)
case invalidJSONVariable
// MARK: - Experiment
case experimentKeyInvalid(_ key: String)
case experimentIdInvalid(_ id: String)
case experimentHasNoTrafficAllocation(_ key: String)
case variationKeyInvalid(_ expKey: String, _ varKey: String)
case variationIdInvalid(_ expKey: String, _ varKey: String)
case variationUnknown(_ userId: String, _ key: String)
case variableKeyInvalid(_ varKey: String, _ feature: String)
case eventKeyInvalid(_ key: String)
case eventBuildFailure(_ key: String)
case eventTagsFormatInvalid
case attributesKeyInvalid(_ key: String)
case attributeValueInvalid(_ key: String)
case attributeFormatInvalid
case groupIdInvalid(_ id: String)
case groupHasNoTrafficAllocation(_ key: String)
case rolloutIdInvalid(_ id: String, _ feature: String)
// MARK: - Audience Evaluation
case conditionNoMatchingAudience(_ id: String)
case conditionInvalidFormat(_ hint: String)
case conditionCannotBeEvaluated(_ hint: String)
case evaluateAttributeInvalidCondition(_ condition: String)
case evaluateAttributeInvalidType(_ condition: String, _ value: Any, _ key: String)
case evaluateAttributeValueOutOfRange(_ condition: String, _ key: String)
case evaluateAttributeInvalidFormat(_ hint: String)
case userAttributeInvalidType(_ condition: String)
case userAttributeInvalidMatch(_ condition: String)
case userAttributeNilValue(_ condition: String)
case userAttributeInvalidName(_ condition: String)
case nilAttributeValue(_ condition: String, _ key: String)
case missingAttributeValue(_ condition: String, _ key: String)
// MARK: - Bucketing
case userIdInvalid
case bucketingIdInvalid(_ id: UInt64)
case userProfileInvalid
// MARK: - Datafile Errors
case datafileDownloadFailed(_ hint: String)
case dataFileInvalid
case dataFileVersionInvalid(_ version: String)
case datafileSavingFailed(_ hint: String)
case datafileLoadingFailed(_ hint: String)
// MARK: - EventDispatcher Errors
case eventDispatchFailed(_ reason: String)
case eventDispatcherConfigError(_ reason: String)
// MARK: - AudienceSegements Errors
case invalidSegmentIdentifier
case fetchSegmentsFailed(_ hint: String)
case odpEventFailed(_ hint: String, _ canRetry: Bool)
case odpNotIntegrated
case odpNotEnabled
case odpInvalidData
}
// MARK: - CustomStringConvertible
extension OptimizelyError: CustomStringConvertible, ReasonProtocol {
public var description: String {
return "[Optimizely][Error] " + self.reason
}
public var localizedDescription: String {
return description
}
var reason: String {
var message: String
switch self {
case .generic: message = "Unknown reason."
// DO NOT CHANGE these critical error messages - FSC will validate exact-wordings of these messages.
case .sdkNotReady: message = "Optimizely SDK not configured properly yet."
case .featureKeyInvalid(let key): message = "No flag was found for key \"\(key)\"."
case .variableValueInvalid(let key): message = "Variable value for key \"\(key)\" is invalid or wrong type."
case .invalidJSONVariable: message = "Invalid variables for OptimizelyJSON."
// These error messages not validated by FSC
case .experimentKeyInvalid(let key): message = "Experiment key (\(key)) is not in datafile. It is either invalid, paused, or archived."
case .experimentIdInvalid(let id): message = "Experiment ID (\(id)) is not in datafile."
case .experimentHasNoTrafficAllocation(let key): message = "No traffic allocation rules are defined for experiment (\(key))."
case .variationKeyInvalid(let expKey, let varKey): message = "No variation key (\(varKey)) defined in datafile for experiment (\(expKey))."
case .variationIdInvalid(let expKey, let varId): message = "No variation ID (\(varId)) defined in datafile for experiment (\(expKey))."
case .variationUnknown(let userId, let key): message = "User (\(userId)) does not meet conditions to be in experiment/feature (\(key))."
case .variableKeyInvalid(let varKey, let feature): message = "Variable with key (\(varKey)) associated with feature with key (\(feature)) is not in datafile."
case .eventKeyInvalid(let key): message = "Event key (\(key)) is not in datafile."
case .eventBuildFailure(let key): message = "Failed to create a dispatch event (\(key))"
case .eventTagsFormatInvalid: message = "Provided event tags are in an invalid format."
case .attributesKeyInvalid(let key): message = "Attribute key (\(key)) is not in datafile."
case .attributeValueInvalid(let key): message = "Attribute value for (\(key)) is invalid."
case .attributeFormatInvalid: message = "Provided attributes are in an invalid format."
case .groupIdInvalid(let id): message = "Group ID (\(id)) is not in datafile."
case .groupHasNoTrafficAllocation(let id): message = "No traffic allocation rules are defined for group (\(id))."
case .rolloutIdInvalid(let id, let feature): message = "Invalid rollout ID (\(id)) attached to feature (\(feature))."
case .conditionNoMatchingAudience(let id): message = "Audience (\(id)) is not in datafile."
case .conditionInvalidFormat(let hint): message = "Condition has an invalid format (\(hint))."
case .conditionCannotBeEvaluated(let hint): message = "Condition cannot be evaluated (\(hint))."
case .evaluateAttributeInvalidCondition(let condition): message = "Audience condition (\(condition)) has an unsupported condition value. You may need to upgrade to a newer release of the Optimizely SDK."
case .evaluateAttributeInvalidType(let condition, let value, let key): message = "Audience condition (\(condition)) evaluated to UNKNOWN because a value of type (\(value)) was passed for user attribute (\(key))."
case .evaluateAttributeValueOutOfRange(let condition, let key): message = "Audience condition (\(condition)) evaluated to UNKNOWN because the number value for user attribute (\(key)) is not in the range [-2^53, +2^53]."
case .evaluateAttributeInvalidFormat(let hint): message = "Evaluation attribute has an invalid format (\(hint))."
case .userAttributeInvalidType(let condition): message = "Audience condition (\(condition)) uses an unknown condition type. You may need to upgrade to a newer release of the Optimizely SDK."
case .userAttributeInvalidMatch(let condition): message = "Audience condition (\(condition)) uses an unknown match type. You may need to upgrade to a newer release of the Optimizely SDK."
case .userAttributeNilValue(let condition): message = "Audience condition (\(condition)) evaluated to UNKNOWN because of null value."
case .userAttributeInvalidName(let condition): message = "Audience condition (\(condition)) evaluated to UNKNOWN because of invalid attribute name."
case .nilAttributeValue(let condition, let key): message = "Audience condition (\(condition)) evaluated to UNKNOWN because a null value was passed for user attribute (\(key))."
case .missingAttributeValue(let condition, let key): message = "Audience condition (\(condition)) evaluated to UNKNOWN because no value was passed for user attribute (\(key))."
case .userIdInvalid: message = "Provided user ID is in an invalid format."
case .bucketingIdInvalid(let id): message = "Invalid bucketing ID (\(id))."
case .userProfileInvalid: message = "Provided user profile object is invalid."
case .datafileDownloadFailed(let hint): message = "Datafile download failed (\(hint))."
case .dataFileInvalid: message = "Provided datafile is in an invalid format."
case .dataFileVersionInvalid(let version): message = "Provided datafile version (\(version)) is not supported."
case .datafileSavingFailed(let hint): message = "Datafile save failed (\(hint))."
case .datafileLoadingFailed(let hint): message = "Datafile load failed (\(hint))."
case .eventDispatchFailed(let hint): message = "Event dispatch failed (\(hint))."
case .eventDispatcherConfigError(let hint): message = "EventDispatcher config error (\(hint))."
case .invalidSegmentIdentifier: message = "Audience segments fetch failed (invalid identifier)"
case .fetchSegmentsFailed(let hint): message = "Audience segments fetch failed (\(hint))."
case .odpEventFailed(let hint, _): message = "ODP event send failed (\(hint))."
case .odpNotIntegrated: message = "ODP is not integrated."
case .odpNotEnabled: message = "ODP is not enabled."
case .odpInvalidData: message = "ODP data is not valid."
}
return message
}
}
// MARK: - LocalizedError (ObjC NSError)
extension OptimizelyError: LocalizedError {
public var errorDescription: String? {
return self.reason
}
}
| apache-2.0 | 91db27c2c871e8655a1b1ccca69eeab7 | 59.207865 | 229 | 0.65606 | 5.057574 | false | false | false | false |
huangboju/Moots | Examples/SwiftUI/Scrumdinger/Scrumdinger/ScrumsView.swift | 1 | 2130 | //
// ScrumsView.swift
// Scrumdinger
//
// Created by 黄伯驹 on 2020/12/25.
//
import SwiftUI
struct ScrumsView: View {
@Binding var scrums: [DailyScrum]
@Environment(\.scenePhase) private var scenePhase
@State private var isPresented = false
@State private var newScrumData = DailyScrum.Data()
let saveAction: () -> Void
var body: some View {
List {
ForEach(scrums) { scrum in
NavigationLink(destination: DetailView(scrum: binding(for: scrum))) {
CardView(scrum: scrum)
}
.listRowBackground(scrum.color)
}
}
.navigationTitle("Daily Scrums")
.navigationBarItems(trailing: Button(action: {
isPresented = true
}) {
Image(systemName: "plus")
})
.sheet(isPresented: $isPresented) {
NavigationView {
EditView(scrumData: $newScrumData)
.navigationBarItems(leading: Button("dismiss") {
isPresented = false
}, trailing: Button("Add") {
let newScrum = DailyScrum(title: newScrumData.title, attendees: newScrumData.attendees,
lengthInMinutes: Int(newScrumData.lengthInMinutes), color: newScrumData.color)
scrums.append(newScrum)
isPresented = false
})
}
}
.onChange(of: scenePhase) { phase in
if phase == .inactive { saveAction() }
}
}
private func binding(for scrum: DailyScrum) -> Binding<DailyScrum> {
guard let scrumIndex = scrums.firstIndex(where: { $0.id == scrum.id }) else {
fatalError("Can't find scrum in array")
}
return $scrums[scrumIndex]
}
}
struct ScrumsView_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
ScrumsView(scrums: .constant(DailyScrum.data)) {
}
}
}
}
| mit | 4790bb3a192babe170dad046afbc6f4e | 31.181818 | 152 | 0.525895 | 4.45283 | false | false | false | false |
jeffreybergier/FruitKey | FruitKey/AppDelegate.swift | 1 | 8865 | //
// AppDelegate.swift
// FruitKey
//
// Created by Jeffrey Bergier on 10/29/14.
//
// The MIT License (MIT)
//
// Copyright (c) 2014 Jeffrey Bergier
//
// 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
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
private let applicationName = NSLocalizedString("FruitKey: ", comment: "Title of the Application that appears in the navigation bar. should be followed by a : and a space")
private var howToUseViewController: LoopingMoviePlayerController?
private var howToInstallViewController: LoopingMoviePlayerController?
private var aboutTableViewController: AboutTableViewController?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
//how to use video
let howToUsePath = NSBundle.mainBundle().pathForResource("howToUseVideo", ofType: "mp4")
if let howToUsePath = howToUsePath {
let howToUseURL = NSURL(fileURLWithPath: howToUsePath)
if let howToUseURL = howToUseURL {
let titleString = NSLocalizedString("How to Use", comment: "How to use appears in the tab bar controller and is where the user finds out how to use the app")
let tabBarImage = UIImage(named: "tabBar2")
howToUseViewController = LoopingMoviePlayerController(contentURL: howToUseURL)
howToUseViewController?.title = self.applicationName + titleString
if let tabBarImage = tabBarImage {
tabBarImage.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
howToUseViewController?.tabBarItem = UITabBarItem(title: titleString, image: tabBarImage, tag: 1)
}
}
}
//how to install view
let howToInstallPath = NSBundle.mainBundle().pathForResource("howToInstallVideo", ofType: "mp4")
if let howToInstallPath = howToInstallPath {
let howToInstallURL = NSURL(fileURLWithPath: howToInstallPath)
if let howToInstallURL = howToInstallURL {
let titleString = NSLocalizedString("How to Install", comment: "How to install appears in the tab bar controller and is where the user finds out how to install the keyboard")
let tabBarImage = UIImage(named: "tabBar1")
howToInstallViewController = LoopingMoviePlayerController(contentURL: howToInstallURL)
howToInstallViewController?.title = self.applicationName + titleString
if let tabBarImage = tabBarImage {
tabBarImage.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
howToInstallViewController?.tabBarItem = UITabBarItem(title: titleString, image: tabBarImage, tag: 0)
}
}
}
//about screen from storyboard
let aboutStoryboard: UIStoryboard? = UIStoryboard(name: "AboutTableViewController", bundle: nil)
if let aboutStoryboard = aboutStoryboard {
self.aboutTableViewController = aboutStoryboard.instantiateInitialViewController() as? AboutTableViewController
if let aboutTableViewController = self.aboutTableViewController {
let titleString = NSLocalizedString("About", comment: "About appears in the tab bar controller and is where the user finds out about the company that made the app")//"About"
let tabBarImage = UIImage(named: "tabBar3")
aboutTableViewController.title = self.applicationName + titleString
if let tabBarImage = tabBarImage {
tabBarImage.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
aboutTableViewController.tabBarItem = UITabBarItem(title: titleString, image: tabBarImage, tag: 3)
}
}
}
// create an empty array that I can add View Controller objects into
// this helps increase reliability because each view controller is optional
// this allows me to unwrap the optionals 1 at a time instead of 3 at once.
// It increases reliability of the the root view controller loading even if something went wrong with one of the optionals.
var tabBarControllerArray: [UINavigationController] = []
//check all the optionals and add them into the array
if let howToInstallViewController = self.howToInstallViewController {
let howToInstallNavigationController = FKNavigationController(rootViewController: howToInstallViewController)
tabBarControllerArray.append(howToInstallNavigationController)
}
if let howToUseViewController = self.howToUseViewController {
let howToUseNavigationController = FKNavigationController(rootViewController: howToUseViewController)
tabBarControllerArray.append(howToUseNavigationController)
}
if let aboutTableViewController = self.aboutTableViewController {
let aboutTableViewNavigationController = FKNavigationController(rootViewController: aboutTableViewController)
tabBarControllerArray.append(aboutTableViewNavigationController)
}
//set up the tab bar controller with the populated array
let tabBarController = FKTabBarController()
if tabBarControllerArray.count > 0 {
tabBarController.viewControllers = tabBarControllerArray
}
//set up the rootview controller
self.window?.rootViewController = tabBarController
//set the window background color
self.window?.backgroundColor = UIColor.whiteColor()
//make the window visible
self.window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit | ee6ccefa2a5139b3976505f237cbe8b9 | 52.727273 | 285 | 0.700959 | 5.760234 | false | false | false | false |
flockoffiles/FFDataWrapper | FFDataWrapper/FFDataWrapper+Mapping.swift | 1 | 4070 | //
// FFDataWrapper+Mapping.swift
// FFDataWrapper
//
// Created by Sergey Novitsky on 19/02/2019.
// Copyright © 2019 Flock of Files. All rights reserved.
//
import Foundation
extension FFDataWrapper {
/// Execute the given closure with wrapped data.
/// If you used InfoCoder when you created the wrapper, you should use the second version of mapData to pass extra info.
/// Data is converted back from its internal representation and is wiped after the closure is completed.
/// Wiping of the data will succeed ONLY if the data is not passed outside the closure (i.e. if there are no additional references to it
/// by the time the closure completes).
/// - Parameter block: The closure to execute.
@discardableResult
public func mapData<ResultType>(_ block: (inout Data) throws -> ResultType) rethrows -> ResultType {
var decodedData = Data(repeating:0, count: dataRef.dataBuffer.count)
let count = decodedData.withUnsafeMutableBytes({ (destPtr: UnsafeMutablePointer<UInt8>) -> Int in
switch self.storedCoders {
case .coders(_, let decoder):
decoder(UnsafeBufferPointer(start: self.dataRef.dataBuffer.baseAddress!, count: dataRef.dataBuffer.count),
UnsafeMutableBufferPointer(start: destPtr, count: dataRef.dataBuffer.count))
return dataRef.dataBuffer.count
case .infoCoders(_, let decoder):
decoder(UnsafeBufferPointer(start: self.dataRef.dataBuffer.baseAddress!, count: dataRef.dataBuffer.count),
UnsafeMutableBufferPointer(start: destPtr, count: dataRef.dataBuffer.count), nil)
return dataRef.dataBuffer.count
}
})
// Must NOT grow the buffer of decodedData (only shrink)
if count < decodedData.count {
decodedData.count = count
}
let result = try block(&decodedData)
decodedData.resetBytes(in: 0 ..< decodedData.count)
return result
}
/// Execute the given closure with wrapped data.
/// This version takes some extra info and passes it to the decoder in case InfoCoder was used.
/// Data is converted back from its internal representation and is wiped after the closure is completed.
/// Wiping of the data will succeed ONLY if the data is not passed outside the closure (i.e. if there are no additional references to it
/// by the time the closure completes).
/// - Parameter info: Extra info to pass to the decoder in case InfoCoder is being used.
/// - Parameter block: The closure to execute.
@discardableResult
public func mapData<ResultType>(info: Any?, block: (inout Data) throws -> ResultType) rethrows -> ResultType {
var decodedData = Data(repeating:0, count: dataRef.dataBuffer.count)
decodedData.withUnsafeMutableBytes({ (destPtr: UnsafeMutablePointer<UInt8>) -> Void in
switch self.storedCoders {
case .coders(_, let decoder):
decoder(UnsafeBufferPointer(start: self.dataRef.dataBuffer.baseAddress!, count: dataRef.dataBuffer.count),
UnsafeMutableBufferPointer(start: destPtr, count: dataRef.dataBuffer.count))
case .infoCoders(_, let decoder):
decoder(UnsafeBufferPointer(start: self.dataRef.dataBuffer.baseAddress!, count: dataRef.dataBuffer.count),
UnsafeMutableBufferPointer(start: destPtr, count: dataRef.dataBuffer.count), info)
}
})
let result = try block(&decodedData)
decodedData.resetBytes(in: 0 ..< decodedData.count)
return result
}
/// Will be deprecated soon. Please use mapData instead.
@available(*, deprecated, message: "This method is deprecated. Please use mapData instead")
@discardableResult
public func withDecodedData<ResultType>(_ block: (inout Data) throws -> ResultType) rethrows -> ResultType {
return try mapData(block)
}
}
| mit | c710ccc2037dec6b29f6d23ab62d0a06 | 49.8625 | 140 | 0.665028 | 5.098997 | false | false | false | false |
norwoood/swiftBook | coreData/Camera/Camera/Datasourse/TableViewDataSourse.swift | 1 | 5002 | //
// TableViewDataSourse.swift
// Camera
//
// Created by 郑清江 on 2017/8/8.
// Copyright © 2017年 zqj. All rights reserved.
//
import UIKit
import CoreData
protocol TableViewDataSourseDelegate {
associatedtype Object
associatedtype Cell: UITableViewCell
func config(cell: Cell, for object: Object)
var numberOfAdditionalRows: Int { get }
func supplementaryObject(at indexPath: IndexPath) -> Object?
func presentedIndexPath(for fetchedIndexPath: IndexPath) -> IndexPath
func fetchedIndexPath(for presentedIndexPath: IndexPath) -> IndexPath?
}
extension TableViewDataSourseDelegate{
var numberOfAdditionalRows: Int {
return 0
}
func supplementaryObject(at indexPath: IndexPath) -> Object? {
return nil
}
func presentedIndexPath(for fetchedIndexPath: IndexPath) -> IndexPath{
return fetchedIndexPath
}
func fetchedIndexPath(for presentedIndexPath: IndexPath) -> IndexPath?{
return presentedIndexPath
}
}
class TableViewDataSourse<Result: NSFetchRequestResult, Delegate: TableViewDataSourseDelegate>: NSObject, UITableViewDataSource, NSFetchedResultsControllerDelegate {
typealias Object = Delegate.Object
typealias Cell = Delegate.Cell
required init(tableView: UITableView,
cellIdentifire: String,
fetchResultController: NSFetchedResultsController<Result>,
delegate: Delegate) {
self.delegate = delegate
self.tableView = tableView
self.cellIdent = cellIdentifire
self.fetchResultController = fetchResultController
super.init()
fetchResultController.delegate = self
try! fetchResultController.performFetch()
tableView.dataSource = self
tableView.reloadData()
}
var selectedObject: Object? {
guard let indexPath = tableView.indexPathForSelectedRow else {
return nil
}
return objectAtIndexPath(indexPath)
}
func objectAtIndexPath(_ indexPath: IndexPath) -> Object {
guard let fetchResultIndexPath = delegate.fetchedIndexPath(for: indexPath) else {
return delegate.supplementaryObject(at: indexPath)!
}
return (fetchResultController.object(at: fetchResultIndexPath) as! Object)
}
//MARK: - NSFetchResultControllerDelegate
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.beginUpdates()
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch type {
case .insert:
guard let indexPath = newIndexPath else { fatalError("indexPath can't be nil") }
tableView.insertRows(at: [indexPath], with: .fade)
case .delete:
guard let indexPath = indexPath else { fatalError("indexPath can't be nil") }
tableView.deleteRows(at: [indexPath], with: .fade)
case .move:
guard let indexPath = indexPath else { fatalError("indexPath can't be nil") }
guard let newIndexPath = newIndexPath else { fatalError("indexPath can't be nil") }
tableView.deleteRows(at: [indexPath], with: .fade)
tableView.insertRows(at: [newIndexPath], with: .fade)
case .update:
guard let indexPath = indexPath else { fatalError("indexpath can't be nil") }
let object = objectAtIndexPath(indexPath)
guard let cell = tableView.cellForRow(at: indexPath) as? Cell else { break }
delegate.config(cell: cell, for: object)
}
}
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.endUpdates()
}
//MARK: - Private
fileprivate let tableView: UITableView
fileprivate let fetchResultController: NSFetchedResultsController<Result>
fileprivate var delegate: Delegate
fileprivate let cellIdent: String
//MARK: - TableViewDataSourse
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let section = fetchResultController.sections?[section] else {
return 0
}
return section.numberOfObjects + delegate.numberOfAdditionalRows
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let object = objectAtIndexPath(indexPath)
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdent, for: indexPath) as? Cell else { fatalError("can't find cell") }
delegate.config(cell: cell, for: object)
return cell
}
}
| mit | 06a39b933281d091a0096648dbdd52ed | 32.736486 | 200 | 0.659924 | 5.585011 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Blockchain/FeatureApp/RootView/RootViewController+LoggedInBridge.swift | 1 | 16927 | // Copyright © 2021 Blockchain Luxembourg S.A. All rights reserved.
import Combine
import FeatureAppUI
import FeatureInterestUI
import FeatureOnboardingUI
import FeatureTransactionUI
import MoneyKit
import PlatformKit
import PlatformUIKit
import SwiftUI
import ToolKit
import UIComponentsKit
extension RootViewController: LoggedInBridge {
func alert(_ content: AlertViewContent) {
alertViewPresenter.notify(content: content, in: topMostViewController ?? self)
}
func presentPostSignUpOnboarding() {
onboardingRouter.presentPostSignUpOnboarding(from: self)
.receive(on: DispatchQueue.main)
.handleEvents(receiveOutput: { output in
"\(output)".peek("🏄")
})
.sink { [weak self] _ in
self?.dismiss(animated: true)
}
.store(in: &bag)
}
func presentPostSignInOnboarding() {
onboardingRouter.presentPostSignInOnboarding(from: self)
.handleEvents(receiveOutput: { output in
"\(output)".peek("🏄")
})
.sink { [weak self] result in
guard let self = self, self.presentedViewController != nil, result != .skipped else {
return
}
self.dismiss(animated: true)
}
.store(in: &bag)
}
func toggleSideMenu() {
dismiss(animated: true) { [self] in
viewStore.send(.enter(into: .account, context: .none))
}
}
func closeSideMenu() {
viewStore.send(.dismiss())
}
func send(from account: BlockchainAccount) {
transactionsRouter.presentTransactionFlow(to: .send(account, nil))
.sink { result in "\(result)".peek("🧾") }
.store(in: &bag)
}
func send(from account: BlockchainAccount, target: TransactionTarget) {
transactionsRouter.presentTransactionFlow(to: .send(account, target))
.sink { result in "\(result)".peek("🧾") }
.store(in: &bag)
}
func sign(from account: BlockchainAccount, target: TransactionTarget) {
transactionsRouter.presentTransactionFlow(
to: .sign(
sourceAccount: account,
destination: target
)
)
.sink { result in "\(result)".peek("🧾") }
.store(in: &bag)
}
func receive(into account: BlockchainAccount) {
transactionsRouter.presentTransactionFlow(to: .receive(account as? CryptoAccount))
.sink { result in "\(result)".peek("🧾") }
.store(in: &bag)
}
func withdraw(from account: BlockchainAccount) {
transactionsRouter.presentTransactionFlow(to: .withdraw(account as! FiatAccount))
.sink { result in "\(result)".peek("🧾") }
.store(in: &bag)
}
func deposit(into account: BlockchainAccount) {
transactionsRouter.presentTransactionFlow(to: .deposit(account as! FiatAccount))
.sink { result in "\(result)".peek("🧾") }
.store(in: &bag)
}
func interestTransfer(into account: BlockchainAccount) {
transactionsRouter.presentTransactionFlow(to: .interestTransfer(account as! CryptoInterestAccount))
.sink { result in "\(result)".peek("🧾") }
.store(in: &bag)
}
func interestWithdraw(from account: BlockchainAccount) {
transactionsRouter.presentTransactionFlow(to: .interestWithdraw(account as! CryptoInterestAccount))
.sink { result in "\(result)".peek("🧾") }
.store(in: &bag)
}
func switchTabToDashboard() {
app.post(event: blockchain.ux.home.tab[blockchain.ux.user.portfolio].select)
}
func switchToSend() {
handleSendCrypto()
}
func switchTabToSwap() {
handleSwapCrypto(account: nil)
}
func switchTabToReceive() {
handleReceiveCrypto()
}
func switchToActivity() {
app.post(event: blockchain.ux.home.tab[blockchain.ux.user.activity].select)
}
func switchToActivity(for currencyType: CurrencyType) {
app.post(event: blockchain.ux.home.tab[blockchain.ux.user.activity].select)
}
func showCashIdentityVerificationScreen() {
let presenter = CashIdentityVerificationPresenter()
let controller = CashIdentityVerificationViewController(presenter: presenter); do {
controller.transitioningDelegate = bottomSheetPresenter
controller.modalPresentationStyle = .custom
controller.isModalInPresentation = true
}
(topMostViewController ?? self).present(controller, animated: true, completion: nil)
}
func showFundTrasferDetails(fiatCurrency: FiatCurrency, isOriginDeposit: Bool) {
let interactor = InteractiveFundsTransferDetailsInteractor(
fiatCurrency: fiatCurrency
)
let webViewRouter = WebViewRouter(
topMostViewControllerProvider: self
)
let presenter = FundsTransferDetailScreenPresenter(
webViewRouter: webViewRouter,
interactor: interactor,
isOriginDeposit: isOriginDeposit
)
let viewController = DetailsScreenViewController(presenter: presenter)
let navigationController = UINavigationController(rootViewController: viewController)
presenter.backRelay.publisher
.sink { [weak navigationController] in
navigationController?.dismiss(animated: true)
}
.store(in: &bag)
topMostViewController?.present(navigationController, animated: true)
}
func handleSwapCrypto(account: CryptoAccount?) {
let transactionsRouter = transactionsRouter
let onboardingRouter = onboardingRouter
coincore.hasPositiveDisplayableBalanceAccounts(for: .crypto)
.receive(on: DispatchQueue.main)
.flatMap { positiveBalance -> AnyPublisher<TransactionFlowResult, Never> in
if !positiveBalance {
guard let viewController = UIApplication.shared.topMostViewController else {
fatalError("Top most view controller cannot be nil")
}
return onboardingRouter
.presentRequiredCryptoBalanceView(from: viewController)
.map(TransactionFlowResult.init)
.eraseToAnyPublisher()
} else {
return transactionsRouter.presentTransactionFlow(to: .swap(account))
}
}
.sink { result in
"\(result)".peek("🧾 \(#function)")
}
.store(in: &bag)
}
func handleSendCrypto() {
transactionsRouter.presentTransactionFlow(to: .send(nil, nil))
.sink { result in
"\(result)".peek("🧾 \(#function)")
}
.store(in: &bag)
}
func handleReceiveCrypto() {
transactionsRouter.presentTransactionFlow(to: .receive(nil))
.sink { result in
"\(result)".peek("🧾 \(#function)")
}
.store(in: &bag)
}
func handleSellCrypto(account: CryptoAccount?) {
transactionsRouter.presentTransactionFlow(to: .sell(account))
.sink { result in
"\(result)".peek("🧾 \(#function)")
}
.store(in: &bag)
}
func handleBuyCrypto(account: CryptoAccount?) {
transactionsRouter.presentTransactionFlow(to: .buy(account))
.sink { result in
"\(result)".peek("🧾 \(#function)")
}
.store(in: &bag)
}
func handleBuyCrypto() {
handleBuyCrypto(currency: .bitcoin)
}
func handleBuyCrypto(currency: CryptoCurrency) {
guard app.currentMode != .defi else {
showBuyCryptoOpenTradingAccount()
return
}
coincore
.cryptoAccounts(for: currency, supporting: .buy, filter: .custodial)
.receive(on: DispatchQueue.main)
.map(\.first)
.sink(to: My.handleBuyCrypto(account:), on: self)
.store(in: &bag)
}
private func currentFiatAccount() -> AnyPublisher<FiatAccount, CoincoreError> {
fiatCurrencyService.displayCurrencyPublisher
.flatMap { [coincore] currency in
coincore.allAccounts(filter: .all)
.map { group in
group.accounts
.first { account in
account.currencyType.code == currency.code
}
.flatMap { account in
account as? FiatAccount
}
}
.first()
}
.compactMap { $0 }
.eraseToAnyPublisher()
}
func handleDeposit() {
currentFiatAccount()
.sink(to: My.deposit(into:), on: self)
.store(in: &bag)
}
func handleWithdraw() {
currentFiatAccount()
.sink(to: My.withdraw(from:), on: self)
.store(in: &bag)
}
func handleRewards() {
let interestAccountList = InterestAccountListHostingController(embeddedInNavigationView: true)
interestAccountList.delegate = self
topMostViewController?.present(
interestAccountList,
animated: true
)
}
func handleNFTAssetView() {
topMostViewController?.present(
AssetListHostingViewController(),
animated: true
)
}
func handleSupport() {
let isSupported = app.publisher(for: blockchain.app.configuration.customer.support.is.enabled, as: Bool.self)
.prefix(1)
.replaceError(with: false)
Publishers.Zip(
isSupported,
eligibilityService.isEligiblePublisher
)
.receive(on: DispatchQueue.main)
.sink(receiveValue: { [weak self] isSupported, isEligible in
guard let self = self else { return }
guard isEligible, isSupported else {
return self.showLegacySupportAlert()
}
self.showCustomerChatSupportIfSupported()
})
.store(in: &bag)
}
private func showCustomerChatSupportIfSupported() {
tiersService
.fetchTiers()
.receive(on: DispatchQueue.main)
.sink(
receiveCompletion: { [weak self] completion in
guard let self = self else { return }
switch completion {
case .failure(let error):
"\(error)".peek(as: .error, "‼️")
self.showLegacySupportAlert()
case .finished:
break
}
},
receiveValue: { [app] tiers in
guard tiers.isTier2Approved else {
self.showLegacySupportAlert()
return
}
app.post(event: blockchain.ux.customer.support.show.messenger)
}
)
.store(in: &bag)
}
private func showLegacySupportAlert() {
alert(
.init(
title: String(format: LocalizationConstants.openArg, Constants.Url.blockchainSupport),
message: LocalizationConstants.youWillBeLeavingTheApp,
actions: [
UIAlertAction(title: LocalizationConstants.continueString, style: .default) { _ in
guard let url = URL(string: Constants.Url.blockchainSupport) else { return }
UIApplication.shared.open(url)
},
UIAlertAction(title: LocalizationConstants.cancel, style: .cancel)
]
)
)
}
private func showBuyCryptoOpenTradingAccount() {
let view = DefiBuyCryptoMessageView {
app.state.set(blockchain.app.mode, to: AppMode.trading.rawValue)
}
let viewController = UIHostingController(rootView: view)
viewController.transitioningDelegate = bottomSheetPresenter
viewController.modalPresentationStyle = .custom
present(viewController, animated: true, completion: nil)
}
func startBackupFlow() {
backupRouter.start()
}
func showSettingsView() {
viewStore.send(.enter(into: .account, context: .none))
}
func reload() {
accountsAndAddressesNavigationController?.reload()
}
func presentKYCIfNeeded() {
dismiss(animated: true) { [self] in
kycRouter
.presentKYCIfNeeded(
from: topMostViewController ?? self,
requiredTier: .tier2
)
.mapToResult()
.receive(on: DispatchQueue.main)
.sink(receiveValue: { [weak self] result in
switch result {
case .success(let kycRoutingResult):
guard case .completed = kycRoutingResult else { return }
// Upon successful KYC completion, present Interest
self?.handleRewards()
case .failure(let kycRoutingError):
Logger.shared.error(kycRoutingError)
}
})
.store(in: &bag)
}
}
func presentBuyIfNeeded(_ cryptoCurrency: CryptoCurrency) {
dismiss(animated: true) { [self] in
handleBuyCrypto(currency: cryptoCurrency)
}
}
func enableBiometrics() {
let logout = { [weak self] () -> Void in
self?.global.send(.logout)
}
let flow = PinRouting.Flow.enableBiometrics(
parent: UnretainedContentBox<UIViewController>(topMostViewController ?? self),
logoutRouting: logout
)
pinRouter = PinRouter(flow: flow) { [weak self] input in
guard let password = input.password else { return }
self?.global.send(.wallet(.authenticateForBiometrics(password: password)))
self?.pinRouter = nil
}
pinRouter?.execute()
}
func changePin() {
let logout = { [weak self] () -> Void in
self?.global.send(.logout)
}
let flow = PinRouting.Flow.change(
parent: UnretainedContentBox<UIViewController>(topMostViewController ?? self),
logoutRouting: logout
)
pinRouter = PinRouter(flow: flow) { [weak self] _ in
self?.pinRouter = nil
}
pinRouter?.execute()
}
func showQRCodeScanner() {
dismiss(animated: true) { [self] in
viewStore.send(.enter(into: .QR, context: .none))
}
}
func logout() {
alert(
.init(
title: LocalizationConstants.SideMenu.logout,
message: LocalizationConstants.SideMenu.logoutConfirm,
actions: [
UIAlertAction(
title: LocalizationConstants.okString,
style: .default
) { [weak self] _ in
self?.viewStore.send(.dismiss())
self?.global.send(.logout)
},
UIAlertAction(
title: LocalizationConstants.cancel,
style: .cancel
)
]
)
)
}
func logoutAndForgetWallet() {
viewStore.send(.dismiss())
global.send(.deleteWallet)
}
func handleAccountsAndAddresses() {
let storyboard = UIStoryboard(name: "AccountsAndAddresses", bundle: nil)
let viewController = storyboard.instantiateViewController(
withIdentifier: "AccountsAndAddressesNavigationController"
) as! AccountsAndAddressesNavigationController
viewController.modalPresentationStyle = .fullScreen
viewController.modalTransitionStyle = .coverVertical
viewController.navigationBar.tintColor = .lightGray
viewController.reload()
(topMostViewController ?? self).present(viewController, animated: true)
accountsAndAddressesNavigationController = viewController
}
func handleSecureChannel() {
func show() {
viewStore.send(.enter(into: .QR, context: .none))
}
if viewStore.route == nil {
show()
} else {
viewStore.send(.dismiss())
DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) { show() }
}
}
}
| lgpl-3.0 | 6102a5f290c0ccd6e33428fc2a5ac97a | 33.302846 | 117 | 0.564022 | 5.197721 | false | false | false | false |
iceVeryCold/DouYuZhiBo | DYDemo/DYDemo/Classes/Home/View/RecommendCycleView.swift | 1 | 3815 | //
// RecommendCycleView.swift
// DYDemo
//
// Created by 这个夏天有点冷 on 2017/3/23.
// Copyright © 2017年 YLT. All rights reserved.
//
import UIKit
private let kCycleCellID = "kCycleCellID"
class RecommendCycleView: UIView {
var cycleTimer : Timer?
// 定义属性
var cycleModels : [CycleModel]? {
didSet {
// 刷新collectionView
collectionView.reloadData()
// 设置pageControl个数
pageControl.numberOfPages = cycleModels?.count ?? 0
let indexPath = IndexPath.init(item: (cycleModels?.count ?? 0) * 10, section: 0)
collectionView.scrollToItem(at: indexPath, at: .left, animated: false)
// 添加定时器
removeCycleTimer()
addCycleTimer()
}
}
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var pageControl: UIPageControl!
override func awakeFromNib() {
// 设置该控件不随父控件拉伸
autoresizingMask = UIViewAutoresizing()
// 注册cell
collectionView.register(UINib.init(nibName: "CollectionCycleCell", bundle: nil), forCellWithReuseIdentifier:kCycleCellID)
}
override func layoutSubviews() {
super.layoutSubviews()
// 设置collectionView的layout
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = collectionView.bounds.size
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
collectionView.isPagingEnabled = true
collectionView.bounces = false
}
}
extension RecommendCycleView {
class func recommendCycleView() -> RecommendCycleView {
return Bundle.main.loadNibNamed("RecommendCycleView", owner: nil, options: nil)?.first as! RecommendCycleView
}
}
// MARK:- 遵守UICollectionView的数据源协议
extension RecommendCycleView : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return (cycleModels?.count ?? 0) * 10000
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kCycleCellID, for: indexPath) as! CollectionCycleCell
cell.cycleModel = cycleModels![indexPath.item % cycleModels!.count]
return cell
}
}
extension RecommendCycleView : UICollectionViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offsetX = scrollView.contentOffset.x
pageControl.currentPage = Int(offsetX / scrollView.bounds.width) % (cycleModels?.count ?? 1)
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
removeCycleTimer()
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
addCycleTimer()
}
}
// MARK:- 对定时器的操作方法
extension RecommendCycleView {
func addCycleTimer() {
cycleTimer = Timer.init(timeInterval: 3.0, target: self, selector: #selector(scrollToNext), userInfo: nil, repeats: true)
RunLoop.main.add(cycleTimer!, forMode: .commonModes)
}
func removeCycleTimer() {
cycleTimer?.invalidate()
cycleTimer = nil
}
@objc func scrollToNext() {
let currentOffset = collectionView.contentOffset.x
let offset = currentOffset + collectionView.bounds.width
collectionView.setContentOffset(CGPoint.init(x: offset, y: 0), animated: true)
}
}
| mit | 892c978b51b2d63a45dfe85c1a53a4b8 | 30.896552 | 129 | 0.659459 | 5.441176 | false | false | false | false |
alblue/swift-corelibs-foundation | Foundation/URLAuthenticationChallenge.swift | 3 | 7324 | // 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
//
public protocol URLAuthenticationChallengeSender : NSObjectProtocol {
/*!
@method useCredential:forAuthenticationChallenge:
*/
func use(_ credential: URLCredential, for challenge: URLAuthenticationChallenge)
/*!
@method continueWithoutCredentialForAuthenticationChallenge:
*/
func continueWithoutCredential(for challenge: URLAuthenticationChallenge)
/*!
@method cancelAuthenticationChallenge:
*/
func cancel(_ challenge: URLAuthenticationChallenge)
/*!
@method performDefaultHandlingForAuthenticationChallenge:
*/
func performDefaultHandling(for challenge: URLAuthenticationChallenge)
/*!
@method rejectProtectionSpaceAndContinueWithChallenge:
*/
func rejectProtectionSpaceAndContinue(with challenge: URLAuthenticationChallenge)
}
/*!
@class URLAuthenticationChallenge
@discussion This class represents an authentication challenge. It
provides all the information about the challenge, and has a method
to indicate when it's done.
*/
open class URLAuthenticationChallenge : NSObject, NSSecureCoding {
private let _protectionSpace: URLProtectionSpace
private let _proposedCredential: URLCredential?
private let _previousFailureCount: Int
private let _failureResponse: URLResponse?
private let _error: Error?
private let _sender: URLAuthenticationChallengeSender
static public var supportsSecureCoding: Bool {
return true
}
public required init?(coder aDecoder: NSCoder) {
NSUnimplemented()
}
open func encode(with aCoder: NSCoder) {
NSUnimplemented()
}
/*!
@method initWithProtectionSpace:proposedCredential:previousFailureCount:failureResponse:error:
@abstract Initialize an authentication challenge
@param space The URLProtectionSpace to use
@param credential The proposed URLCredential for this challenge, or nil
@param previousFailureCount A count of previous failures attempting access.
@param response The URLResponse for the authentication failure, if applicable, else nil
@param error The NSError for the authentication failure, if applicable, else nil
@result An authentication challenge initialized with the specified parameters
*/
public init(protectionSpace space: URLProtectionSpace, proposedCredential credential: URLCredential?, previousFailureCount: Int, failureResponse response: URLResponse?, error: Error?, sender: URLAuthenticationChallengeSender) {
self._protectionSpace = space
self._proposedCredential = credential
self._previousFailureCount = previousFailureCount
self._failureResponse = response
self._error = error
self._sender = sender
}
/*!
@method initWithAuthenticationChallenge:
@abstract Initialize an authentication challenge copying all parameters from another one.
@param challenge
@result A new challenge initialized with the parameters from the passed in challenge
@discussion This initializer may be useful to subclassers that want to proxy
one type of authentication challenge to look like another type.
*/
public init(authenticationChallenge challenge: URLAuthenticationChallenge, sender: URLAuthenticationChallengeSender) {
self._protectionSpace = challenge.protectionSpace
self._proposedCredential = challenge.proposedCredential
self._previousFailureCount = challenge.previousFailureCount
self._failureResponse = challenge.failureResponse
self._error = challenge.error
self._sender = sender
}
/*!
@method protectionSpace
@abstract Get a description of the protection space that requires authentication
@result The protection space that needs authentication
*/
/*@NSCopying*/ open var protectionSpace: URLProtectionSpace {
get {
return _protectionSpace
}
}
/*!
@method proposedCredential
@abstract Get the proposed credential for this challenge
@result The proposed credential
@discussion proposedCredential may be nil, if there is no default
credential to use for this challenge (either stored or in the
URL). If the credential is not nil and returns YES for
hasPassword, this means the NSURLConnection thinks the credential
is ready to use as-is. If it returns NO for hasPassword, then the
credential is not ready to use as-is, but provides a default
username the client could use when prompting.
*/
/*@NSCopying*/ open var proposedCredential: URLCredential? {
get {
return _proposedCredential
}
}
/*!
@method previousFailureCount
@abstract Get count of previous failed authentication attempts
@result The count of previous failures
*/
open var previousFailureCount: Int {
get {
return _previousFailureCount
}
}
/*!
@method failureResponse
@abstract Get the response representing authentication failure.
@result The failure response or nil
@discussion If there was a previous authentication failure, and
this protocol uses responses to indicate authentication failure,
then this method will return the response. Otherwise it will
return nil.
*/
/*@NSCopying*/ open var failureResponse: URLResponse? {
get {
return _failureResponse
}
}
/*!
@method error
@abstract Get the error representing authentication failure.
@discussion If there was a previous authentication failure, and
this protocol uses errors to indicate authentication failure,
then this method will return the error. Otherwise it will
return nil.
*/
/*@NSCopying*/ open var error: Error? {
get {
return _error
}
}
/*!
@method sender
@abstract Get the sender of this challenge
@result The sender of the challenge
@discussion The sender is the object you should reply to when done processing the challenge.
*/
open var sender: URLAuthenticationChallengeSender? {
get {
return _sender
}
}
}
extension _HTTPURLProtocol : URLAuthenticationChallengeSender {
func cancel(_ challenge: URLAuthenticationChallenge) {
NSUnimplemented()
}
func continueWithoutCredential(for challenge: URLAuthenticationChallenge) {
NSUnimplemented()
}
func use(_ credential: URLCredential, for challenge: URLAuthenticationChallenge) {
NSUnimplemented()
}
func performDefaultHandling(for challenge: URLAuthenticationChallenge) {
NSUnimplemented()
}
func rejectProtectionSpaceAndContinue(with challenge: URLAuthenticationChallenge) {
NSUnimplemented()
}
}
| apache-2.0 | 918b2c39daae8a8091328d9e1e4a2384 | 32.751152 | 231 | 0.700847 | 5.901692 | false | false | false | false |
epv44/TwitchAPIWrapper | Example/Tests/Request Tests/ModifyChannelInformationRequestTests.swift | 1 | 1231 | //
// ModifyChannelInformationRequestTests.swift
// TwitchAPIWrapper_Tests
//
// Created by Eric Vennaro on 8/1/21.
// Copyright © 2021 CocoaPods. All rights reserved.
//
import XCTest
@testable import TwitchAPIWrapper
class ModifyChannelInformationRequestTests: XCTestCase {
override func setUpWithError() throws {
TwitchAuthorizationManager.sharedInstance.clientID = "1"
TwitchAuthorizationManager.sharedInstance.credentials = Credentials(accessToken: "XXX", scopes: ["user", "read"])
super.setUp()
}
func testBuildRequest_withRequiredParams_shouldSucceed() throws {
let request = try ModifyChannelInformationRequest(broadcasterID: "1", gameID: "2", broadcasterLanguage: "en", title: "Lancelot", delay: 1)
XCTAssertEqual(
request.url!.absoluteString,
expectedURL: "https://api.twitch.tv/helix/channels?broadcaster_id=1")
let d = try JSONSerialization.jsonObject(with: request.data, options: .allowFragments) as! [String:String]
XCTAssertEqual(d, ["game_id": "2", "broadcaster_language": "en", "title": "Lancelot", "delay": "1"])
XCTAssertEqual(request.headers, ["Client-Id": "1", "Authorization": "Bearer XXX"])
}
}
| mit | fa816f91ea45d5ccb4e36306ab0b7a3c | 41.413793 | 146 | 0.699187 | 4.212329 | false | true | false | false |
uasys/swift | test/Constraints/array_literal.swift | 1 | 9546 | // RUN: %target-typecheck-verify-swift
struct IntList : ExpressibleByArrayLiteral {
typealias Element = Int
init(arrayLiteral elements: Int...) {}
}
struct DoubleList : ExpressibleByArrayLiteral {
typealias Element = Double
init(arrayLiteral elements: Double...) {}
}
struct IntDict : ExpressibleByArrayLiteral {
typealias Element = (String, Int)
init(arrayLiteral elements: Element...) {}
}
final class DoubleDict : ExpressibleByArrayLiteral {
typealias Element = (String, Double)
init(arrayLiteral elements: Element...) {}
}
final class List<T> : ExpressibleByArrayLiteral {
typealias Element = T
init(arrayLiteral elements: T...) {}
}
final class Dict<K,V> : ExpressibleByArrayLiteral {
typealias Element = (K,V)
init(arrayLiteral elements: (K,V)...) {}
}
infix operator =>
func => <K, V>(k: K, v: V) -> (K,V) { return (k,v) }
func useIntList(_ l: IntList) {}
func useDoubleList(_ l: DoubleList) {}
func useIntDict(_ l: IntDict) {}
func useDoubleDict(_ l: DoubleDict) {}
func useList<T>(_ l: List<T>) {}
func useDict<K,V>(_ d: Dict<K,V>) {}
useIntList([1,2,3])
useIntList([1.0,2,3]) // expected-error{{cannot convert value of type 'Double' to expected element type 'Int'}}
useIntList([nil]) // expected-error {{nil is not compatible with expected element type 'Int'}}
useDoubleList([1.0,2,3])
useDoubleList([1.0,2.0,3.0])
useIntDict(["Niners" => 31, "Ravens" => 34])
useIntDict(["Niners" => 31, "Ravens" => 34.0]) // expected-error{{cannot convert value of type '(String, Double)' to expected element type '(String, Int)'}}
// <rdar://problem/22333090> QoI: Propagate contextual information in a call to operands
useDoubleDict(["Niners" => 31, "Ravens" => 34.0])
useDoubleDict(["Niners" => 31.0, "Ravens" => 34])
useDoubleDict(["Niners" => 31.0, "Ravens" => 34.0])
// Generic slices
useList([1,2,3])
useList([1.0,2,3])
useList([1.0,2.0,3.0])
useDict(["Niners" => 31, "Ravens" => 34])
useDict(["Niners" => 31, "Ravens" => 34.0])
useDict(["Niners" => 31.0, "Ravens" => 34.0])
// Fall back to [T] if no context is otherwise available.
var a = [1,2,3]
var a2 : [Int] = a
var b = [1,2,3.0]
var b2 : [Double] = b
var arrayOfStreams = [1..<2, 3..<4]
struct MyArray : ExpressibleByArrayLiteral {
typealias Element = Double
init(arrayLiteral elements: Double...) {
}
}
var myArray : MyArray = [2.5, 2.5]
// Inference for tuple elements.
var x1 = [1]
x1[0] = 0
var x2 = [(1, 2)]
x2[0] = (3, 4)
var x3 = [1, 2, 3]
x3[0] = 4
func trailingComma() {
_ = [1, ]
_ = [1, 2, ]
_ = ["a": 1, ]
_ = ["a": 1, "b": 2, ]
}
func longArray() {
var _=["1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1"]
}
[1,2].map // expected-error {{expression type '((Int) throws -> _) throws -> [_]' is ambiguous without more context}}
// <rdar://problem/25563498> Type checker crash assigning array literal to type conforming to _ArrayProtocol
func rdar25563498<T : ExpressibleByArrayLiteral>(t: T) {
var x: T = [1] // expected-error {{cannot convert value of type '[Int]' to specified type 'T'}}
// expected-warning@-1{{variable 'x' was never used; consider replacing with '_' or removing it}}
}
func rdar25563498_ok<T : ExpressibleByArrayLiteral>(t: T) -> T
where T.ArrayLiteralElement : ExpressibleByIntegerLiteral {
let x: T = [1]
return x
}
class A { }
class B : A { }
class C : A { }
/// Check for defaulting the element type to 'Any' / 'Any?'.
func defaultToAny(i: Int, s: String) {
let a1 = [1, "a", 3.5]
// expected-error@-1{{heterogeneous collection literal could only be inferred to '[Any]'; add explicit type annotation if this is intentional}}
let _: Int = a1 // expected-error{{value of type '[Any]'}}
let a2: Array = [1, "a", 3.5]
// expected-error@-1{{heterogeneous collection literal could only be inferred to '[Any]'; add explicit type annotation if this is intentional}}
let _: Int = a2 // expected-error{{value of type 'Array<Any>'}}
let a3 = [1, "a", nil, 3.5]
// expected-error@-1{{heterogeneous collection literal could only be inferred to '[Any?]'; add explicit type annotation if this is intentional}}
let _: Int = a3 // expected-error{{value of type '[Any?]'}}
let a4: Array = [1, "a", nil, 3.5]
// expected-error@-1{{heterogeneous collection literal could only be inferred to '[Any?]'; add explicit type annotation if this is intentional}}
let _: Int = a4 // expected-error{{value of type 'Array<Any?>'}}
let a5 = []
// expected-error@-1{{empty collection literal requires an explicit type}}
let _: Int = a5 // expected-error{{value of type '[Any]'}}
let _: [Any] = [1, "a", 3.5]
let _: [Any] = [1, "a", [3.5, 3.7, 3.9]]
let _: [Any] = [1, "a", [3.5, "b", 3]]
let _: [Any?] = [1, "a", nil, 3.5]
let _: [Any?] = [1, "a", nil, [3.5, 3.7, 3.9]]
let _: [Any?] = [1, "a", nil, [3.5, "b", nil]]
let a6 = [B(), C()]
let _: Int = a6 // expected-error{{value of type '[A]'}}
}
func noInferAny(iob: inout B, ioc: inout C) {
var b = B()
var c = C()
let _ = [b, c, iob, ioc] // do not infer [Any] when elements are lvalues or inout
let _: [A] = [b, c, iob, ioc] // do not infer [Any] when elements are lvalues or inout
b = B()
c = C()
}
/// Check handling of 'nil'.
protocol Proto1 {}
protocol Proto2 {}
struct Nilable: ExpressibleByNilLiteral {
init(nilLiteral: ()) {}
}
func joinWithNil<T>(s: String, a: Any, t: T, m: T.Type, p: Proto1 & Proto2, arr: [Int], opt: Int?, iou: Int!, n: Nilable) {
let a1 = [s, nil]
let _: Int = a1 // expected-error{{value of type '[String?]'}}
let a2 = [nil, s]
let _: Int = a2 // expected-error{{value of type '[String?]'}}
let a3 = ["hello", nil]
let _: Int = a3 // expected-error{{value of type '[String?]'}}
let a4 = [nil, "hello"]
let _: Int = a4 // expected-error{{value of type '[String?]'}}
let a5 = [(s, s), nil]
let _: Int = a5 // expected-error{{value of type '[(String, String)?]'}}
let a6 = [nil, (s, s)]
let _: Int = a6 // expected-error{{value of type '[(String, String)?]'}}
let a7 = [("hello", "world"), nil]
let _: Int = a7 // expected-error{{value of type '[(String, String)?]'}}
let a8 = [nil, ("hello", "world")]
let _: Int = a8 // expected-error{{value of type '[(String, String)?]'}}
let a9 = [{ $0 * 2 }, nil]
let _: Int = a9 // expected-error{{value of type '[((Int) -> Int)?]'}}
let a10 = [nil, { $0 * 2 }]
let _: Int = a10 // expected-error{{value of type '[((Int) -> Int)?]'}}
let a11 = [a, nil]
let _: Int = a11 // expected-error{{value of type '[Any?]'}}
let a12 = [nil, a]
let _: Int = a12 // expected-error{{value of type '[Any?]'}}
let a13 = [t, nil]
let _: Int = a13 // expected-error{{value of type '[T?]'}}
let a14 = [nil, t]
let _: Int = a14 // expected-error{{value of type '[T?]'}}
let a15 = [m, nil]
let _: Int = a15 // expected-error{{value of type '[T.Type?]'}}
let a16 = [nil, m]
let _: Int = a16 // expected-error{{value of type '[T.Type?]'}}
let a17 = [p, nil]
let _: Int = a17 // expected-error{{value of type '[(Proto1 & Proto2)?]'}}
let a18 = [nil, p]
let _: Int = a18 // expected-error{{value of type '[(Proto1 & Proto2)?]'}}
let a19 = [arr, nil]
let _: Int = a19 // expected-error{{value of type '[[Int]?]'}}
let a20 = [nil, arr]
let _: Int = a20 // expected-error{{value of type '[[Int]?]'}}
let a21 = [opt, nil]
let _: Int = a21 // expected-error{{value of type '[Int?]'}}
let a22 = [nil, opt]
let _: Int = a22 // expected-error{{value of type '[Int?]'}}
let a23 = [iou, nil]
let _: Int = a23 // expected-error{{value of type '[Int?]'}}
let a24 = [nil, iou]
let _: Int = a24 // expected-error{{value of type '[Int?]'}}
let a25 = [n, nil]
let _: Int = a25 // expected-error{{value of type '[Nilable]'}}
let a26 = [nil, n]
let _: Int = a26 // expected-error{{value of type '[Nilable]'}}
}
struct OptionSetLike : ExpressibleByArrayLiteral {
typealias Element = OptionSetLike
init() { }
init(arrayLiteral elements: OptionSetLike...) { }
static let option: OptionSetLike = OptionSetLike()
}
func testOptionSetLike(b: Bool) {
let _: OptionSetLike = [ b ? [] : OptionSetLike.option, OptionSetLike.option]
let _: OptionSetLike = [ b ? [] : .option, .option]
}
// Join of class metatypes - <rdar://problem/30233451>
class Company<T> {
init(routes: [() -> T]) { }
}
class Person { }
class Employee: Person { }
class Manager: Person { }
let routerPeople = Company(
routes: [
{ () -> Employee.Type in
_ = ()
return Employee.self
},
{ () -> Manager.Type in
_ = ()
return Manager.self
}
]
)
// Same as above but with existentials
protocol Fruit {}
protocol Tomato : Fruit {}
struct Chicken : Tomato {}
protocol Pear : Fruit {}
struct Beef : Pear {}
let routerFruit = Company(
routes: [
// FIXME: implement join() for existentials
// expected-error@+1 {{cannot convert value of type '() -> Tomato.Type' to expected element type '() -> _'}}
{ () -> Tomato.Type in
_ = ()
return Chicken.self
},
{ () -> Pear.Type in
_ = ()
return Beef.self
}
]
)
// Infer [[Int]] for SR3786aa.
// FIXME: As noted in SR-3786, this was the behavior in Swift 3, but
// it seems like the wrong choice and is less by design than by
// accident.
let SR3786a: [Int] = [1, 2, 3]
let SR3786aa = [SR3786a.reversed(), SR3786a]
| apache-2.0 | 430672b4e333b33589c630046a19e684 | 28.282209 | 178 | 0.593233 | 3.052766 | false | false | false | false |
kperryua/swift | test/Compatibility/protocol_composition.swift | 1 | 2105 | // RUN: rm -rf %t && mkdir -p %t
// RUN: %utils/split_file.py -o %t %s
// RUN: %target-swift-frontend -parse -primary-file %t/swift3.swift %t/common.swift -verify
// RUN: %target-swift-frontend -parse -primary-file %t/swift4.swift %t/common.swift -verify -swift-version 4
// BEGIN common.swift
protocol P1 {
static func p1() -> Int
}
protocol P2 {
static var p2: Int { get }
}
// BEGIN swift3.swift
// Warning for mistakenly accepted protocol composition production.
func foo(x: P1 & Any & P2.Type?) {
// expected-warning @-1 {{protocol composition with postfix '.Type' is ambiguous and will be rejected in future version of Swift}} {{13-13=(}} {{26-26=)}}
let _: (P1 & P2).Type? = x
let _: (P1 & P2).Type = x!
let _: Int = x!.p1()
let _: Int? = x?.p2
}
// Type expression
func bar() -> ((P1 & P2)?).Type {
let x = (P1 & P2?).self
// expected-warning @-1 {{protocol composition with postfix '?' is ambiguous and will be rejected in future version of Swift}} {{12-12=(}} {{19-19=)}}
return x
}
// Non-ident type at non-last position are rejected anyway.
typealias A1 = P1.Type & P2 // expected-error {{type 'P1.Type' cannot be used within a protocol composition}}
// BEGIN swift4.swift
func foo(x: P1 & Any & P2.Type?) { // expected-error {{non-protocol type 'P2.Type?' cannot be used within a protocol composition}}
let _: (P1 & P2).Type? = x // expected-error {{cannot convert value of type 'P1' to specified type '(P1 & P2).Type?'}}
let _: (P1 & P2).Type = x! // expected-error {{cannot force unwrap value of non-optional type 'P1'}}
let _: Int = x!.p1() // expected-error {{cannot force unwrap value of non-optional type 'P1'}}
let _: Int? = x?.p2 // expected-error {{cannot use optional chaining on non-optional value of type 'P1'}}
}
func bar() -> ((P1 & P2)?).Type {
let x = (P1 & P2?).self // expected-error {{non-protocol type 'P2?' cannot be used within a protocol composition}}
return x // expected-error {{cannot convert return expression}}
}
typealias A1 = P1.Type & P2 // expected-error {{type 'P1.Type' cannot be used within a protocol composition}}
| apache-2.0 | 1577dea9a71f7ac7f2090e46e12d15ce | 41.959184 | 156 | 0.656057 | 3.179758 | false | false | false | false |
justindaigle/grogapp-ios | GroGApp/GroGApp/TimelineTableViewController.swift | 1 | 35967 | //
// TimelineTableViewController.swift
// GroGApp
//
// Created by Justin Daigle on 2/7/15.
// Copyright (c) 2015 Justin Daigle (.com). All rights reserved.
//
import UIKit
class TimelineTableViewController: UITableViewController {
@IBOutlet var statusesView:UITableView!
@IBOutlet var aRefreshControl:UIRefreshControl!
var statuses = [JSON]()
var avatars = [UIImage]() // let's not reload avatars a billion times...
var avatarUrls = [String]()
var initiallyLoaded = false // keep the costly load timeline operation from happening EVERY time we return to this view
private struct rContainer { static var ready = false }
var highestId = 0;
var lowestId = 0;
var min = 0;
@IBAction func newFollowFriend() {
var prompt = UIAlertController(title: "Add User", message: "Enter the username of a user to follow or friend", preferredStyle: UIAlertControllerStyle.Alert)
prompt.addTextFieldWithConfigurationHandler({(textField:UITextField!) in
textField.placeholder = "Username"
textField.secureTextEntry = false})
prompt.addAction((UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil)))
prompt.addAction(UIAlertAction(title: "Unfollow", style: UIAlertActionStyle.Destructive, handler: {(alertAction: UIAlertAction!) in
let defaults = NSUserDefaults.standardUserDefaults()
let username = defaults.stringForKey("username")
let password = defaults.stringForKey("password")
let text = prompt.textFields![0] as! UITextField
var success = DataMethods.UnfollowUser(username!, password!, text.text)
if (success) {
var newPrompt = UIAlertController(title: "Success", message: "User unfollowed.", preferredStyle: UIAlertControllerStyle.Alert)
newPrompt.addAction((UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)))
self.presentViewController(newPrompt, animated: true, completion: nil)
}
else {
var newPrompt = UIAlertController(title: "Unfollow Failed", message: "User does not exist, or you do not follow them.", preferredStyle: UIAlertControllerStyle.Alert)
newPrompt.addAction((UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)))
self.presentViewController(newPrompt, animated: true, completion: nil)
}
}))
prompt.addAction(UIAlertAction(title: "Follow", style: UIAlertActionStyle.Default, handler: {(alertAction: UIAlertAction!) in
let defaults = NSUserDefaults.standardUserDefaults()
let username = defaults.stringForKey("username")
let password = defaults.stringForKey("password")
let text = prompt.textFields![0] as! UITextField
var success = DataMethods.FollowUser(username!, password!, text.text)
if (success) {
var newPrompt = UIAlertController(title: "Success", message: "User followed.", preferredStyle: UIAlertControllerStyle.Alert)
newPrompt.addAction((UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)))
self.presentViewController(newPrompt, animated: true, completion: nil)
}
else {
var newPrompt = UIAlertController(title: "Follow Failed", message: "User does not exist.", preferredStyle: UIAlertControllerStyle.Alert)
newPrompt.addAction((UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)))
self.presentViewController(newPrompt, animated: true, completion: nil)
}
}))
/*prompt.addAction(UIAlertAction(title: "Request Friend", style: UIAlertActionStyle.Default, handler: {
(alertAction:UIAlertAction!) in
let defaults = NSUserDefaults.standardUserDefaults()
let username = defaults.stringForKey("username")
let password = defaults.stringForKey("password")
let text = prompt.textFields![0] as! UITextField
var success = DataMethods.RequestFriend(username!, password!, text.text)
if (success) {
var newPrompt = UIAlertController(title: "Success", message: "Friend requested.", preferredStyle: UIAlertControllerStyle.Alert)
newPrompt.addAction((UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)))
self.presentViewController(newPrompt, animated: true, completion: nil)
}
else {
var newPrompt = UIAlertController(title: "Request Failed", message: "User does not exist.", preferredStyle: UIAlertControllerStyle.Alert)
newPrompt.addAction((UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)))
self.presentViewController(newPrompt, animated: true, completion: nil)
}
}))*/
prompt.addAction(UIAlertAction(title: "Log Out", style: UIAlertActionStyle.Default, handler: {
(alertAction: UIAlertAction!) in
var defaults = NSUserDefaults.standardUserDefaults()
defaults.setValue("", forKey: "username")
defaults.setValue("", forKey: "password")
var successPrompt = UIAlertController(title: "Success", message: "You are now logged out.", preferredStyle: UIAlertControllerStyle.Alert)
successPrompt.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: {
(alertAction: UIAlertAction!) in
self.promptUserForCredentials(false)
}))
self.presentViewController(successPrompt, animated: true, completion: nil)
}))
prompt.addAction(UIAlertAction(title: "Change Password", style: UIAlertActionStyle.Default, handler: {
(action:UIAlertAction!) in
self.changePasswordPrompt(false)
}))
prompt.addAction(UIAlertAction(title: "My Profile", style: UIAlertActionStyle.Default, handler: {
(action:UIAlertAction!) in
self.myProfilePrompt()
}))
self.presentViewController(prompt, animated: true, completion: nil)
}
@IBAction func refresh(sender:UIRefreshControl) {
println("Pulled to refresh!")
updateStatusView()
aRefreshControl.endRefreshing()
}
@IBAction func unwindToHomeScreen(segue:UIStoryboardSegue) {
}
@IBAction func updateStatusView() {
refreshStatusList(false)
statusesView.reloadData()
}
func getReady() {
rContainer.ready = true
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "detail") {
if let indexPath = self.tableView.indexPathForSelectedRow() {
var dest = segue.destinationViewController as! DetailViewController
dest.statusId = self.statuses[indexPath.row]["id"].int!
dest.username = self.statuses[indexPath.row]["username"].stringValue
}
}
}
override func scrollViewWillBeginDragging(scrollView: UIScrollView) {
var offset = scrollView.contentOffset.y + scrollView.frame.size.height
if (offset > scrollView.contentSize.height) {
println("Something should be happening!")
println("This shouldn't be seen more often than every five seconds! 😭")
rContainer.ready = false;
refreshStatusList(true)
statusesView.reloadData()
// var timer = NSTimer.scheduledTimerWithTimeInterval(15, target: self, selector: Selector(getReady()), userInfo: nil, repeats: false);
}
}
/* override func scrollViewDidScroll(scrollView: UIScrollView) {
// println("Scroll view did scroll!")
var offset = scrollView.contentOffset.y + scrollView.frame.size.height
if (offset > scrollView.contentSize.height + 50) {
println("Something should be happening!")
if (rContainer.ready) {
println("This shouldn't be seen more often than every five seconds! 😭")
rContainer.ready = false;
refreshStatusList(true)
statusesView.reloadData()
var timer = NSTimer.scheduledTimerWithTimeInterval(15, target: self, selector: Selector(getReady()), userInfo: nil, repeats: false);
}
}
// println(offset)
// println(scrollView.contentSize.height)
} */
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
//DataMethods.ValidateUser("justin", "123change")
// making things a little more responsive
if (initiallyLoaded) {
return
}
else {
initiallyLoaded = true
}
// check if user info stored in phone already
let defaults = NSUserDefaults.standardUserDefaults()
let username = defaults.stringForKey("username")
let password = defaults.stringForKey("password")
if (username != nil && password != nil) {
// validate against the server
let userIsValid = DataMethods.ValidateUser(username!, password!)
if (userIsValid) {
// populate the timeline
updateStatusView()
}
else {
// invalid credentials are stored; get new ones
promptUserForCredentials(false)
}
}
else {
// no credentials are stored; get some
promptUserForCredentials(false)
}
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func viewDidLoad() {
super.viewDidLoad()
}
// recursive calls happen when a prompt fails to get valid credentials
// these give a different message to the user
func promptUserForCredentials(recursive:Bool) {
// how to do this prompt
// http://stackoverflow.com/questions/24579537/how-do-you-use-an-alert-to-prompt-for-text-in-ios-with-swift
// initial username/password prompt
var credentialPrompt = UIAlertController(title: "Log In", message: recursive ? "Incorrect username or password" : "Enter your username and password", preferredStyle: UIAlertControllerStyle.Alert)
credentialPrompt.addTextFieldWithConfigurationHandler({(textField:UITextField!) in
textField.placeholder = "Username"
textField.secureTextEntry = false})
credentialPrompt.addTextFieldWithConfigurationHandler({(textField:UITextField!) in
textField.placeholder = "Password"
textField.secureTextEntry = true})
credentialPrompt.addAction(UIAlertAction(title: "Create/Reset", style: UIAlertActionStyle.Cancel, handler: { (alertAction:UIAlertAction!) in
var otherPrompt = UIAlertController(title: "Account Options", message: "Create a new account or reset a forgotten password", preferredStyle: UIAlertControllerStyle.Alert)
otherPrompt.addAction(UIAlertAction(title: "Create Account", style: UIAlertActionStyle.Default, handler: {(alertAction:UIAlertAction!) in
self.createAccountPrompt(false)
}))
otherPrompt.addAction(UIAlertAction(title: "Request Password Reset Code", style: UIAlertActionStyle.Default, handler: {(alertAction:UIAlertAction!) in
self.requestResetCodePrompt(false)
}))
otherPrompt.addAction(UIAlertAction(title: "Enter Password Reset Code", style: UIAlertActionStyle.Default, handler: {(alertAction:UIAlertAction!) in
self.resetPasswordPrompt(false)
}))
otherPrompt.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default, handler: {
(alertAction:UIAlertAction!) in
self.promptUserForCredentials(false)
}))
self.presentViewController(otherPrompt, animated: true, completion: nil)
}))
credentialPrompt.addAction(UIAlertAction(title: "OK", style: .Default, handler: { (alertAction:UIAlertAction!) in
let uField = credentialPrompt.textFields![0] as! UITextField
let pField = credentialPrompt.textFields![1] as! UITextField
// validate these against the server
let userIsValid = DataMethods.ValidateUser(uField.text, pField.text)
if (userIsValid) {
var defaults = NSUserDefaults.standardUserDefaults()
defaults.setValue(uField.text, forKey: "username")
defaults.setValue(pField.text, forKey: "password")
var successPrompt = UIAlertController(title: "Login Successful", message: "You are now logged in.", preferredStyle: UIAlertControllerStyle.Alert)
successPrompt.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(successPrompt, animated: true, completion: nil)
self.updateStatusView()
}
else {
self.promptUserForCredentials(true)
}
}))
self.presentViewController(credentialPrompt, animated: true, completion: nil) // should probably have timeline loading stuff in another function that can be called after this
}
func myProfilePrompt() {
var pPrompt = UIAlertController(title: "My Profile", message: "Change your avatar, real name, bio, or location here", preferredStyle: UIAlertControllerStyle.Alert)
pPrompt.addAction((UIAlertAction(title: "Avatar", style: UIAlertActionStyle.Default, handler: {
(action:UIAlertAction!) in
self.changeAvatarPrompt()
})))
pPrompt.addAction((UIAlertAction(title: "Bio", style: UIAlertActionStyle.Default, handler: {
(action:UIAlertAction!) in
self.changeBioPrompt()
})))
pPrompt.addAction((UIAlertAction(title: "Location", style: UIAlertActionStyle.Default, handler: {
(action:UIAlertAction!) in
self.changeLocPrompt()
})))
pPrompt.addAction((UIAlertAction(title: "Real Name", style: UIAlertActionStyle.Default, handler: {
(action:UIAlertAction!) in
self.changeRNamePrompt()
})))
pPrompt.addAction((UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil)))
self.presentViewController(pPrompt, animated: true, completion: nil)
}
func changeAvatarPrompt() {
var chPrompt = UIAlertController(title: "Change Avatar", message: "Link to the image URL of your desired avatar (must be hosted elsewhere; should end in .jpg or .png or something)", preferredStyle: UIAlertControllerStyle.Alert)
chPrompt.addTextFieldWithConfigurationHandler({
(textField:UITextField!) in
textField.placeholder = "Image URL"
textField.secureTextEntry = false
})
chPrompt.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: {
(action:UIAlertAction!) in
let field = chPrompt.textFields![0] as! UITextField
let defaults = NSUserDefaults.standardUserDefaults()
let username = defaults.stringForKey("username")
let password = defaults.stringForKey("password")
let result = DataMethods.ChangeAvatar(username!, password!, field.text)
var mPrompt = UIAlertController(title: result ? "Success":"Failure", message: result ? "Avatar changed successfully." : "Something went wrong.", preferredStyle: UIAlertControllerStyle.Alert)
mPrompt.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(mPrompt, animated: true, completion: nil)
}))
chPrompt.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))
self.presentViewController(chPrompt, animated: true, completion: nil)
}
func changeBioPrompt() {
var chPrompt = UIAlertController(title: "Change Bio", message: "Type a new bio here", preferredStyle: UIAlertControllerStyle.Alert)
chPrompt.addTextFieldWithConfigurationHandler({
(textField:UITextField!) in
textField.placeholder = "Bio Text"
textField.secureTextEntry = false
})
chPrompt.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: {
(action:UIAlertAction!) in
let field = chPrompt.textFields![0] as! UITextField
let defaults = NSUserDefaults.standardUserDefaults()
let username = defaults.stringForKey("username")
let password = defaults.stringForKey("password")
let result = DataMethods.ChangeBio(username!, password!, field.text)
var mPrompt = UIAlertController(title: result ? "Success":"Failure", message: result ? "Bio changed successfully." : "Something went wrong.", preferredStyle: UIAlertControllerStyle.Alert)
mPrompt.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(mPrompt, animated: true, completion: nil)
}))
chPrompt.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))
self.presentViewController(chPrompt, animated: true, completion: nil)
}
func changeLocPrompt() {
var chPrompt = UIAlertController(title: "Change Location", message: "Enter the name of your location.", preferredStyle: UIAlertControllerStyle.Alert)
chPrompt.addTextFieldWithConfigurationHandler({
(textField:UITextField!) in
textField.placeholder = "Location"
textField.secureTextEntry = false
})
chPrompt.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: {
(action:UIAlertAction!) in
let field = chPrompt.textFields![0] as! UITextField
let defaults = NSUserDefaults.standardUserDefaults()
let username = defaults.stringForKey("username")
let password = defaults.stringForKey("password")
let result = DataMethods.ChangeLocation(username!, password!, field.text)
var mPrompt = UIAlertController(title: result ? "Success":"Failure", message: result ? "Location changed successfully." : "Something went wrong.", preferredStyle: UIAlertControllerStyle.Alert)
mPrompt.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(mPrompt, animated: true, completion: nil)
}))
chPrompt.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))
self.presentViewController(chPrompt, animated: true, completion: nil)
}
func changeRNamePrompt() {
var chPrompt = UIAlertController(title: "Change Real Name", message: "Enter your real name here.", preferredStyle: UIAlertControllerStyle.Alert)
chPrompt.addTextFieldWithConfigurationHandler({
(textField:UITextField!) in
textField.placeholder = "Real Name"
textField.secureTextEntry = false
})
chPrompt.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: {
(action:UIAlertAction!) in
let field = chPrompt.textFields![0] as! UITextField
let defaults = NSUserDefaults.standardUserDefaults()
let username = defaults.stringForKey("username")
let password = defaults.stringForKey("password")
let result = DataMethods.ChangeRealName(username!, password!, field.text)
var mPrompt = UIAlertController(title: result ? "Success":"Failure", message: result ? "Real name changed successfully." : "Something went wrong.", preferredStyle: UIAlertControllerStyle.Alert)
mPrompt.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(mPrompt, animated: true, completion: nil)
}))
chPrompt.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))
self.presentViewController(chPrompt, animated: true, completion: nil)
}
func changePasswordPrompt(recursive:Bool) {
var chPrompt = UIAlertController(title: "Change Password", message: recursive ? "The passwords do not match, or your old password was incorrect.":"Confirm your old password and enter a new one.", preferredStyle: UIAlertControllerStyle.Alert)
chPrompt.addTextFieldWithConfigurationHandler({
(textField:UITextField!) in
textField.placeholder = "Old Password"
textField.secureTextEntry = true
})
chPrompt.addTextFieldWithConfigurationHandler({
(textField:UITextField!) in
textField.placeholder = "New Password"
textField.secureTextEntry = true
})
chPrompt.addTextFieldWithConfigurationHandler({
(textField:UITextField!) in
textField.placeholder = "Confirm New Password"
textField.secureTextEntry = true
})
chPrompt.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: {
(action:UIAlertAction!) in
let oField = chPrompt.textFields![0] as! UITextField
let nField = chPrompt.textFields![1] as! UITextField
let cField = chPrompt.textFields![2] as! UITextField
if (nField.text != cField.text) {
self.changePasswordPrompt(true)
}
else {
let defaults = NSUserDefaults.standardUserDefaults()
let username = defaults.stringForKey("username")
let result = DataMethods.ChangePassword(username!, oField.text, nField.text)
if (result) {
var sPrompt = UIAlertController(title: "Success", message: "Password changed successfully. You must now log back in.", preferredStyle: UIAlertControllerStyle.Alert)
sPrompt.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: {
(action:UIAlertAction!) in
self.promptUserForCredentials(false)
}))
self.presentViewController(sPrompt, animated: true, completion: nil)
}
else {
self.changePasswordPrompt(true)
}
}
}))
chPrompt.addAction((UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: {
(action:UIAlertAction!) in
self.promptUserForCredentials(false)
})))
self.presentViewController(chPrompt, animated: true, completion: nil)
}
func createAccountPrompt(recursive:Bool) {
var accPrompt = UIAlertController(title: "Create Account", message: recursive ? "Error: Username or email already in use, or password less than 8 characters":"Enter a username, email address, and password. Your usage is bound by the GroG Platform Terms of Service.", preferredStyle: UIAlertControllerStyle.Alert)
accPrompt.addTextFieldWithConfigurationHandler({
(textField:UITextField!) in
textField.placeholder = "Username"
textField.secureTextEntry = false
})
accPrompt.addTextFieldWithConfigurationHandler({
(textField:UITextField!) in
textField.placeholder = "Email"
textField.secureTextEntry = false
})
accPrompt.addTextFieldWithConfigurationHandler({
(textField:UITextField!) in
textField.placeholder = "Password"
textField.secureTextEntry = true
})
accPrompt.addTextFieldWithConfigurationHandler({
(textField:UITextField!) in
textField.placeholder = "Confirm Password"
textField.secureTextEntry = true
})
accPrompt.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: {
(alertAction:UIAlertAction!) in
let uField = accPrompt.textFields![0] as! UITextField
let eField = accPrompt.textFields![1] as! UITextField
let pField = accPrompt.textFields![2] as! UITextField
let cField = accPrompt.textFields![3] as! UITextField
if (pField.text != cField.text) {
var passPrompt = UIAlertController(title: "Passwords must match", message: "Make sure both password fields match", preferredStyle: UIAlertControllerStyle.Alert)
passPrompt.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: {
(action:UIAlertAction!) in
self.createAccountPrompt(false)
}))
self.presentViewController(passPrompt, animated: true, completion: nil)
}
else {
let result = DataMethods.CreateAccount(uField.text, eField.text, pField.text)
if (result) {
var sPrompt = UIAlertController(title: "Success", message: "Account created. You can now log in.", preferredStyle: UIAlertControllerStyle.Alert)
sPrompt.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: {
(action:UIAlertAction!) in
self.promptUserForCredentials(false)
}))
self.presentViewController(sPrompt, animated: true, completion: nil)
}
else {
self.createAccountPrompt(true)
}
}
}))
accPrompt.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: {
(alertAction:UIAlertAction!) in
self.promptUserForCredentials(false)
}))
accPrompt.addAction(UIAlertAction(title: "View TOS", style: UIAlertActionStyle.Default, handler: {
(alertAction:UIAlertAction!) in
UIApplication.sharedApplication().openURL(NSURL(string: "http://getgrog.com/tos.aspx")!)
}))
self.presentViewController(accPrompt, animated: true, completion: nil)
}
func resetPasswordPrompt(recursive:Bool) {
var resPrompt = UIAlertController(title: "Reset Password", message: recursive ? "That isn't a valid password reset code." : "Enter your password reset code, and we'll email you a new password", preferredStyle: UIAlertControllerStyle.Alert)
resPrompt.addTextFieldWithConfigurationHandler({
(textField:UITextField!) in
textField.placeholder = "Reset Code"
textField.secureTextEntry = false
})
resPrompt.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: {
(action:UIAlertAction!) in
let cField = resPrompt.textFields![0] as! UITextField
let result = DataMethods.ResetPassword(cField.text)
if (result) {
var sPrompt = UIAlertController(title: "Success", message: "A new password has been emailed to you. Please change it soon.", preferredStyle: UIAlertControllerStyle.Alert)
sPrompt.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: {
(action:UIAlertAction!) in
self.promptUserForCredentials(false)
}))
self.presentViewController(sPrompt, animated: true, completion: nil)
}
else {
self.resetPasswordPrompt(true)
}
}))
resPrompt.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: {
(action:UIAlertAction!) in
self.promptUserForCredentials(false)
}))
self.presentViewController(resPrompt, animated: true, completion: nil)
}
func requestResetCodePrompt(recursive:Bool) {
var reqPrompt = UIAlertController(title: "Request Reset Code", message: recursive ? "The username you entered was invalid. Try again.":"Enter your username, and we'll email you a code to reset your password.", preferredStyle: UIAlertControllerStyle.Alert)
reqPrompt.addTextFieldWithConfigurationHandler({
(textField:UITextField!) in
textField.placeholder = "Email"
textField.secureTextEntry = false
})
reqPrompt.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: {
(action:UIAlertAction!) in
let uField = reqPrompt.textFields![0] as! UITextField
let result = DataMethods.ReqPasswordReset(uField.text)
if (result) {
var sPrompt = UIAlertController(title: "Success", message: "A request code has been sent to you. Go back to the menu and paste the code.", preferredStyle: UIAlertControllerStyle.Alert)
sPrompt.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: {
(action:UIAlertAction!) in
self.promptUserForCredentials(false)
}))
self.presentViewController(sPrompt, animated: true, completion: nil)
}
else {
self.requestResetCodePrompt(true)
}
}))
reqPrompt.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default, handler: {
(action:UIAlertAction!) in
self.promptUserForCredentials(false)
}))
self.presentViewController(reqPrompt, animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func refreshStatusList(moreOld:Bool) {
var defaults = NSUserDefaults.standardUserDefaults()
var username = defaults.valueForKey("username") as! String
var password = defaults.valueForKey("password") as! String
var resp:JSON;
if (!moreOld) {
resp = DataMethods.GetTimeline(username, password, 0, 4)
}
else {
resp = DataMethods.GetTimeline(username, password, min, min + 4)
}
min += 5
var tempStatuses:JSON = resp["statuses"]
// add each of these to tempStatuses
for (index: String, subJson: JSON) in tempStatuses {
if (subJson["id"].int < lowestId || lowestId == 0) {
println("lowestId is \(lowestId)")
lowestId = subJson["id"].int!
if (subJson["id"].int > highestId) {
highestId = subJson["id"].int!
}
statuses.append(subJson)
}
else if (subJson["id"].int > highestId || highestId == 0) {
println(subJson["id"])
println(highestId)
highestId = subJson["id"].int!
statuses.insert(subJson, atIndex: 0)
}
}
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of rows in the section.
return statuses.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! StatusTableViewCell
// println("Is this even getting called? 0_o")
// Configure the cell...
cell.authorLabel.text = statuses[indexPath.row]["author"].string
cell.dateLabel.text = statuses[indexPath.row]["time"].string
cell.contentLabel.text = statuses[indexPath.row]["content"].string
cell.contentLabel.sizeToFit()
// get the avatar
if (statuses[indexPath.row]["authoravatar"].string! != "") {
if (contains(avatarUrls, statuses[indexPath.row]["authoravatar"].string!)) {
var index = find(avatarUrls, statuses[indexPath.row]["authoravatar"].string!)!
cell.avatarView.image = avatars[index]
}
else {
avatarUrls.append(statuses[indexPath.row]["authoravatar"].string!)
var avaUrl = NSURL(string:statuses[indexPath.row]["authoravatar"].string!)
if let avUrl = avaUrl {
var avaData = NSData(contentsOfURL: avUrl)
var img = UIImage(data: avaData!)!
avatars.append(img)
cell.avatarView.image = UIImage(data: avaData!)
}
}
}
else {
cell.avatarView.image = nil
}
cell.avatarView.layer.cornerRadius = cell.avatarView.frame.size.width / 2
cell.avatarView.clipsToBounds = true
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
}
| mit | 50c04e83f97a67021869d387d7f8819c | 50.446352 | 320 | 0.637802 | 5.361712 | false | false | false | false |
kagemiku/ios-clean-architecture-sample | ios-clean-architecture-sample/Application/Builder/GitHubRepositoryDetailViewControllerBuilder.swift | 1 | 1072 | //
// GitHubRepositoryDetailViewControllerBuilder.swift
// ios-clean-architecture-sample
//
// Created by Akira Fukunaga on 1/10/17.
// Copyright © 2017 KAGE. All rights reserved.
//
import UIKit
struct GitHubRepositoryDetailViewControllerBuilder: ViewControllerBuilder {
typealias ViewController = GitHubRepositoryDetailViewController
static func build() -> ViewController {
let viewController = GitHubRepositoryDetailViewController()
let dataStore = GitHubRepositoryDetailDataStoreImpl()
let repository = GitHubRepositoryDetailRepositoryImpl(dataStore: dataStore)
let useCase = GitHubRepositoryDetailUseCaseImpl(repository: repository)
let presenter = GitHubRepositoryDetailPresenterImpl(useCase: useCase)
dataStore.inject(repository: repository)
repository.inject(useCase: useCase)
useCase.inject(presenter: presenter)
presenter.inject(viewController: viewController)
viewController.inject(presenter: presenter)
return viewController
}
}
| mit | 7fcf1b57cb1c7780c1baf689fed6b717 | 35.931034 | 87 | 0.741363 | 5.328358 | false | false | false | false |
PerfectlySoft/Perfect-TensorFlow | 1 | 1435 | // swift-tools-version:4.0
// The swift-tools-version declares the minimum version of Swift required to build this package.
//
// Package.swift
// Perfect-TensorFlow
//
// Created by Rockford Wei on 2017-05-18.
// Copyright © 2017 PerfectlySoft. All rights reserved.
//
//===----------------------------------------------------------------------===//
//
// This source file is part of the Perfect.org open source project
//
// Copyright (c) 2017 - 2018 PerfectlySoft Inc. and the Perfect project authors
// Licensed under Apache License v2.0
//
// See http://perfect.org/licensing.html for license information
//
//===----------------------------------------------------------------------===//
//
import PackageDescription
#if os(OSX)
import Darwin
#else
import Glibc
#endif
let package = Package(
name: "PerfectTensorFlow",
products: [
.library(
name: "PerfectTensorFlow",
targets: ["PerfectTensorFlow"]),
],
dependencies: [
.package(url: "https://github.com/apple/swift-protobuf.git", .exact("1.5.0"))
],
targets: [
.target(
name: "TensorFlowAPI",
dependencies: []),
.target(
name: "PerfectTensorFlow",
dependencies: ["TensorFlowAPI", "SwiftProtobuf"],
exclude:[]),
.testTarget(
name: "PerfectTensorFlowTests",
dependencies: ["PerfectTensorFlow"]),
]
)
| apache-2.0 | 659da7557869a72a21c589781b5ed7e4 | 27.68 | 96 | 0.555788 | 4.509434 | false | false | false | false |
|
ibm-cloud-security/appid-clientsdk-swift | IBMCloudAppIDTests/UserProfileTests.swift | 1 | 20186 | /* * Copyright 2016, 2017 IBM Corp.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
import XCTest
import BMSCore
@testable import IBMCloudAppID
public class UserProfileTests: XCTestCase {
static let bearerHeader = ["Authorization": "Bearer" + AppIDTestConstants.ACCESS_TOKEN]
static let expectedAttributesPathWithKey = "/api/v1/attributes/key"
static let expectedAttributesPath = "/api/v1/attributes"
static let expectedProfilePath = "/tenant/userinfo"
class MockUserProfileManger : UserProfileManagerImpl {
var data : Data? = nil
var response : URLResponse? = nil
var error : Error? = nil
var token : String? = nil
var idTokenSubject: String? = nil
var expectMethod = "GET"
var expectedPath = expectedAttributesPath
override func send(request : URLRequest, handler : @escaping (Data?, URLResponse?, Error?) -> Void) {
// make sure the token is put on the request:
if let token = token {
XCTAssert(("Bearer " + token) == request.value(forHTTPHeaderField: "Authorization"))
}
XCTAssert(expectMethod == request.httpMethod)
XCTAssert(request.url?.path.hasSuffix(expectedPath) == true)
handler(data, response, error)
}
override func getLatestAccessToken() -> String? {
return token
}
override func getLatestIdentityTokenSubject() -> String? {
return idTokenSubject
}
}
class MyDelegate {
var failed = false
var passed = false
var failureDesc : String? = nil
func onSuccess(result: [String: Any]) {
XCTAssert(result["key"] != nil)
let actualValue = result["key"]!
let actualValueString = String(describing: actualValue)
XCTAssert(actualValueString == "value")
passed = true
}
func onFailure(error: Error) {
failed = true
}
func reset() {
failed = false
passed = false
}
}
override public func setUp() {
AppID.sharedInstance.initialize(tenantId: "tenant", region: AppID.REGION_US_SOUTH)
}
func testGetAllAttributes () {
let delegate = MyDelegate()
let userProfileManager = MockUserProfileManger(appId: AppID.sharedInstance)
let resp = HTTPURLResponse(url: URL(string: "http://someurl.com")!, statusCode: 200, httpVersion: "1.1", headerFields: [:])
userProfileManager.response = resp
userProfileManager.data = "{\"key\" : \"value\"}".data(using: .utf8)
userProfileManager.token = "token"
userProfileManager.expectMethod = "GET"
userProfileManager.getAttributes { (err, res) in
if err == nil {
delegate.onSuccess(result: res!)
} else {
delegate.onFailure(error: err!)
}
}
if delegate.failed || !delegate.passed {
XCTFail()
}
delegate.reset()
}
func testGetAllAttributesWithToken () {
let delegate = MyDelegate()
let userProfileManager = MockUserProfileManger(appId: AppID.sharedInstance)
let resp = HTTPURLResponse(url: URL(string: "http://someurl.com")!, statusCode: 200, httpVersion: "1.1", headerFields: [:])
userProfileManager.response = resp
userProfileManager.data = "{\"key\" : \"value\"}".data(using: .utf8)
userProfileManager.token = "token"
userProfileManager.expectMethod = "GET"
userProfileManager.getAttributes(accessTokenString: "token") { (err, res) in
if err == nil {
delegate.onSuccess(result: res!)
} else {
delegate.onFailure(error: err!)
}
}
if delegate.failed || !delegate.passed {
XCTFail()
}
delegate.reset()
}
func testGetAttribute () {
let delegate = MyDelegate()
let userProfileManager = MockUserProfileManger(appId: AppID.sharedInstance)
let resp = HTTPURLResponse(url: URL(string: "http://someurl.com")!, statusCode: 200, httpVersion: "1.1", headerFields: [:])
userProfileManager.response = resp
userProfileManager.data = "{\"key\" : \"value\"}".data(using: .utf8)
userProfileManager.token = "token"
userProfileManager.expectMethod = "GET"
userProfileManager.expectedPath = UserProfileTests.expectedAttributesPathWithKey
userProfileManager.getAttribute(key: "key") { (err, res) in
if err == nil {
delegate.onSuccess(result: res!)
} else {
delegate.onFailure(error: err!)
}
}
if delegate.failed || !delegate.passed {
XCTFail()
}
delegate.reset()
}
func testGetAttributeWithToken () {
let delegate = MyDelegate()
let userProfileManager = MockUserProfileManger(appId: AppID.sharedInstance)
let resp = HTTPURLResponse(url: URL(string: "http://someurl.com")!, statusCode: 200, httpVersion: "1.1", headerFields: [:])
userProfileManager.response = resp
userProfileManager.data = "{\"key\" : \"value\"}".data(using: .utf8)
userProfileManager.token = "token"
userProfileManager.expectMethod = "GET"
userProfileManager.expectedPath = UserProfileTests.expectedAttributesPathWithKey
userProfileManager.getAttribute(key: "key", accessTokenString: "token") { (err, res) in
if err == nil {
delegate.onSuccess(result: res!)
} else {
delegate.onFailure(error: err!)
}
}
if delegate.failed || !delegate.passed {
XCTFail()
}
delegate.reset()
}
func testSetAttribute () {
let delegate = MyDelegate()
let userProfileManager = MockUserProfileManger(appId: AppID.sharedInstance)
let resp = HTTPURLResponse(url: URL(string: "http://someurl.com")!, statusCode: 200, httpVersion: "1.1", headerFields: [:])
userProfileManager.response = resp
userProfileManager.data = "{\"key\" : \"value\"}".data(using: .utf8)
userProfileManager.token = "token"
userProfileManager.expectMethod = "PUT"
userProfileManager.expectedPath = UserProfileTests.expectedAttributesPathWithKey
userProfileManager.setAttribute(key: "key", value: "value") { (err, res) in
if err == nil {
delegate.onSuccess(result: res!)
} else {
delegate.onFailure(error: err!)
}
}
if delegate.failed || !delegate.passed {
XCTFail()
}
delegate.reset()
}
func testSetAttributeWithToken () {
let delegate = MyDelegate()
let userProfileManager = MockUserProfileManger(appId: AppID.sharedInstance)
let resp = HTTPURLResponse(url: URL(string: "http://someurl.com")!, statusCode: 200, httpVersion: "1.1", headerFields: [:])
userProfileManager.response = resp
userProfileManager.data = "{\"key\" : \"value\"}".data(using: .utf8)
userProfileManager.token = "token"
userProfileManager.expectMethod = "PUT"
userProfileManager.expectedPath = UserProfileTests.expectedAttributesPathWithKey
userProfileManager.setAttribute(key: "key", value: "value", accessTokenString: "token") { (err, res) in
if err == nil {
delegate.onSuccess(result: res!)
} else {
delegate.onFailure(error: err!)
}
}
if delegate.failed || !delegate.passed {
XCTFail()
}
delegate.reset()
}
func testDeleteAttributeWithToken () {
let delegate = MyDelegate()
let userProfileManager = MockUserProfileManger(appId: AppID.sharedInstance)
let resp = HTTPURLResponse(url: URL(string: "http://someurl.com")!, statusCode: 204, httpVersion: "1.1", headerFields: [:])
userProfileManager.response = resp
userProfileManager.data = "".data(using: .utf8)
userProfileManager.token = "token"
userProfileManager.expectMethod = "DELETE"
userProfileManager.expectedPath = UserProfileTests.expectedAttributesPathWithKey
userProfileManager.deleteAttribute(key: "key", accessTokenString: "token") { (err, res) in
guard err == nil else {
return delegate.onFailure(error: err!)
}
XCTAssertEqual(res!.count, 0)
delegate.passed = true
}
if delegate.failed || !delegate.passed {
XCTFail()
}
delegate.reset()
}
func testFailure () {
let delegate = MyDelegate()
let userProfileManager = MockUserProfileManger(appId: AppID.sharedInstance)
let resp = HTTPURLResponse(url: URL(string: "http://someurl.com")!, statusCode: 404, httpVersion: "1.1", headerFields: [:])
userProfileManager.response = resp
userProfileManager.data = "{\"error\" : \"NOT_FOUND\"}".data(using: .utf8)
userProfileManager.token = "token"
userProfileManager.expectMethod = "PUT"
userProfileManager.expectedPath = UserProfileTests.expectedAttributesPathWithKey
userProfileManager.setAttribute(key: "key", value: "value", accessTokenString: "token") { (err, res) in
if err == nil {
delegate.onSuccess(result: res!)
} else {
delegate.onFailure(error: err!)
}
}
XCTAssert(delegate.failed)
delegate.reset()
}
func testUserInfoSuccessFlow () {
let userProfileManager = MockUserProfileManger(appId: AppID.sharedInstance)
let resp = HTTPURLResponse(url: URL(string: UserProfileTests.expectedProfilePath)!, statusCode: 200, httpVersion: "1.1", headerFields: UserProfileTests.bearerHeader)
userProfileManager.response = resp
userProfileManager.expectedPath = UserProfileTests.expectedProfilePath
userProfileManager.token = AppIDConstants.APPID_ACCESS_TOKEN
userProfileManager.data = "{\"sub\" : \"123\"}".data(using: .utf8)
userProfileManager.idTokenSubject = "123"
func happyFlowHandler(err: Swift.Error?, res: [String: Any]?) {
guard err == nil, let res = res else {
return XCTFail()
}
guard let dict = res as? [String: String] else {
return XCTFail()
}
XCTAssert(dict == ["sub": "123"])
}
userProfileManager.getUserInfo(completionHandler: happyFlowHandler)
userProfileManager.getUserInfo(accessTokenString: AppIDConstants.APPID_ACCESS_TOKEN,
identityTokenString: nil,
completionHandler: happyFlowHandler)
userProfileManager.getUserInfo(accessTokenString: AppIDConstants.APPID_ACCESS_TOKEN,
identityTokenString: AppIDTestConstants.ID_TOKEN_WITH_SUBJECT,
completionHandler: happyFlowHandler)
}
func testMissingAccessToken () {
let userProfileManager = MockUserProfileManger(appId: AppID.sharedInstance)
userProfileErrorHandler(manager: userProfileManager, expectedError: .missingAccessToken)
}
func testUnauthorized () {
let userProfileManager = MockUserProfileManger(appId: AppID.sharedInstance)
let resp = HTTPURLResponse(url: URL(string: UserProfileTests.expectedProfilePath)!, statusCode: 401, httpVersion: "1.1", headerFields: UserProfileTests.bearerHeader)
userProfileManager.response = resp
userProfileManager.token = "Bad token"
userProfileManager.idTokenSubject = "123"
userProfileManager.expectedPath = UserProfileTests.expectedProfilePath
userProfileErrorHandler(manager: userProfileManager, expectedError: .unauthorized)
}
func testUserNotFound () {
let userProfileManager = MockUserProfileManger(appId: AppID.sharedInstance)
let resp = HTTPURLResponse(url: URL(string: UserProfileTests.expectedProfilePath)!, statusCode: 404, httpVersion: "1.1", headerFields: UserProfileTests.bearerHeader)
userProfileManager.response = resp
userProfileManager.token = AppIDConstants.APPID_ACCESS_TOKEN
userProfileManager.idTokenSubject = "123"
userProfileManager.expectedPath = UserProfileTests.expectedProfilePath
userProfileErrorHandler(manager: userProfileManager, expectedError: .notFound)
}
func testUnexpectedResponseCode () {
let userProfileManager = MockUserProfileManger(appId: AppID.sharedInstance)
let resp = HTTPURLResponse(url: URL(string: UserProfileTests.expectedProfilePath)!, statusCode: 500, httpVersion: "1.1", headerFields: UserProfileTests.bearerHeader)
userProfileManager.response = resp
userProfileManager.token = "Bad token"
userProfileManager.idTokenSubject = "123"
userProfileManager.expectedPath = UserProfileTests.expectedProfilePath
userProfileErrorHandler(manager: userProfileManager, expectedError: .general("Unexpected"))
}
func testTokenSubstitutionAttack () {
let userProfileManager = MockUserProfileManger(appId: AppID.sharedInstance)
let resp = HTTPURLResponse(url: URL(string: UserProfileTests.expectedProfilePath)!, statusCode: 200, httpVersion: "1.1", headerFields: UserProfileTests.bearerHeader)
userProfileManager.response = resp
userProfileManager.data = "{\"sub\" : \"1234\"}".data(using: .utf8)
userProfileManager.token = AppIDConstants.APPID_ACCESS_TOKEN
userProfileManager.idTokenSubject = "123"
userProfileManager.expectedPath = UserProfileTests.expectedProfilePath
userProfileErrorHandler(manager: userProfileManager, expectedError: .responseValidationError)
}
func testUnexpectedError () {
let userProfileManager = MockUserProfileManger(appId: AppID.sharedInstance)
userProfileManager.error = NSError(domain: "Unexpected", code: 1, userInfo: nil)
userProfileManager.data = "{\"sub\" : \"1234\"}".data(using: .utf8)
userProfileManager.token = AppIDConstants.APPID_ACCESS_TOKEN
userProfileManager.idTokenSubject = "123"
userProfileManager.expectedPath = UserProfileTests.expectedProfilePath
userProfileErrorHandler(manager: userProfileManager, expectedError: .general("Unexpected"))
}
func testNoData () {
let userProfileManager = MockUserProfileManger(appId: AppID.sharedInstance)
let resp = HTTPURLResponse(url: URL(string: UserProfileTests.expectedProfilePath)!, statusCode: 200, httpVersion: "1.1", headerFields: UserProfileTests.bearerHeader)
userProfileManager.response = resp
userProfileManager.token = AppIDConstants.APPID_ACCESS_TOKEN
userProfileManager.idTokenSubject = "123"
userProfileManager.expectedPath = UserProfileTests.expectedProfilePath
userProfileErrorHandler(manager: userProfileManager, expectedError: .general("Failed to parse server response - no response text"))
}
func testNoResponse () {
let userProfileManager = MockUserProfileManger(appId: AppID.sharedInstance)
userProfileManager.data = "{\"sub\" : \"1234\"}".data(using: .utf8)
userProfileManager.token = AppIDConstants.APPID_ACCESS_TOKEN
userProfileManager.idTokenSubject = "123"
userProfileManager.expectedPath = UserProfileTests.expectedProfilePath
userProfileErrorHandler(manager: userProfileManager, expectedError: .general("Did not receive a response"))
}
func testMalformedJsonData () {
let userProfileManager = MockUserProfileManger(appId: AppID.sharedInstance)
let resp = HTTPURLResponse(url: URL(string: UserProfileTests.expectedProfilePath)!, statusCode: 200, httpVersion: "1.1", headerFields: UserProfileTests.bearerHeader)
userProfileManager.response = resp
userProfileManager.data = "\"sub\" : \"1234\"}".data(using: .utf8)
userProfileManager.token = AppIDConstants.APPID_ACCESS_TOKEN
userProfileManager.idTokenSubject = "123"
userProfileManager.expectedPath = UserProfileTests.expectedProfilePath
userProfileErrorHandler(manager: userProfileManager, expectedError: .bodyParsingError)
}
func testInvalidUserInfoResponse () {
let userProfileManager = MockUserProfileManger(appId: AppID.sharedInstance)
let resp = HTTPURLResponse(url: URL(string: UserProfileTests.expectedProfilePath)!, statusCode: 200, httpVersion: "1.1", headerFields: UserProfileTests.bearerHeader)
userProfileManager.response = resp
userProfileManager.data = "{\"nosub\" : \"1234\"}".data(using: .utf8)
userProfileManager.token = AppIDConstants.APPID_ACCESS_TOKEN
userProfileManager.idTokenSubject = "123"
userProfileManager.expectedPath = UserProfileTests.expectedProfilePath
userProfileErrorHandler(manager: userProfileManager, expectedError: .invalidUserInfoResponse)
}
func testMalformedIdentityToken () {
let userProfileManager = MockUserProfileManger(appId: AppID.sharedInstance)
userProfileManager.getUserInfo(accessTokenString: "", identityTokenString: "bad token") { (err, resp) in
guard let err = err as? UserProfileError else {
return XCTFail()
}
XCTAssert(err.description == UserProfileError.missingOrMalformedIdToken.description)
}
}
func testIdentityTokenWithoutSubject () {
let userProfileManager = MockUserProfileManger(appId: AppID.sharedInstance)
let resp = HTTPURLResponse(url: URL(string: UserProfileTests.expectedProfilePath)!, statusCode: 200, httpVersion: "1.1", headerFields: UserProfileTests.bearerHeader)
userProfileManager.response = resp
userProfileManager.data = "{\"sub\" : \"1234\"}".data(using: .utf8)
userProfileManager.expectedPath = UserProfileTests.expectedProfilePath
userProfileManager.getUserInfo(accessTokenString: AppIDTestConstants.ACCESS_TOKEN,
identityTokenString: AppIDTestConstants.malformedIdTokenNoSubject) { (err, res) in
if err != nil {
return XCTFail()
}
guard let dict = res as? [String: String] else {
return XCTFail()
}
XCTAssert(dict == ["sub": "1234"])
}
}
func testMalformedUserProvidedIdToken () {
let userProfileManager = MockUserProfileManger(appId: AppID.sharedInstance)
userProfileManager.getUserInfo(accessTokenString: "", identityTokenString: "") { (err, resp) in
guard let err = err as? UserProfileError else {
return XCTFail()
}
XCTAssert(err.description == UserProfileError.missingOrMalformedIdToken.description)
}
}
func userProfileErrorHandler(manager: UserProfileManager, expectedError: UserProfileError) {
manager.getUserInfo { (err, res) in
guard let error = err as? UserProfileError else {
return XCTFail()
}
switch (expectedError, error) {
case (.general(_), .general(_)): return
default:
XCTAssert(error.description == expectedError.description)
}
}
}
}
| apache-2.0 | c68db18028ade7d4dfb042e4c27799ff | 43.364835 | 173 | 0.651987 | 5.005207 | false | true | false | false |
dannichols/HDOService | HDOService/ServiceResponse.swift | 1 | 10103 | //
// RESTResponse.swift
// SocialTVCore
//
// Created by Daniel Nichols on 4/12/16.
// Copyright © 2016 Hey Danno. All rights reserved.
//
import Foundation
import HDOPromise
/// Possible HTTP response codes
public enum ServiceResponseStatus: Int {
case
Unknown = 0,
Continue = 100,
SwitchingProtocols = 101,
OK = 200,
Created = 201,
Accepted = 202,
NonAuthoritativeInformation = 203,
NoContent = 204,
ResetContent = 205,
PartialContent = 206,
MultipleChoices = 300,
MovedPermanently = 301,
Found = 302,
SeeOther = 303,
NotModified = 304,
UseProxy = 305,
TemporaryRedirect = 307,
BadRequest = 400,
Unauthorized = 401,
PaymentRequired = 402,
Forbidden = 403,
NotFound = 404,
MethodNotAllowed = 405,
NotAcceptable = 406,
ProxyAuthenticationRequired = 407,
RequestTimeout = 408,
Conflict = 409,
Gone = 410,
LengthRequired = 411,
PreconditionFailed = 412,
RequestEntityTooLarge = 413,
RequestURITooLong = 414,
UnsupportedMediaType = 415,
RequestedRangeNotSatisfiable = 416,
ExpectationFailed = 417,
InternalServerError = 500,
NotImplemented = 501,
BadGateway = 502,
ServiceUnavailable = 503,
GatewayTimeout = 504,
HTTPVersionNotSupported = 505
/// Translates an integer into a supported code
/// - parameter code: The raw integer value
/// - returns: The status code
public static func withValue(code: Int) -> ServiceResponseStatus {
guard let value = ServiceResponseStatus(rawValue: code) else {
return .Unknown
}
return value
}
/// Whether or not this is an informational response code
public var isInformational: Bool {
get {
return self.rawValue >= 100 && self.rawValue < 200
}
}
/// Whether or not this is an successful response code
public var isSuccessful: Bool {
get {
return self.rawValue >= 200 && self.rawValue < 300
}
}
/// Whether or not this is an redirection response code
public var isRedirect: Bool {
get {
return self.rawValue >= 300 && self.rawValue < 400
}
}
/// Whether or not this is an client error response code
public var isClientError: Bool {
get {
return self.rawValue >= 400 && self.rawValue < 500
}
}
/// Whether or not this is an server error response code
public var isServerError: Bool {
get {
return self.rawValue >= 500 && self.rawValue < 600
}
}
}
/// Interface for the response from a service request
public protocol ServiceResponse {
/// The response received
var response: NSHTTPURLResponse { get }
/// The body of the response
var data: NSData? { get }
/// Creates a new response
/// - parameter response: The HTTP response received
/// - parameter data: The body of the response, if any
init(response: NSHTTPURLResponse, data: NSData?)
}
public extension ServiceResponse {
/// The HTTP status code of the response
var status: ServiceResponseStatus {
get {
return ServiceResponseStatus.withValue(self.response.statusCode)
}
}
/// The value of the HTTP Content-Encoding header
var contentEncoding: String? {
get {
guard let value = self.response.allHeaderFields["Content-Encoding"] as? String else {
return nil
}
return value
}
}
/// The value of the HTTP Content-Type header
var contentType: String? {
get {
guard let value = self.response.allHeaderFields["Content-Type"] as? String else {
return nil
}
return value
}
}
/// Whether or not the response is an error
var isError: Bool {
get {
return self.status.isClientError || self.status.isServerError
}
}
}
/// A simple response that can be received from a service request
public class BasicServiceResponse: ServiceResponse {
/// The response received
public let response: NSHTTPURLResponse
/// The body of the response
public let data: NSData?
/// Creates a new response
/// - parameter response: The HTTP response received
/// - parameter data: The body of the response, if any
public required init(response: NSHTTPURLResponse, data: NSData?) {
self.response = response
self.data = data
}
}
/// A response with a body that can be decoded. This is an abstract base
/// class, and must be subclassed to be used.
public class DecoderServiceResponse<T>: BasicServiceResponse {
/// Creates a new response
/// - parameter response: The HTTP response received
/// - parameter data: The body of the response, if any
public required init(response: NSHTTPURLResponse, data: NSData?) {
super.init(response: response, data: data)
}
/// Decodes the response body
/// - returns: A promise that resolves with the decoded data, if any
public func parse() -> Promise<T?> {
return Promise<T?> { (onFulfilled, onRejected) in
guard let data = self.data else {
onFulfilled(nil)
return
}
do {
let decoded = try self.decode(data)
onFulfilled(decoded)
} catch {
onRejected(error)
}
}
}
/// Decodes raw data
/// - returns: The decoded data, if any
/// - throws: An error that occurred while parsing the data
public func decode(data: NSData) throws -> T? {
print("Call to abstract function: DecoderServiceResponse<T>::decode")
fatalError()
}
}
/// A response with a string body
public class StringServiceResponse: DecoderServiceResponse<String> {
/// The encoding of the string data. Defaults to UTF-8
public var encoding: UInt = NSUTF8StringEncoding
/// Creates a new response
/// - parameter response: The HTTP response received
/// - parameter data: The body of the response, if any
public required init(response: NSHTTPURLResponse, data: NSData?) {
super.init(response: response, data: data)
}
/// A response with a UTF-8 string body
public typealias UTF8 = StringServiceResponse
/// A response with a UTF-16 string body
public class UTF16: StringServiceResponse {
/// Creates a new response
/// - parameter response: The HTTP response received
/// - parameter data: The body of the response, if any
public required init(response: NSHTTPURLResponse, data: NSData?) {
super.init(response: response, data: data)
self.encoding = NSUTF16StringEncoding
}
}
/// Decodes raw data
/// - returns: The decoded data, if any
/// - throws: An error that occurred while parsing the data
public override func decode(data: NSData) throws -> String? {
return String(data: data, encoding: self.encoding)
}
}
/// A response with an image body
public class ImageServiceResponse: DecoderServiceResponse<UIImage> {
/// Creates a new response
/// - parameter response: The HTTP response received
/// - parameter data: The body of the response, if any
public required init(response: NSHTTPURLResponse, data: NSData?) {
super.init(response: response, data: data)
}
/// Decodes raw data
/// - returns: The decoded data, if any
/// - throws: An error that occurred while parsing the data
public override func decode(data: NSData) throws -> UIImage? {
return UIImage(data: data)
}
}
// A response with a JSON object body
public class JSONDictionaryServiceResponse: DecoderServiceResponse<JSONDictionary> {
/// Creates a new response
/// - parameter response: The HTTP response received
/// - parameter data: The body of the response, if any
public required init(response: NSHTTPURLResponse, data: NSData?) {
super.init(response: response, data: data)
}
/// Decodes raw data
/// - returns: The decoded data, if any
/// - throws: An error that occurred while parsing the data
public override func decode(data: NSData) throws -> JSONDictionary? {
let deserialized = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0)) as? JSONDictionary
return deserialized
}
}
/// A response with a JSON array body
public class JSONArrayServiceResponse: DecoderServiceResponse<JSONArray> {
/// Creates a new response
/// - parameter response: The HTTP response received
/// - parameter data: The body of the response, if any
public required init(response: NSHTTPURLResponse, data: NSData?) {
super.init(response: response, data: data)
}
/// Decodes raw data
/// - returns: The decoded data, if any
/// - throws: An error that occurred while parsing the data
public override func decode(data: NSData) throws -> JSONArray? {
let deserialized = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0)) as? JSONArray
return deserialized
}
}
/// A response with an XML body
public class XMLServiceResponse: DecoderServiceResponse<NSXMLParser> {
/// Creates a new response
/// - parameter response: The HTTP response received
/// - parameter data: The body of the response, if any
public required init(response: NSHTTPURLResponse, data: NSData?) {
super.init(response: response, data: data)
}
/// Decodes raw data
/// - returns: The decoded data, if any
/// - throws: An error that occurred while parsing the data
public override func decode(data: NSData) throws -> NSXMLParser? {
return NSXMLParser(data: data)
}
} | mit | c791e767593aae4edb70b01eeb392d5b | 29.615152 | 138 | 0.632053 | 4.808187 | false | false | false | false |
Artilles/FloppyCows | Floppy Cows/HighscoreScene.swift | 1 | 5107 | //
// HighscoreScene.swift
// Floppy Cows
//
// Created by Zac Bell on 2014-11-03.
// Copyright (c) 2014 Velocitrix. All rights reserved.
//
import Foundation
import SpriteKit
import Darwin
import AVFoundation
class HighscoreScene : SKScene {
var _resetButton = SKSpriteNode(imageNamed: "reset_button.png")
var _backButton = SKSpriteNode(imageNamed: "back_button.png")
let scoreLabel = SKLabelNode(fontNamed:"ChalkboardSE-Bold")
let scoreLabelBack = SKLabelNode(fontNamed:"ChalkboardSE-Bold")
var Score = HighScore()
var retrievedHighScore = SaveHighScore().RetrieveHighScore() as HighScore
var soundPlayer:AVAudioPlayer = AVAudioPlayer()
var backgroundMusicPlayer:AVAudioPlayer = AVAudioPlayer()
var clickURL:NSURL = NSBundle.mainBundle().URLForResource("click", withExtension: "mp3")!
var bgMusicURL:NSURL = NSBundle.mainBundle().URLForResource("menuMusic", withExtension: "mp3")!
override init(size:CGSize) {
super.init(size: size)
let background = SKSpriteNode(imageNamed: "hscore.jpg")
background.anchorPoint = CGPoint(x: 0, y: 0)
background.size = self.size
background.zPosition = -2
self.addChild(background)
soundPlayer = AVAudioPlayer(contentsOfURL: clickURL, error: nil)
backgroundMusicPlayer = AVAudioPlayer(contentsOfURL: bgMusicURL, error: nil)
initMenu()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func initMenu()
{
scoreLabel.text = "High Score: \(retrievedHighScore.highScore)"
self.addChild(scoreLabel)
scoreLabel.position.x = 300
scoreLabel.position.y = self.size.height - 250
scoreLabel.color = SKColor(red: 1.0, green: 0.0, blue: 0.3, alpha: 1.0)
scoreLabel.colorBlendFactor = 1.0
scoreLabel.zPosition = 100
scoreLabelBack.text = "High Score: \(retrievedHighScore.highScore)"
self.addChild(scoreLabelBack)
scoreLabelBack.setScale(1.02)
scoreLabelBack.position.x = 300
scoreLabelBack.position.y = self.size.height - 250
scoreLabelBack
scoreLabelBack.color = SKColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0)
scoreLabelBack.colorBlendFactor = 1.0
scoreLabelBack.zPosition = 90
// Add Reset buttons
_resetButton.position = CGPoint(x: _resetButton.size.width / 2, y: 40)
_resetButton.setScale(0.8)
self.addChild(_resetButton)
// Add Back button
_backButton.position = CGPoint(x: self.size.width - (_backButton.size.width / 2), y: 40)
_backButton.setScale(0.8)
self.addChild(_backButton)
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
for touch: AnyObject in touches {
// Reset button touched
if CGRectContainsPoint(_resetButton.frame, touch.locationInNode(self)) {
_resetButton.texture = SKTexture(imageNamed: "reset_button_pressed.png")
}
// Back button touched
if CGRectContainsPoint(_backButton.frame, touch.locationInNode(self)) {
_backButton.texture = SKTexture(imageNamed: "back_button_pressed.png")
}
}
}
override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {
for touch: AnyObject in touches {
if !CGRectContainsPoint(_resetButton.frame, touch.locationInNode(self)) {
_resetButton.texture = SKTexture(imageNamed: "reset_button.png")
}
if !CGRectContainsPoint(_backButton.frame, touch.locationInNode(self)) {
_backButton.texture = SKTexture(imageNamed: "back_button.png")
}
}
}
override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
for touch: AnyObject in touches {
// Reset button event
if CGRectContainsPoint(_resetButton.frame, touch.locationInNode(self)) {
_resetButton.texture = SKTexture(imageNamed: "reset_button.png")
resetButtonEvent()
}
// Back button event
if CGRectContainsPoint(_backButton.frame, touch.locationInNode(self)) {
backButtonEvent()
}
}
}
/* Callback function for the Reset button. */
func resetButtonEvent() {
soundPlayer.prepareToPlay()
soundPlayer.play()
Score.highScore = 0
SaveHighScore().ArchiveHighScore(highScore: Score)
let scene = HighscoreScene(size: self.size)
scene.scaleMode = .AspectFill
self.view?.presentScene(scene)
}
/* Callback function for Back button. Changes scene to MenuScene. */
func backButtonEvent() {
soundPlayer.prepareToPlay()
soundPlayer.play()
let scene = MenuScene(size: self.size)
scene.scaleMode = .AspectFill
self.view?.presentScene(scene)
}
} | gpl-2.0 | 55dce75cf72c0d573d7090831f08f32e | 36.558824 | 99 | 0.630703 | 4.711255 | false | false | false | false |
leejayID/Linkage-Swift | Linkage/Global.swift | 1 | 434 | //
// Global.swift
// Linkage
//
// Created by LeeJay on 2017/3/10.
// Copyright © 2017年 LeeJay. All rights reserved.
//
import UIKit
let ScreenWidth = UIScreen.main.bounds.width
let ScreenHeight = UIScreen.main.bounds.height
let kLeftTableViewCell = "LeftTableViewCell"
let kRightTableViewCell = "RightTableViewCell"
let kCollectionViewCell = "CollectionViewCell"
let kCollectionViewHeaderView = "CollectionViewHeaderView"
| apache-2.0 | 8876f7f315b8de7921bb73600e93d0a7 | 24.352941 | 58 | 0.779582 | 3.918182 | false | false | false | false |
codercd/DPlayer | DPlayer/AlbumViewController.swift | 1 | 6876 | //
// AlbumViewController.swift
// DPlayer
//
// Created by LiChendi on 16/4/6.
// Copyright © 2016年 LiChendi. All rights reserved.
//
import UIKit
import Photos
class AlbumViewController: UITableViewController,PHPhotoLibraryChangeObserver {
var sectionFetchResults = Array<PHFetchResult>()
var sectionLocalizedTitles = Array<AnyObject>()
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
let allPhotosOptions = PHFetchOptions()
allPhotosOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
let allPhotos = PHAsset.fetchAssetsWithOptions(allPhotosOptions)
let smartAlbums = PHAsset.fetchAssetsWithOptions(allPhotosOptions)
let topLevelUserCollections = PHAssetCollection.fetchAssetCollectionsWithType(.SmartAlbum, subtype: .AlbumRegular, options: nil)
sectionFetchResults = [allPhotos,smartAlbums,topLevelUserCollections]
sectionLocalizedTitles = ["",NSLocalizedString("Smart Albums", comment: ""),NSLocalizedString("Albums", comment: "")]
PHPhotoLibrary.sharedPhotoLibrary().registerChangeObserver(self)
self.tableView.reloadData()
// 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()
}
deinit {
PHPhotoLibrary.sharedPhotoLibrary().unregisterChangeObserver(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 Incomplete implementation, return the number of sections
return self.sectionFetchResults.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
var numberOfRows = 0;
if (section == 0) {
// The "All Photos" section only ever has a single row.
numberOfRows = 1;
} else {
let fetchResult = self.sectionFetchResults[section];
numberOfRows = fetchResult.count;
}
return numberOfRows
}
func photoLibraryDidChange(changeInstance: PHChange) {
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
// let fetchResult = sectionFetchResults[indexPath.row]
// Configure the cell...
cell.textLabel?.text = String(indexPath.row)
if (indexPath.section == 0) {
// cell = [tableView dequeueReusableCellWithIdentifier:AllPhotosReuseIdentifier forIndexPath:indexPath];
cell.textLabel?.text = NSLocalizedString("All Photos", comment: "")
} else {
let fetchResult:PHFetchResult = self.sectionFetchResults[indexPath.section] //as! PHFetchResult
let collection = fetchResult[indexPath.row];
// cell = [tableView dequeueReusableCellWithIdentifier:CollectionCellReuseIdentifier forIndexPath:indexPath];
cell.textLabel?.text = collection.localizedTitle;
}
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let fetchResult = self.sectionFetchResults[indexPath.section];
// if ([segue.identifier isEqualToString:AllPhotosSegue]) {
// assetGridViewController.assetsFetchResults = fetchResult;
// } else if ([segue.identifier isEqualToString:CollectionSegue]) {
// Get the PHAssetCollection for the selected row.
let collection:PHCollection = fetchResult[indexPath.row] as! PHCollection;
// if (![collection isKindOfClass:[PHAssetCollection class]]) {
// return;
// }
let assetCollection = collection as! PHAssetCollection
let assetsFetchResult = PHAsset.fetchAssetsInAssetCollection(assetCollection, options: nil)
// Configure the AAPLAssetGridViewController with the asset collection.
// PHAssetCollection *assetCollection = (PHAssetCollection *)collection;
// PHFetchResult *assetsFetchResult = [PHAsset fetchAssetsInAssetCollection:assetCollection options:nil];
//
let noname = NoNameViewController()
noname.assetsFetchResults = assetsFetchResult;
noname.assetCollection = assetCollection;
// noname.title = assetsFetchResult[indexPath.row] as! String
self.navigationController?.pushViewController(noname, animated: true)
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 0ba2a317703b7847d5b3115e93d83cdb | 39.668639 | 157 | 0.68238 | 5.708472 | false | false | false | false |
lioonline/v2ex-lio | V2ex/V2ex/V2AttributedStringHelper.swift | 1 | 4878 | //
// V2AttributedStringHelper.swift
// V2ex
//
// Created by Lee on 16/4/15.
// Copyright © 2016年 lio. All rights reserved.
//
import UIKit
class V2AttributedStringHelper: NSObject {
//解析
class func transformString(originalStr:String)->(NSAttributedString) {
let text:NSString = originalStr;
let attStr = (text as String).utf8Data?.attributedString
let attText = NSMutableAttributedString.init(attributedString: attStr!)
//解析http https
let regexHTTP = "http(s)?://([a-zA-Z|\\d]+\\.)+[a-zA-Z|\\d]+(/[a-zA-Z|\\d|\\-|\\+|_./?%&=]*)?"
let regularHTTP = try! NSRegularExpression.init(pattern: regexHTTP, options: NSRegularExpressionOptions.CaseInsensitive)
let attTextString = attText.string
let httpArray = regularHTTP.matchesInString(attTextString, options: NSMatchingOptions.ReportProgress, range: NSMakeRange(0, attTextString.count))
for itemHTTP in httpArray {
let rang = itemHTTP.range
let strhttp = text.substringWithRange(rang)
print("http-----:\(strhttp)------\(rang)")
attText.addAttribute(NSLinkAttributeName, value: strhttp, range: rang)
}
//解析@
let regexAt = "@[\\u4e00-\\u9fa5\\w\\-]+"
let regularAt = try! NSRegularExpression.init(pattern: regexAt, options: NSRegularExpressionOptions.CaseInsensitive)
let atArray = regularAt.matchesInString(attTextString, options: NSMatchingOptions.ReportProgress, range: NSMakeRange(0, attTextString.count))
for itemAt in atArray {
let rang = itemAt.range
let strAt = text.substringWithRange(rang)
attText.addAttribute(NSLinkAttributeName, value: strAt, range: rang)
print("at-----:\(strAt)")
}
//解析话题
let regexPound = "#([^\\#|.]+)#"
let regularPound = try! NSRegularExpression.init(pattern: regexPound, options: NSRegularExpressionOptions.CaseInsensitive)
let poundArray = regularPound.matchesInString(attTextString, options: NSMatchingOptions.ReportProgress, range: NSMakeRange(0, attTextString.count))
for itemPound in poundArray {
let rang = itemPound.range
let itemPound = text.substringWithRange(rang)
print("pound-----:\(itemPound)")
}
// 解析表情 无效
let regexEmoji = "\\[a−zA−Z0−9u4e00−u9fa5]+"
let regularEmoji = try! NSRegularExpression.init(pattern: regexEmoji, options: NSRegularExpressionOptions.CaseInsensitive)
let emojiArray = regularEmoji.matchesInString(attTextString, options: NSMatchingOptions.ReportProgress, range: NSMakeRange(0, attTextString.count))
for itemEmoji in emojiArray {
let rang = itemEmoji.range
let itemPound = text.substringWithRange(rang)
print("Emoji----:\(itemPound)")
}
//邮箱
let regexEmail = "\\w[-\\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\\.)+[A-Za-z]{2,14}"
let regularEmail = try! NSRegularExpression.init(pattern: regexEmail, options: NSRegularExpressionOptions.CaseInsensitive)
let EmailArray = regularEmail.matchesInString(attTextString, options: NSMatchingOptions.ReportProgress, range: NSMakeRange(0, attTextString.count))
for itemEmail in EmailArray {
let rang = itemEmail.range
let itemEmail = text.substringWithRange(rang)
print("Email----:\(itemEmail)")
attText.addAttribute(NSLinkAttributeName, value: itemEmail, range: rang)
}
//手机
let regexPhone = "0?(13|14|15|18)[0-9]{9}"
let regularPhone = try! NSRegularExpression.init(pattern: regexPhone, options: NSRegularExpressionOptions.CaseInsensitive)
let phoneArray = regularPhone.matchesInString(attTextString, options: NSMatchingOptions.ReportProgress, range: NSMakeRange(0, attTextString.count))
for itemPhone in phoneArray {
let rang = itemPhone.range
let itemPhone = text.substringWithRange(rang)
print("Phone----:\(itemPhone)")
}
attText.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(14), range: NSMakeRange(0, attTextString.count))
attText.addAttribute(NSForegroundColorAttributeName, value: RGBA(119, g: 128, b: 135, a: 1), range: NSMakeRange(0, attTextString.count))
let paragraph = NSMutableParagraphStyle()
attText.addAttribute(NSParagraphStyleAttributeName, value: paragraph, range: NSMakeRange(0, attTextString.count))
return attText
}
}
| mit | 91c7b0b244ddfa18605a927eb72d54c1 | 42.098214 | 155 | 0.627926 | 4.597143 | false | false | false | false |
danialzahid94/template-project-ios | TemplateProject/Utilities/IBInspectables/ShadowButton.swift | 1 | 945 | //
// ShadowView.swift
// Pros and Cons
//
// Created by Danial Zahid on 9/11/15.
// Copyright © 2015 Danial Zahid. All rights reserved.
//
import UIKit
class ShadowButton: UIButton {
//MARK: - IBInspectables
@IBInspectable var shadowColor : UIColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5)
@IBInspectable var shadowOffset : CGSize = CGSizeMake(3, 3)
@IBInspectable var shadowRadius : CGFloat = CGFloat(3.0)
@IBInspectable var shadowOpacity : Float = 1
//MARK: - View lifecycle
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
layer.shadowColor = shadowColor.CGColor
layer.shadowOffset = shadowOffset
layer.shadowRadius = shadowRadius
layer.shadowOpacity = shadowOpacity
}
}
| mit | 2d57d654c8cef576f6aa795484edbc6a | 25.971429 | 93 | 0.662076 | 4.495238 | false | false | false | false |
loiwu/SCoreData | WorldCup/WorldCup/AppDelegate.swift | 1 | 2908 | //
// AppDelegate.swift
// WorldCup
//
// Created by loi on 1/28/15.
// Copyright (c) 2015 GWrabbit. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
lazy var coreDataStack = CoreDataStack()
func application(application: UIApplication,
didFinishLaunchingWithOptions
launchOptions: [NSObject: AnyObject]?) -> Bool {
importJSONSeedDataIfNeeded()
let navController = window!.rootViewController as UINavigationController
let viewController = navController.topViewController as ViewController
viewController.coreDataStack = coreDataStack
return true
}
func applicationWillTerminate(application: UIApplication) {
coreDataStack.saveContext()
}
func importJSONSeedDataIfNeeded() {
let fetchRequest = NSFetchRequest(entityName: "Team")
var error: NSError? = nil
let results =
coreDataStack.context.countForFetchRequest(fetchRequest,
error: &error)
if (results == 0) {
var fetchError: NSError? = nil
if let results =
coreDataStack.context.executeFetchRequest(fetchRequest,
error: &fetchError) {
for object in results {
let team = object as Team
coreDataStack.context.deleteObject(team)
}
}
coreDataStack.saveContext()
importJSONSeedData()
}
}
func importJSONSeedData() {
let jsonURL = NSBundle.mainBundle().URLForResource("seed", withExtension: "json")
let jsonData = NSData(contentsOfURL: jsonURL!)
var error: NSError? = nil
let jsonArray = NSJSONSerialization.JSONObjectWithData(jsonData!, options: nil, error: &error) as NSArray
let entity = NSEntityDescription.entityForName("Team", inManagedObjectContext: coreDataStack.context)
for jsonDictionary in jsonArray {
let teamName = jsonDictionary["teamName"] as String
let zone = jsonDictionary["qualifyingZone"] as String
let imageName = jsonDictionary["imageName"] as String
let wins = jsonDictionary["wins"] as NSNumber
let team = Team(entity: entity!,
insertIntoManagedObjectContext: coreDataStack.context)
team.teamName = teamName
team.imageName = imageName
team.qualifyingZone = zone
team.wins = wins
}
coreDataStack.saveContext()
println("Imported \(jsonArray.count) teams")
}
}
| mit | c0adfc7923d8224d0fd2d9873ab721b2 | 31.311111 | 113 | 0.585282 | 6.174098 | false | false | false | false |
shou7783/AnimatedCheckButton | AnimatedCheckButton/AnimatedCheckButton.swift | 1 | 10734 | //
// AnimatedCheckButton.swift
// AnimatedCheckButton
//
// The MIT License (MIT)
//
// Copyright (c) 2016 MengHsiu Chang
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import UIKit
public class AnimatedCheckButton: UIButton {
// Public Property
public var duration: Double = 0.5
public var circleAlpha: CGFloat = 0.2 {
didSet {
circleLayer.strokeColor = self.color.colorWithAlphaComponent(circleAlpha).CGColor
}
}
public var color: UIColor = UIColor.blueColor() {
didSet {
circleLayer.strokeColor = color.colorWithAlphaComponent(self.circleAlpha).CGColor
animatedLayer.strokeColor = color.CGColor
}
}
public var lineWidth: CGFloat = 8 {
didSet {
circleLayer.lineWidth = lineWidth
animatedLayer.lineWidth = lineWidth
}
}
override public var selected: Bool {
didSet {
if selected {
self.selectAnimation()
} else {
self.deselectAnimation()
}
}
}
var animatedLayer: CAShapeLayer = CAShapeLayer()
var circleLayer: CAShapeLayer = CAShapeLayer()
private let strokeStart_initValue: CGFloat = 0
private let strokeStart_completionValue : CGFloat = 0.815
private let strokeEnd_initValue: CGFloat = 0.735
private let strokeEnd_completionValue : CGFloat = 0.98
private let animationOffset: CGFloat = 0.02
private var circleSize: CGSize {
get {
var newSize = self.frame.size
if (self.frame.width > self.frame.height) {
newSize = CGSizeMake(self.frame.height, self.frame.height)
} else if (frame.width < frame.height) {
newSize = CGSizeMake(self.frame.width, self.frame.width)
}
return newSize
}
}
override init(frame: CGRect) {
super.init(frame: frame)
self.setupView()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setupView()
}
private func setupView() {
self.color = self.tintColor
circleLayer.path = UIBezierPath(ovalInRect: self.bounds).CGPath
circleLayer.fillColor = UIColor.clearColor().CGColor
circleLayer.strokeColor = self.color.colorWithAlphaComponent(self.circleAlpha).CGColor
circleLayer.lineWidth = self.lineWidth
animatedLayer.path = self.getAnimatedPath().CGPath
animatedLayer.fillColor = UIColor.clearColor().CGColor
animatedLayer.lineJoin = "round"
animatedLayer.lineCap = "round"
animatedLayer.strokeEnd = strokeEnd_initValue
animatedLayer.strokeColor = self.color.CGColor
animatedLayer.lineWidth = self.lineWidth
self.layer.addSublayer(self.animatedLayer)
self.layer.addSublayer(self.circleLayer)
self.addTargets()
}
private func addTargets() {
//===============
// add target
//===============
self.addTarget(self, action: #selector(AnimatedCheckButton.touchDown(_:)), forControlEvents: UIControlEvents.TouchDown)
self.addTarget(self, action: #selector(AnimatedCheckButton.touchUpInside(_:)), forControlEvents: UIControlEvents.TouchUpInside)
self.addTarget(self, action: #selector(AnimatedCheckButton.touchDragExit(_:)), forControlEvents: UIControlEvents.TouchDragExit)
self.addTarget(self, action: #selector(AnimatedCheckButton.touchDragEnter(_:)), forControlEvents: UIControlEvents.TouchDragEnter)
self.addTarget(self, action: #selector(AnimatedCheckButton.touchCancel(_:)), forControlEvents: UIControlEvents.TouchCancel)
}
func touchDown(sender: AnimatedCheckButton) {
self.layer.opacity = 0.4
}
func touchUpInside(sender: AnimatedCheckButton) {
self.layer.opacity = 1.0
self.selected = !self.selected
}
func touchDragExit(sender: AnimatedCheckButton) {
self.layer.opacity = 1.0
}
func touchDragEnter(sender: AnimatedCheckButton) {
self.layer.opacity = 0.4
}
func touchCancel(sender: AnimatedCheckButton
) {
self.layer.opacity = 1.0
}
private func getAnimatedPath() -> UIBezierPath {
let size = self.circleSize
let bPath = UIBezierPath(arcCenter: CGPointMake(size.width/2, size.height/2), radius: size.height/2, startAngle: 3.15*CGFloat(M_PI), endAngle: 1.15*CGFloat(M_PI), clockwise: false)
bPath.addLineToPoint(CGPointMake(size.width*10.5/25, size.height*17/25))
bPath.addLineToPoint(CGPointMake(size.width*21/25, size.height*7/25))
return bPath
}
override public func layoutSubviews() {
super.layoutSubviews()
circleLayer.path = UIBezierPath(ovalInRect: CGRect(origin: CGPointZero, size: self.circleSize)).CGPath
animatedLayer.path = self.getAnimatedPath().CGPath
}
override public func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool {
let size = self.circleSize
if (point.x < size.width && point.y < size.height) {
return true;
}
return false;
}
private func selectAnimation() {
let animation = CABasicAnimation(keyPath: "strokeStart")
animation.fromValue = strokeStart_initValue
animation.toValue = strokeStart_completionValue + animationOffset
animation.duration = self.duration * 0.8
animation.fillMode = kCAFillModeForwards
animation.removedOnCompletion = false
let endAnimation = CABasicAnimation(keyPath: "strokeEnd")
endAnimation.fromValue = strokeEnd_initValue
endAnimation.toValue = strokeEnd_completionValue + animationOffset
endAnimation.duration = self.duration * 0.8
endAnimation.fillMode = kCAFillModeForwards
endAnimation.removedOnCompletion = false
let sanimation = CABasicAnimation(keyPath: "strokeStart")
sanimation.beginTime = self.duration * 0.8
sanimation.fromValue = strokeStart_completionValue + animationOffset
sanimation.toValue = strokeStart_completionValue
sanimation.duration = self.duration * 0.2
sanimation.fillMode = kCAFillModeForwards
sanimation.removedOnCompletion = false
let eAnimation = CABasicAnimation(keyPath: "strokeEnd")
eAnimation.beginTime = self.duration * 0.8
eAnimation.fromValue = strokeEnd_completionValue + animationOffset
eAnimation.toValue = strokeEnd_completionValue
eAnimation.duration = self.duration * 0.2
eAnimation.fillMode = kCAFillModeForwards
eAnimation.removedOnCompletion = false
let animationGroup = CAAnimationGroup()
animationGroup.fillMode = kCAFillModeForwards
animationGroup.removedOnCompletion = false
animationGroup.duration = self.duration;
animationGroup.animations = [animation, endAnimation, sanimation, eAnimation]
animationGroup.delegate = self
animationGroup.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
animatedLayer.addAnimation(animationGroup, forKey: "ff")
}
private func deselectAnimation() {
let animation = CABasicAnimation(keyPath: "strokeStart")
animation.fromValue = strokeStart_completionValue
animation.toValue = strokeStart_completionValue + animationOffset
animation.duration = self.duration * 0.2
animation.fillMode = kCAFillModeForwards
animation.removedOnCompletion = false
let endAnimation = CABasicAnimation(keyPath: "strokeEnd")
endAnimation.fromValue = strokeEnd_completionValue
endAnimation.toValue = strokeEnd_completionValue + animationOffset
endAnimation.duration = self.duration * 0.2
endAnimation.fillMode = kCAFillModeForwards
endAnimation.removedOnCompletion = false
let sanimation = CABasicAnimation(keyPath: "strokeStart")
sanimation.beginTime = self.duration * 0.2
sanimation.fromValue = strokeStart_completionValue + animationOffset
sanimation.toValue = strokeStart_initValue
sanimation.duration = self.duration * 0.8
sanimation.fillMode = kCAFillModeForwards
sanimation.removedOnCompletion = false
let eAnimation = CABasicAnimation(keyPath: "strokeEnd")
eAnimation.beginTime = self.duration * 0.2
eAnimation.fromValue = strokeEnd_completionValue + animationOffset
eAnimation.toValue = strokeEnd_initValue
eAnimation.duration = self.duration * 0.8
eAnimation.fillMode = kCAFillModeForwards
eAnimation.removedOnCompletion = false
let animationGroup = CAAnimationGroup()
animationGroup.fillMode = kCAFillModeForwards
animationGroup.removedOnCompletion = false
animationGroup.duration = self.duration
animationGroup.animations = [animation, endAnimation, sanimation, eAnimation]
animationGroup.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn)
animationGroup.delegate = self
animatedLayer.addAnimation(animationGroup, forKey: "ff")
}
override public func animationDidStart(anim: CAAnimation) {
self.userInteractionEnabled = false
}
override public func animationDidStop(anim: CAAnimation, finished flag: Bool) {
self.userInteractionEnabled = true
}
}
| mit | 9710ee6efe65c3a00e54deffb11b6e55 | 39.50566 | 188 | 0.674865 | 5.140805 | false | false | false | false |
mpclarkson/vapor | Sources/Generator/main.swift | 1 | 6173 | #if !os(Linux)
import Foundation
let GENERIC_MAP = ["T", "U", "V", "W", "X"]
let MAX_PARAMS = GENERIC_MAP.count
struct Func: CustomStringConvertible {
enum Method {
case get, post, put, patch, delete, options
}
var method: Method
var params: [Param]
var description: String {
let wildcards = params.filter { param in
return param.type == .Wildcard
}
var f = ""
f += "\tpublic func "
f += "\(method)".lowercased()
//generic <>
if wildcards.count > 0 {
let genericsString = wildcards.map { wildcard in
return "\(wildcard.generic): StringInitializable"
}.joined(separator: ", ")
f += "<\(genericsString)>"
}
let paramsString = params.enumerated().map { (index, param) in
if index > 0 {
return "_ \(param)"
} else {
return param.description
}
}.joined(separator: ", ")
f += "(\(paramsString), handler: (Request"
//handler params
if wildcards.count > 0 {
let genericsString = wildcards.map { wildcard in
return wildcard.generic
}.joined(separator: ", ")
f += ", \(genericsString)) throws -> ResponseRepresentable) {\n"
} else {
f += ") throws -> ResponseRepresentable) {\n"
}
let pathString = params.map { param in
if param.type == .Wildcard {
return ":\(param.name)"
}
return "\\(\(param.name))"
}.joined(separator: "/")
f += "\t\tself.add(.\(method), path: \"\(pathString)\") { request in\n"
//function body
if wildcards.count > 0 {
//grab from request params
for wildcard in wildcards {
f += "\t\t\tguard let v\(wildcard.name) = request.parameters[\"\(wildcard.name)\"] else {\n"
f += "\t\t\t\tthrow Abort.badRequest\n"
f += "\t\t\t}\n"
}
f += "\n"
//try
for wildcard in wildcards {
f += "\t\t\tlet e\(wildcard.name) = try \(wildcard.generic)(from: v\(wildcard.name))\n"
}
f += "\n"
//ensure conversion worked
for wildcard in wildcards {
f += "\t\t\tguard let c\(wildcard.name) = e\(wildcard.name) else {\n"
f += "\t\t\t\tthrow Abort.invalidParameter(\"\(wildcard.name)\", \(wildcard.generic).self)\n"
f += "\t\t\t}\n"
}
f += "\n"
let wildcardString = wildcards.map { wildcard in
return "c\(wildcard.name)"
}.joined(separator: ", ")
f += "\t\t\treturn try handler(request, \(wildcardString))\n"
} else {
f += "\t\t\treturn try handler(request)\n"
}
f += "\t\t}\n"
f += "\t}"
return f
}
}
func paramTypeCount(type: Param.`Type`, params: [Param]) -> Int {
var i = 0
for param in params {
if param.type == type {
i += 1
}
}
return i
}
struct Param: CustomStringConvertible {
var name: String
var type: Type
var generic: String
var description: String {
var description = "\(name): "
if type == .Wildcard {
description += "\(generic).Type"
} else {
description += "String"
}
return description
}
enum `Type` {
case Path, Wildcard
}
static var types: [Type] = [.Path, .Wildcard]
static func addTypePermutations(toArray paramsArray: [[Param]]) -> [[Param]] {
var permParamsArray: [[Param]] = []
for paramArray in paramsArray {
for type in Param.types {
var mutableParamArray = paramArray
var name = ""
if type == .Wildcard {
name = "w"
} else {
name = "p"
}
let count = paramTypeCount(type, params: paramArray)
name += "\(count)"
let generic = GENERIC_MAP[count]
let param = Param(name: name, type: type, generic: generic)
mutableParamArray.append(param)
permParamsArray.append(mutableParamArray)
}
}
return permParamsArray
}
}
var paramPermutations: [[Param]] = []
for paramCount in 0...MAX_PARAMS {
var perms: [[Param]] = [[]]
for _ in 0..<paramCount {
perms = Param.addTypePermutations(toArray: perms)
}
paramPermutations += perms
}
var generated = "// *** GENERATED CODE ***\n"
generated += "// \(NSDate())\n"
generated += "//\n"
generated += "// DO NOT EDIT THIS FILE OR CHANGES WILL BE OVERWRITTEN\n\n"
generated += "extension Application {\n\n"
for method: Func.Method in [.get, .post, .put, .patch, .delete, .options] {
for params in paramPermutations {
guard params.count > 0 else {
continue
}
var f = Func(method: method, params: params)
generated += "\(f)\n\n"
}
}
generated += "}\n"
if Process.arguments.count < 2 {
fatalError("Please pass $SRCROOT as a parameter")
}
let path = Process.arguments[1].replacingOccurrences(of: "XcodeProject", with: "")
let url = NSURL(fileURLWithPath: path + "/Sources/Vapor/Core/Generated.swift")
do{
// writing to disk
try generated.write(to: url, atomically: true, encoding: NSUTF8StringEncoding)
print("File created at \(url)")
} catch let error as NSError {
print("Error writing generated file at \(url)")
print(error.localizedDescription)
}
#endif | mit | f0c298e58c6c83585d59dd4a0c2d1429 | 26.198238 | 109 | 0.480642 | 4.532305 | false | false | false | false |
yangxiaodongcn/iOSAppBase | iOSAppBase/iOSAppBase/Tools/Device/Device.swift | 1 | 7129 | //
// Device.swift
// Device
//
// Created by Lucas Ortis on 30/10/2015.
// Copyright © 2015 Ekhoo. All rights reserved.
//
import UIKit
public class Device {
static fileprivate func getVersionCode() -> String {
var systemInfo = utsname()
uname(&systemInfo)
let versionCode: String = String(validatingUTF8: NSString(bytes: &systemInfo.machine, length: Int(_SYS_NAMELEN), encoding: String.Encoding.ascii.rawValue)!.utf8String!)!
return versionCode
}
static fileprivate func getVersion(code: String) -> Version {
switch code {
/*** iPhone ***/
case "iPhone3,1", "iPhone3,2", "iPhone3,3": return Version.iPhone4
case "iPhone4,1", "iPhone4,2", "iPhone4,3": return Version.iPhone4S
case "iPhone5,1", "iPhone5,2": return Version.iPhone5
case "iPhone5,3", "iPhone5,4": return Version.iPhone5C
case "iPhone6,1", "iPhone6,2": return Version.iPhone5S
case "iPhone7,2": return Version.iPhone6
case "iPhone7,1": return Version.iPhone6Plus
case "iPhone8,1": return Version.iPhone6S
case "iPhone8,2": return Version.iPhone6SPlus
case "iPhone8,4": return Version.iPhoneSE
case "iPhone9,1", "iPhone9,3": return Version.iPhone7
case "iPhone9,2", "iPhone9,4": return Version.iPhone7Plus
/*** iPad ***/
case "iPad1,1": return Version.iPad1
case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4": return Version.iPad2
case "iPad3,1", "iPad3,2", "iPad3,3": return Version.iPad3
case "iPad3,4", "iPad3,5", "iPad3,6": return Version.iPad4
case "iPad4,1", "iPad4,2", "iPad4,3": return Version.iPadAir
case "iPad5,3", "iPad5,4": return Version.iPadAir2
case "iPad2,5", "iPad2,6", "iPad2,7": return Version.iPadMini
case "iPad4,4", "iPad4,5", "iPad4,6": return Version.iPadMini2
case "iPad4,7", "iPad4,8", "iPad4,9": return Version.iPadMini3
case "iPad5,1", "iPad5,2": return Version.iPadMini4
case "iPad6,3", "iPad6,4", "iPad6,7", "iPad6,8": return Version.iPadPro
/*** iPod ***/
case "iPod1,1": return Version.iPodTouch1Gen
case "iPod2,1": return Version.iPodTouch2Gen
case "iPod3,1": return Version.iPodTouch3Gen
case "iPod4,1": return Version.iPodTouch4Gen
case "iPod5,1": return Version.iPodTouch5Gen
case "iPod7,1": return Version.iPodTouch6Gen
/*** Simulator ***/
case "i386", "x86_64": return Version.simulator
default: return Version.unknown
}
}
static fileprivate func getType(code: String) -> Type {
let versionCode = Device.getVersionCode()
switch versionCode {
case "iPhone3,1", "iPhone3,2", "iPhone3,3",
"iPhone4,1", "iPhone4,2", "iPhone4,3",
"iPhone5,1", "iPhone5,2",
"iPhone5,3", "iPhone5,4",
"iPhone6,1", "iPhone6,2",
"iPhone7,2",
"iPhone7,1",
"iPhone8,1",
"iPhone8,2",
"iPhone8,4",
"iPhone9,1", "iPhone9,3",
"iPhone9,2", "iPhone9,4": return Type.iPhone
case "iPad1,1",
"iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4",
"iPad3,1", "iPad3,2", "iPad3,3",
"iPad3,4", "iPad3,5", "iPad3,6",
"iPad4,1", "iPad4,2", "iPad4,3",
"iPad5,3", "iPad5,4",
"iPad2,5", "iPad2,6", "iPad2,7",
"iPad4,4", "iPad4,5", "iPad4,6",
"iPad4,7", "iPad4,8", "iPad4,9",
"iPad5,1", "iPad5,2",
"iPad6,3", "iPad6,4", "iPad6,7", "iPad6,8": return Type.iPad
case "iPod1,1",
"iPod2,1",
"iPod3,1",
"iPod4,1",
"iPod5,1",
"iPod7,1":
return Type.iPod
case "i386", "x86_64": return Type.simulator
default: return Type.unknown
}
}
static public var version: Version {
let versionName = Device.getVersionCode()
return Device.getVersion(code: versionName)
}
static public var size: Size {
let w: Double = Double(UIScreen.main.bounds.width)
let h: Double = Double(UIScreen.main.bounds.height)
let screenHeight: Double = max(w, h)
switch screenHeight {
case 480:
return Size.screen3_5Inch
case 568:
return Size.screen4_0Inch
case 667:
return UIScreen.main.scale == 3.0 ? Size.screen5_5Inch : Size.screen4_7Inch
case 736:
return Size.screen5_5Inch
case 1024:
switch Device.version {
case .iPadMini,.iPadMini2,.iPadMini3,.iPadMini4:
return Size.screen7_9Inch
default:
return Size.screen9_7Inch
}
case 1366:
return Size.screen12_9Inch
default:
return Size.unknown
}
}
static public var type: Type {
let versionName = Device.getVersionCode()
return Device.getType(code: versionName)
}
static public func isEqualToScreenSize(_ size: Size) -> Bool {
return size == Device.size ? true : false;
}
static public func isLargerThanScreenSize(_ size: Size) -> Bool {
return size.rawValue < Device.size.rawValue ? true : false;
}
static public func isSmallerThanScreenSize(_ size: Size) -> Bool {
return size.rawValue > Device.size.rawValue ? true : false;
}
static public func isRetina() -> Bool {
return UIScreen.main.scale > 1.0
}
static public func isPad() -> Bool {
return Device.type == .iPad
}
static public func isPhone() -> Bool {
return Device.type == .iPhone
}
static public func isPod() -> Bool {
return Device.type == .iPod
}
static public func isSimulator() -> Bool {
return Device.type == .simulator
}
}
| mit | 13caf114e735c4f43e04f1a6cc611d88 | 38.6 | 177 | 0.475449 | 4.20531 | false | false | false | false |
Aster0id/Swift-StudyNotes | Swift-StudyNotes/L2-S4.swift | 1 | 8980 | //
// L2-S4.swift
// Swift-StudyNotes
//
// Created by 牛萌 on 15/5/13.
// Copyright (c) 2015年 Aster0id.Team. All rights reserved.
//
import Foundation
/**
* @class
* @brief 2.4 集合类型
*/
class Lesson2Section4 {
func run(flag:Bool) {
if !flag {
return
}
//MARK: Begin Runing
println("\n\n------------------------------------")
println(">>>>> Lesson2-Section4 begin running\n\n")
//!!!!! Swift 语言里的数组和字典中存储的数据值类型必须明确。
// -----------------------------------------
// MARK: 数组 (Array)
// -----------------------------------------
/*
Swift 数组对存储数据有具体要求。
不同于 Objective-C 的 NSArray 和 NSMutableArray 类,他们可以存储任何类型的实例而且不提供他们返回对象的任何本质信息。
在 Swift 中, 数据值在被存储进入某个数组之前类型必须明确,方法是通过显式的类型标注或类型推断, 而且不是必须是 class 类型。
例如: 如果我们创建了一个 Int 值类型的数组,我们不能往其中插入任何不是 Int 类型的数据。
Swift 中的数组是类型安全的,并且它们中包含的类型必须明确。
*/
// 写 Swift 数组应该遵循像 Array<SomeType>这样的形式,其中 sometype 是这个数组中唯一允许存在的数据类型。
var array1: Array<String>
var shoppingList: [String] = ["Eggs", "Milk"]
var shoppingList1:[Dictionary<String,Int>] = [["Eggs":34]]
//-- 空数组判断
// 使用布尔项 isEmpty 来作为检查 count 属性的值是否为 0 的捷径。
if !shoppingList.isEmpty {
println("The shopping list is not empty.")
} else {
println("The shopping list is empty.")
}
//## 打印: The shopping list is not empty. (shoppinglist 不是空的)
//-- 数组添加元素
// 可以使用 append 方法在数组后面添加新的数据项:
shoppingList.append("Flour")
// 除此之外,使用加法赋值运算符(+=)也可以直接在数组后面添加数据项:
shoppingList += ["Baking Powder"]
// 我们也可以使用加法赋值运算符(+=)直接添加拥有相同类型数据的数组。
shoppingList += ["Chocolate Spread", "Cheese", "Butter"]
//## 结果: shoppingList中有7个元素
// ["Eggs", "Milk", "Flour", "Baking Powder", "Chocolate Spread", "Cheese", "Butter"]
//-- 数组修改元素
shoppingList[0] = "Six eggs"
shoppingList[3...6] = ["Bananas", "Apples"]
//## 结果: shoppingList中有5个元素
// ["Six eggs", "Milk", "Flour", "Bananas", "Apples"]
//-- 数组插入元素
shoppingList.insert("Maple Syrup", atIndex: 0)
//## 结果: shoppingList中有6个元素
// ["Maple Syrup", "Six eggs", "Milk", "Flour", "Bananas", "Apples"]
//-- 数组移除元素
shoppingList.removeAtIndex(3)
//~~ 移除元素的高级用法
let apples = shoppingList.removeLast()
// 数组的最后一项被移除了
// shoppingList现在只有4项, ["Maple Syrup", "Six eggs", "Milk", "Bananas"]
// apples 常量的值现在等于"Apples" 字符串
//-- 数组的遍历
for item in shoppingList {
println(item)
}
/*
//## 打印:
Maple Syrup
Six eggs
Milk
Bananas
*/
/*
//~~ 高级用法:
如果我们同时需要每个数据项的值和索引值,可以使用全局 enumerate 函数来进行数组遍 历。
enumerate 返回一个由每一个数据项索引值和数据值组成的键值对组。
我们可以把这个键值对组分解成临时常量或者变量来进行遍历
*/
for (index, value) in enumerate(shoppingList) {
println("Item \(index + 1): \(value)")
}
/*
//## 打印:
Item 1: Maple Syrup
Item 2: Six eggs
Item 3: Milk
Item 4: Bananas
*/
//~~ 新语法:
//-- 数组的构造方法
// Swift 中的 Array 类型还提供一个可以创建特定大小并且所有数据都被默认的构造方法。
// 我们可以把准备加入新数组的数据项数量(count)和适当类型的初始值(repeatedValue)传 入数组构造函数:
var threeDoubles = [Double](count: 3, repeatedValue:1.0)
//## 结果: threeDoubles 是一种[Double]数组, 等于 [1.0, 1.0, 1.0]
var anotherThreeDoubles = Array(count: 3, repeatedValue: 2.5)
//## 结果: anotherThreeDoubles 是一种[Double]数组, 等于 [2.5, 2.5, 2.5]
var sixDoubles = threeDoubles + anotherThreeDoubles
//## 打印: sixDoubles 被推断为[Double]数组, 等于[1.0, 1.0, 1.0, 2.5, 2.5, 2.5]
// -----------------------------------------
// MARK: 字典 (Dictionary)
// -----------------------------------------
// Swift 的字典使用 Dictionary<KeyType, ValueType>定义,其中KeyType是字典中键的数据类型, ValueType是字典中对应于这些键所存储值的数据类型。
var airports: Dictionary<String, String> = [
"TYO": "Tokyo",
"DUB": "Dublin"]
//-- 字典更新键值对
//updateValue(forKey:)函数会返回包含一个字典值类型的可选值。举例来说:对于存储 String 值的字典,这个函数会返回一个 String?或者“可选 String”类型的值。如果值存在,则这个可选值值等于被替换的值,否则将会是 nil。
if let oldValue = airports.updateValue("Dublin Internation", forKey: "DUB") {
println("The old value for DUB was \(oldValue).")
}
//## 打印: "The old value for DUB was Dublin."(dub 原值是 dublin)
//-- 字典删除键值对
if let removedValue = airports.removeValueForKey("DUB") {
println("The removed airport's name is \(removedValue).")
} else {
println("The airports dictionary does not contain a value for DUB.")
}
//## 打印 "The removed airport's name is Dublin International."(被移除的 机场名字是都柏林国际)
//-- 字典的遍历
for (airportCode, airportName) in airports {
println("\(airportCode): \(airportName)")
}
//## 打印: "TYO: Tokyo"
//-- 字典的构造方法
var namesOfIntegers = Dictionary<Int, String>()
namesOfIntegers[16] = "sixteen"
// namesOfIntegers 现在包含一个键值对
namesOfIntegers = [:]
// namesOfIntegers 又成为了一个 Int, String类型的空字典
// -----------------------------------------
// MARK: 集合的可变性
// -----------------------------------------
/*
数组和字典都是在单个集合中存储可变值。如果我们创建一个数组或者字典并且把它分配成一个变量,这个集合将会是可变的。这意味着我们可以在创建之后添加更多或移除已存在的 数据项来改变这个集合的大小。与此相反,如果我们把数组或字典分配成常量,那么他就是 不可变的,它的大小不能被改变。
对字典来说,不可变性也意味着我们不能替换其中任何现有键所对应的值。不可变字典的内 容在被首次设定之后不能更改。 不可变行对数组来说有一点不同,当然我们不能试着改变 任何不可变数组的大小,但是我们可以重新设定相对现存索引所对应的值。这使得 Swift 数组在大小被固定的时候依然可以做的很棒。
Swift 数组的可变性行为同时影响了数组实例如何被分配和修改,想获取更多信息,请参见 Assignment and Copy Behavior for Collection Types。
注意: 在我们不需要改变数组大小的时候创建不可变数组是很好的习惯。如此 Swift 编译 器可以优化我们创建的集合。
*/
//MARK: End Runing
println("\n\nLesson2-Section4 end running <<<<<<<")
println("------------------------------------\n\n")
}
} | mit | bba8e69ac6013b5af10eacf77772166b | 29.240909 | 153 | 0.498948 | 3.712054 | false | false | false | false |
Loyolny/DateOfEaster | DateOfEaster.playground/Contents.swift | 1 | 449 | // DateOfEaster playground
import Foundation
import DateOfEaster
let easternEasterHundredYearsFromNow = Date.easternEasterDate(year: 2117)
let westernEasterHundredYearsFromNow = Date.westernEasterDate(year: 2117)
let westernPentecost = Date.westernPentecostDate(year: 2017)
let easternPentecost = Date.easternPentecostDate(year: 2016)
let corpusChristi = Date.corpusChristiDate(year: 2017)
let ashWednesday = Date.ashWednesdayDate(year: 1983)
| mit | 2a7f3896da1b704f8b71a8bccc92ffd1 | 28.933333 | 73 | 0.832962 | 3.096552 | false | false | false | false |
TriangleLeft/Flashcards | ios/Flashcards/UI/Main/DrawerViewCell.swift | 1 | 1313 | //
// DrawerViewCellTableViewCell.swift
// Flashcards
//
// Created by Aleksey Kurnosenko on 28.08.16.
// Copyright © 2016 TriangleLeft. All rights reserved.
//
import UIKit
class DrawerViewCell: UITableViewCell {
var flagImages = ["de":"germany", "fr":"france","es":"spain", "dn":"netherlands", "ru":"russia", "uk":"ukraine", "pt":"brazil", "vi":"viewtnam", "nb":"norway", "tr":"turkey", "sv":"sweden","da":"denmark","cy":"wales", "ga":"ireland","it":"italy", "pl":"polish", "he":"israel"]
@IBOutlet weak var levelLabel: UILabel!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var iconView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
selectionStyle = .None
}
func showLanguage(item: Language) {
iconView.image = getFlagImage(item.getId())
titleLabel.text = item.getName()
levelLabel.text = String(item.getLevel())
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
private func getFlagImage(id:String) -> UIImage? {
if let imageName:String = flagImages[id] {
return UIImage(named: imageName)
} else {
return UIImage(named: "unknown")
}
}
}
| apache-2.0 | 817ed2324f46d41cf12a5a3db004d6a9 | 31 | 280 | 0.616616 | 3.858824 | false | false | false | false |
flowsprenger/RxLifx-Swift | RxLifxApi/RxLifxApi/Command/DeviceGetGroupCommand.swift | 1 | 1654 | /*
Copyright 2017 Florian Sprenger
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import Foundation
import RxLifx
import LifxDomain
import RxSwift
public class DeviceGetGroupCommand {
public class func create(light: Light, ackRequired: Bool = false, responseRequired: Bool = false) -> Observable<Result<StateGroup>> {
let message = Message.createMessageWithPayload(GetGroup(), target: light.target, source: light.lightSource.source)
message.header.ackRequired = ackRequired
message.header.responseRequired = responseRequired
return AsyncLightCommand.sendMessage(lightSource: light.lightSource, light: light, message: message)
}
}
| mit | 768e907d2484a84528ef109082e6b472 | 50.6875 | 137 | 0.788392 | 4.646067 | false | false | false | false |
zSher/BulletThief | BulletThief/BulletThief/WaveEnemy.swift | 1 | 2091 | //
// WaveEnemy.swift
// BulletThief
//
// Created by Zachary on 5/16/15.
// Copyright (c) 2015 Zachary. All rights reserved.
//
import UIKit
import SpriteKit
class WaveEnemy: Enemy {
//MARK: - init -
init(){
var bulletEffects: [BulletEffectProtocol] = [TextureBulletEffect(textureName: "lineBullet"), FireDelayBulletEffect(delay: 3.5), SpeedBulletEffect(speed: 10), WavePathBulletEffect(dir: Directions.Down), StandardSpawnBulletEffect()]
super.init(textureName: "waveEnemy", bulletEffects: bulletEffects, numBullets: 1, bulletCount: 10, speed: 8, name: "enemy")
}
required init?(coder aDecoder: NSCoder) {
fatalError("init not implemented")
}
//MARK: - Methods -
//Always become disabled when killed
override func willDie() {
//Chance to disable
var chance = randomRange(0, 1)
if chance < 0.2 {
self.speed = 6
self.weakened = true
self.physicsBody?.categoryBitMask = CollisionCategories.None //become unhittable
var colorizeAction = SKAction.colorizeWithColor(UIColor.grayColor(), colorBlendFactor: 1, duration: 5.0)
var rotateAction = SKAction.repeatActionForever(SKAction.rotateByAngle(CGFloat(-M_PI * 2), duration: 10.0))
var groupAction = SKAction.group([rotateAction, colorizeAction])
self.runAction(groupAction)
} else {
super.willDie()
}
}
override func steal(player:Player){
player.gun!.addEffect(WavePathBulletEffect(dir: Directions.Up))
self.removeAllActions()
self.removeFromParent()
bulletManager.returnBullets(gun.bulletPool)
}
override func addToScene(scene: SKScene) {
var moveAction = SKAction.followPath(movementPath!.CGPath, asOffset: true, orientToPath: false, speed: self.speed)
var removeAction = SKAction.removeFromParent()
var onScreenActionGrp = SKAction.sequence([moveAction, removeAction])
scene.addChild(self)
self.runAction(onScreenActionGrp)
}
}
| mit | 80753b11c1b1de511826dea748d22897 | 34.440678 | 238 | 0.661406 | 4.293634 | false | false | false | false |
LipliStyle/Liplis-iOS | Liplis/ObjLiplisLogList.swift | 1 | 1822 | //
// ObjLiplisLogList.swift
// Liplis
//
// ログ管理クラス
//
//アップデート履歴
// 2015/04/17 ver0.1.0 作成
// 2015/05/09 ver1.0.0 リリース
// 2015/05/16 ver1.4.0 リファクタリング
//
// Created by sachin on 2015/04/17.
// Copyright (c) 2015年 sachin. All rights reserved.
//
import Foundation
class ObjLiplisLogList {
///=============================
/// プロパティ
internal var logList : Array<ObjLiplisLog> = []
//============================================================
//
//初期化処理
//
//============================================================
/**
コンストラクター
*/
internal init()
{
self.logList = Array<ObjLiplisLog>()
}
/**
ログアペンド
*/
internal func append(log : String, url : String)
{
var type : Int = 0
if(url == "")
{
type = 0
}
else
{
type = 1
}
//ログ追加
self.logList.append(ObjLiplisLog(log: log,url: url,type: type))
//100件以上あった場合、最初のデータを削除する
if logList.count > 100
{
self.logList.dequeue()
}
}
internal func append(log : String, url : String, type : Int)
{
//ログ追加
self.logList.append(ObjLiplisLog(log: log,url: url,type: type))
//100件以上あった場合、最初のデータを削除する
if logList.count > 100
{
self.logList.dequeue()
}
}
/**
一件のlogを取得する
*/
internal func getLog(idx : Int)->ObjLiplisLog {
return self.logList[idx]
}
} | mit | f66e1ddf3da1e390cef3cdca99db15b1 | 19.139241 | 71 | 0.435849 | 3.533333 | false | false | false | false |
codepgq/WeiBoDemo | PQWeiboDemo/PQWeiboDemo/classes/Index 首页/imageBrowser/PQImageBroserViewController.swift | 1 | 5096 | //
// PQImageBroserViewController.swift
// PQWeiboDemo
//
// Created by Mac on 16/10/15.
// Copyright © 2016年 ios. All rights reserved.
//
import UIKit
import SDWebImage
import SVProgressHUD
let imageBrowserIdentifier = "imageBrowserIdentifier"
class PQImageBroserViewController: UIViewController {
var largeUrls : Array<URL>?
var currentIndexPath : IndexPath?
init(currenIndex : IndexPath , ulrs : Array<URL>){
currentIndexPath = currenIndex
largeUrls = ulrs
super.init(nibName: nil, bundle: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
//设置UI
setupUI()
}
override func viewDidAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// collectionView.scrollToItem(at: currentIndexPath!, at: UICollectionViewScrollPosition.left, animated: false)
collectionView.isHidden = false
}
private func setupUI(){
view.addSubview(collectionView)
view.addSubview(saveBtn)
view.addSubview(closeBtn)
collectionView.frame = view.bounds
collectionView.backgroundColor = PQUtil.randomColor()
saveBtn.pq_AlignInner(type: pq_AlignType.BottomLeft, referView: view, size: CGSize(width : 80 , height : 44) , offset: CGPoint(x: 10, y: -10))
closeBtn.pq_AlignInner(type: pq_AlignType.BottomRight, referView: view, size: CGSize(width : 80 , height : 44) ,offset: CGPoint(x: -10, y: -10))
// 1、设置代理
collectionView.dataSource = self
// 2、注册cell
collectionView.register(PQImageBrowserCollectionViewCell.self, forCellWithReuseIdentifier: imageBrowserIdentifier)
}
private lazy var collectionView = UICollectionView(frame: PQUtil.screenBounds(), collectionViewLayout: ImageBrowserCollectionViewFlowLayout())
private lazy var saveBtn : UIButton = {
let btn = UIButton.createBtnWithTitle(title: "关闭", imageNamed: nil, selector: #selector(PQImageBroserViewController.closeBtnClick), target: self)
btn.backgroundColor = UIColor.gray
btn.setTitleColor(UIColor.white ,for: .normal)
return btn
}()
private lazy var closeBtn : UIButton = {
let btn = UIButton.createBtnWithTitle(title: "保存", imageNamed: nil, selector: #selector(PQImageBroserViewController.saveBtnClick), target: self)
btn.backgroundColor = UIColor.gray
btn.setTitleColor(UIColor.white ,for: .normal)
return btn
}()
@objc private func saveBtnClick(){
print("保存")
// 1、获取到显示的Cell
let index = collectionView.indexPathsForVisibleItems.last
let cell = collectionView.cellForItem(at: index!) as! PQImageBrowserCollectionViewCell
// 2、获取到图片
guard let image = cell.getVisitorImage() else {
SVProgressHUD.showError(withStatus: "图片未加载完成")
return
}
// 3、保存图片
UIImageWriteToSavedPhotosAlbum(image, self, #selector(PQImageBroserViewController.image(image:didFinishSavingWithError:contextInfo:)), nil)
}
func image(image:UIImage, didFinishSavingWithError error:NSError?, contextInfo:AnyObject){
if error == nil {
SVProgressHUD.showSuccess(withStatus: "保存成功")
}else{
SVProgressHUD.showError(withStatus: "保存失败")
}
}
@objc private func closeBtnClick(){
print("关闭")
dismiss(animated: true, completion: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//内部类
class ImageBrowserCollectionViewFlowLayout : UICollectionViewFlowLayout{
override func prepare() {
scrollDirection = .horizontal
minimumLineSpacing = 0
minimumInteritemSpacing = 0
itemSize = PQUtil.screenBounds().size
collectionView?.isPagingEnabled = true
collectionView?.bounces = false
collectionView?.showsVerticalScrollIndicator = false
collectionView?.showsHorizontalScrollIndicator = false
}
}
extension PQImageBroserViewController: UICollectionViewDataSource,PQImageBrowserCollectionViewCellDelegate{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return largeUrls?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: imageBrowserIdentifier, for: indexPath) as! PQImageBrowserCollectionViewCell
cell.imageURL = largeUrls![indexPath.item]
cell.backgroundColor = PQUtil.randomColor()
cell.imageBrowserDelegate = self
return cell
}
func browserDidClose(cell: PQImageBrowserCollectionViewCell) {
dismiss(animated: true, completion: nil)
}
}
| mit | d881f24e100f4157179902c3bb0a20e1 | 33.86014 | 154 | 0.674223 | 5.128601 | false | false | false | false |
jloloew/Smiley-Face | Smiley Face/ViewController.swift | 1 | 1681 | //
// ViewController.swift
// Smiley Face
//
// Created by Justin Loew on 8/20/15.
// Copyright © 2015 Justin Loew. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var faceView: FaceView! {
didSet {
faceView.dataSource = self
// enable pinch gestures in the FaceView using its pinch() handler
faceView.addGestureRecognizer(UIPinchGestureRecognizer(target: faceView, action: "pinch:"))
faceView.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: "handleHappinessChange:"))
}
}
var happiness = 0 { // 0 for sad, 100 for happy
didSet {
faceView.setNeedsDisplay()
}
}
func handleHappinessChange(gesture: UIPanGestureRecognizer) {
if gesture.state == .Changed || gesture.state == .Ended {
let translationAmount = gesture.translationInView(faceView)
happiness += Int(translationAmount.y / 2)
if happiness < 0 {
happiness = 0
}
if happiness > 100 {
happiness = 100
}
gesture.setTranslation(CGPointZero, inView: faceView)
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func shouldAutorotate() -> Bool {
faceView.setNeedsDisplay()
return true // support all orientations
}
}
// MARK: - FaceViewDataSource
extension ViewController: FaceViewDataSource {
func smileForFaceView(sender: FaceView) -> CGFloat {
// happiness is 0-100. The range for the smile is -1 to 1.
return CGFloat(happiness - 50) / 50.0
}
}
| gpl-2.0 | 3368547e97497b04e30dfafac141ade0 | 25.25 | 104 | 0.714286 | 3.888889 | false | false | false | false |
ahoppen/swift | stdlib/public/Distributed/DistributedMetadata.swift | 4 | 3832 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020-2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Swift
/// Get the parameter count from a mangled method name.
///
/// - Returns: May return a negative number to signal a decoding error.
@available(SwiftStdlib 5.7, *)
public // SPI Distributed
func _getParameterCount(mangledMethodName name: String) -> Int32 {
let nameUTF8 = Array(name.utf8)
return nameUTF8.withUnsafeBufferPointer { nameUTF8 in
return __getParameterCount(
nameUTF8.baseAddress!, UInt(nameUTF8.endIndex))
}
}
@available(SwiftStdlib 5.7, *)
@_silgen_name("swift_func_getParameterCount")
public // SPI Distributed
func __getParameterCount(
_ typeNameStart: UnsafePointer<UInt8>,
_ typeNameLength: UInt
) -> Int32
/// Write the Metadata of all the mangled methods name's
/// parameters into the provided buffer.
///
/// - Returns: the actual number of types written,
/// or negative value to signify an error
@available(SwiftStdlib 5.7, *)
public // SPI Distributed
func _getParameterTypeInfo(
mangledMethodName name: String,
genericEnv: UnsafeRawPointer?, // GenericEnvironmentDescriptor *
genericArguments: UnsafeRawPointer?,
into typesBuffer: Builtin.RawPointer, length typesLength: Int
) -> Int32 {
let nameUTF8 = Array(name.utf8)
return nameUTF8.withUnsafeBufferPointer { nameUTF8 in
return __getParameterTypeInfo(
nameUTF8.baseAddress!, UInt(nameUTF8.endIndex),
genericEnv, genericArguments, typesBuffer, typesLength)
}
}
/// - Returns: the actual number of types written,
/// or a negative value to signal decoding error.
@available(SwiftStdlib 5.7, *)
@_silgen_name("swift_func_getParameterTypeInfo")
public // SPI Distributed
func __getParameterTypeInfo(
_ typeNameStart: UnsafePointer<UInt8>, _ typeNameLength: UInt,
_ genericEnv: UnsafeRawPointer?, // GenericEnvironmentDescriptor *
_ genericArguments: UnsafeRawPointer?,
_ types: Builtin.RawPointer, _ typesLength: Int
) -> Int32
@available(SwiftStdlib 5.7, *)
public // SPI Distributed
func _getReturnTypeInfo(
mangledMethodName name: String,
genericEnv: UnsafeRawPointer?, // GenericEnvironmentDescriptor *
genericArguments: UnsafeRawPointer?
) -> Any.Type? {
let nameUTF8 = Array(name.utf8)
return nameUTF8.withUnsafeBufferPointer { nameUTF8 in
return __getReturnTypeInfo(nameUTF8.baseAddress!, UInt(nameUTF8.endIndex),
genericEnv, genericArguments)
}
}
@available(SwiftStdlib 5.7, *)
@_silgen_name("swift_func_getReturnTypeInfo")
public // SPI Distributed
func __getReturnTypeInfo(
_ typeNameStart: UnsafePointer<UInt8>,
_ typeNameLength: UInt,
_ genericEnv: UnsafeRawPointer?, // GenericEnvironmentDescriptor *
_ genericArguments: UnsafeRawPointer?
) -> Any.Type?
/// Retrieve a generic environment descriptor associated with
/// the given distributed target
@available(SwiftStdlib 5.7, *)
@_silgen_name("swift_distributed_getGenericEnvironment")
public // SPI Distributed
func _getGenericEnvironmentOfDistributedTarget(
_ targetNameStart: UnsafePointer<UInt8>,
_ targetNameLength: UInt
) -> UnsafeRawPointer?
@available(SwiftStdlib 5.7, *)
@_silgen_name("swift_distributed_getWitnessTables")
public // SPI Distributed
func _getWitnessTablesFor(
environment: UnsafeRawPointer,
genericArguments: UnsafeRawPointer
) -> (UnsafeRawPointer, Int)
| apache-2.0 | 98e1ca0e412c14abb53ff362ea9a14ce | 33.836364 | 80 | 0.708246 | 4.628019 | false | false | false | false |
ontouchstart/swift3-playground | single/今天是个好天气.playgroundbook/Contents/Chapters/今天是个好天气.playgroundchapter/Pages/今天是个好天气.playgroundpage/LiveView.swift | 1 | 283 | import UIKit
import PlaygroundSupport
let frame = CGRect(x: 0, y:0, width: 400, height: 300)
let label = UILabel(frame: frame)
label.text = "今天是个好天气"
label.textAlignment = .center
label.font = UIFont.boldSystemFont(ofSize: 60)
PlaygroundPage.current.liveView = label
| mit | bbd4e6f5eb85f003d3e9cba63484c485 | 25.9 | 54 | 0.762082 | 3.3625 | false | false | false | false |
e78l/swift-corelibs-foundation | Foundation/NSData.swift | 1 | 44738 | // 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 CoreFoundation
#if DEPLOYMENT_ENABLE_LIBDISPATCH
import Dispatch
#endif
extension NSData {
public struct ReadingOptions : OptionSet {
public let rawValue : UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
public static let mappedIfSafe = ReadingOptions(rawValue: UInt(1 << 0))
public static let uncached = ReadingOptions(rawValue: UInt(1 << 1))
public static let alwaysMapped = ReadingOptions(rawValue: UInt(1 << 2))
}
public struct WritingOptions : OptionSet {
public let rawValue : UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
public static let atomic = WritingOptions(rawValue: UInt(1 << 0))
public static let withoutOverwriting = WritingOptions(rawValue: UInt(1 << 1))
}
public struct SearchOptions : OptionSet {
public let rawValue : UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
public static let backwards = SearchOptions(rawValue: UInt(1 << 0))
public static let anchored = SearchOptions(rawValue: UInt(1 << 1))
}
public struct Base64EncodingOptions : OptionSet {
public let rawValue : UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
public static let lineLength64Characters = Base64EncodingOptions(rawValue: UInt(1 << 0))
public static let lineLength76Characters = Base64EncodingOptions(rawValue: UInt(1 << 1))
public static let endLineWithCarriageReturn = Base64EncodingOptions(rawValue: UInt(1 << 4))
public static let endLineWithLineFeed = Base64EncodingOptions(rawValue: UInt(1 << 5))
}
public struct Base64DecodingOptions : OptionSet {
public let rawValue : UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
public static let ignoreUnknownCharacters = Base64DecodingOptions(rawValue: UInt(1 << 0))
}
}
private final class _NSDataDeallocator {
var handler: (UnsafeMutableRawPointer, Int) -> Void = {_,_ in }
}
private let __kCFMutable: CFOptionFlags = 0x01
private let __kCFGrowable: CFOptionFlags = 0x02
private let __kCFBytesInline: CFOptionFlags = 2
private let __kCFUseAllocator: CFOptionFlags = 3
private let __kCFDontDeallocate: CFOptionFlags = 4
open class NSData : NSObject, NSCopying, NSMutableCopying, NSSecureCoding {
typealias CFType = CFData
private var _base = _CFInfo(typeID: CFDataGetTypeID())
private var _length: CFIndex = 0
private var _capacity: CFIndex = 0
private var _deallocator: UnsafeMutableRawPointer? = nil // for CF only
private var _deallocHandler: _NSDataDeallocator? = _NSDataDeallocator() // for Swift
private var _bytes: UnsafeMutablePointer<UInt8>? = nil
internal var _cfObject: CFType {
if type(of: self) === NSData.self || type(of: self) === NSMutableData.self {
return unsafeBitCast(self, to: CFType.self)
} else {
let bytePtr = self.bytes.bindMemory(to: UInt8.self, capacity: self.length)
return CFDataCreate(kCFAllocatorSystemDefault, bytePtr, self.length)
}
}
internal func _providesConcreteBacking() -> Bool {
return type(of: self) === NSData.self || type(of: self) === NSMutableData.self
}
override open var _cfTypeID: CFTypeID {
return CFDataGetTypeID()
}
// NOTE: the deallocator block here is implicitly @escaping by virtue of it being optional
private func _init(bytes: UnsafeMutableRawPointer?, length: Int, copy: Bool = false, deallocator: ((UnsafeMutableRawPointer, Int) -> Void)? = nil) {
let options : CFOptionFlags = (type(of: self) == NSMutableData.self) ? __kCFMutable | __kCFGrowable : 0x0
let bytePtr = bytes?.bindMemory(to: UInt8.self, capacity: length)
if copy {
_CFDataInit(unsafeBitCast(self, to: CFMutableData.self), options, length, bytePtr, length, false)
if let handler = deallocator {
handler(bytes!, length)
}
} else {
if let handler = deallocator {
_deallocHandler!.handler = handler
}
// The data initialization should flag that CF should not deallocate which leaves the handler a chance to deallocate instead
_CFDataInit(unsafeBitCast(self, to: CFMutableData.self), options | __kCFDontDeallocate, length, bytePtr, length, true)
}
}
fileprivate init(bytes: UnsafeMutableRawPointer?, length: Int, copy: Bool = false, deallocator: ((UnsafeMutableRawPointer, Int) -> Void)? = nil) {
super.init()
_init(bytes: bytes, length: length, copy: copy, deallocator: deallocator)
}
public override init() {
super.init()
_init(bytes: nil, length: 0)
}
/// Initializes a data object filled with a given number of bytes copied from a given buffer.
public init(bytes: UnsafeRawPointer?, length: Int) {
super.init()
_init(bytes: UnsafeMutableRawPointer(mutating: bytes), length: length, copy: true)
}
/// Initializes a data object filled with a given number of bytes of data from a given buffer.
public init(bytesNoCopy bytes: UnsafeMutableRawPointer, length: Int) {
super.init()
_init(bytes: bytes, length: length)
}
/// Initializes a data object filled with a given number of bytes of data from a given buffer.
public init(bytesNoCopy bytes: UnsafeMutableRawPointer, length: Int, freeWhenDone: Bool) {
super.init()
_init(bytes: bytes, length: length, copy: false) { buffer, length in
if freeWhenDone {
free(buffer)
}
}
}
/// Initializes a data object filled with a given number of bytes of data from a given buffer, with a custom deallocator block.
/// NOTE: the deallocator block here is implicitly @escaping by virtue of it being optional
public init(bytesNoCopy bytes: UnsafeMutableRawPointer, length: Int, deallocator: ((UnsafeMutableRawPointer, Int) -> Void)? = nil) {
super.init()
_init(bytes: bytes, length: length, copy: false, deallocator: deallocator)
}
/// Initializes a data object with the contents of the file at a given path.
public init(contentsOfFile path: String, options readOptionsMask: ReadingOptions = []) throws {
super.init()
let readResult = try NSData.readBytesFromFileWithExtendedAttributes(path, options: readOptionsMask)
_init(bytes: readResult.bytes, length: readResult.length, copy: false, deallocator: readResult.deallocator)
}
/// Initializes a data object with the contents of the file at a given path.
public init?(contentsOfFile path: String) {
do {
super.init()
let readResult = try NSData.readBytesFromFileWithExtendedAttributes(path, options: [])
_init(bytes: readResult.bytes, length: readResult.length, copy: false, deallocator: readResult.deallocator)
} catch {
return nil
}
}
/// Initializes a data object with the contents of another data object.
public init(data: Data) {
super.init()
data.withUnsafeBytes {
_init(bytes: UnsafeMutableRawPointer(mutating: $0.baseAddress), length: $0.count, copy: true)
}
}
/// Initializes a data object with the data from the location specified by a given URL.
public init(contentsOf url: URL, options readOptionsMask: ReadingOptions = []) throws {
super.init()
let (data, _) = try NSData.contentsOf(url: url, options: readOptionsMask)
_init(bytes: UnsafeMutableRawPointer(mutating: data.bytes), length: data.length, copy: true)
}
/// Initializes a data object with the data from the location specified by a given URL.
public init?(contentsOf url: URL) {
super.init()
do {
let (data, _) = try NSData.contentsOf(url: url)
_init(bytes: UnsafeMutableRawPointer(mutating: data.bytes), length: data.length, copy: true)
} catch {
return nil
}
}
internal static func contentsOf(url: URL, options readOptionsMask: ReadingOptions = []) throws -> (result: NSData, textEncodingNameIfAvailable: String?) {
if url.isFileURL {
return try url.withUnsafeFileSystemRepresentation { (fsRep) -> (result: NSData, textEncodingNameIfAvailable: String?) in
let data = try NSData.readBytesFromFileWithExtendedAttributes(String(cString: fsRep!), options: readOptionsMask)
return (data.toNSData(), nil)
}
} else {
return try _NSNonfileURLContentLoader.current.contentsOf(url: url)
}
}
/// Initializes a data object with the given Base64 encoded string.
public init?(base64Encoded base64String: String, options: Base64DecodingOptions = []) {
let encodedBytes = Array(base64String.utf8)
guard let decodedBytes = NSData.base64DecodeBytes(encodedBytes, options: options) else {
return nil
}
super.init()
_init(bytes: UnsafeMutableRawPointer(mutating: decodedBytes), length: decodedBytes.count, copy: true)
}
/// Initializes a data object with the given Base64 encoded data.
public init?(base64Encoded base64Data: Data, options: Base64DecodingOptions = []) {
var encodedBytes = [UInt8](repeating: 0, count: base64Data.count)
base64Data._nsObject.getBytes(&encodedBytes, length: encodedBytes.count)
guard let decodedBytes = NSData.base64DecodeBytes(encodedBytes, options: options) else {
return nil
}
super.init()
_init(bytes: UnsafeMutableRawPointer(mutating: decodedBytes), length: decodedBytes.count, copy: true)
}
deinit {
if let allocatedBytes = _bytes {
_deallocHandler?.handler(allocatedBytes, _length)
}
if type(of: self) === NSData.self || type(of: self) === NSMutableData.self {
_CFDeinit(self._cfObject)
}
}
// MARK: - Funnel methods
/// The number of bytes contained by the data object.
open var length: Int {
requireFunnelOverridden()
return CFDataGetLength(_cfObject)
}
/// A pointer to the data object's contents.
open var bytes: UnsafeRawPointer {
requireFunnelOverridden()
guard let bytePtr = CFDataGetBytePtr(_cfObject) else {
//This could occure on empty data being encoded.
//TODO: switch with nil when signature is fixed
return UnsafeRawPointer(bitPattern: 0x7f00dead)! //would not result in 'nil unwrapped optional'
}
return UnsafeRawPointer(bytePtr)
}
// MARK: - NSObject methods
open override var hash: Int {
return Int(bitPattern: _CFNonObjCHash(_cfObject))
}
/// Returns a Boolean value indicating whether this data object is the same as another.
open override func isEqual(_ value: Any?) -> Bool {
if let data = value as? Data {
return isEqual(to: data)
} else if let data = value as? NSData {
return isEqual(to: data._swiftObject)
}
#if DEPLOYMENT_ENABLE_LIBDISPATCH
if let data = value as? DispatchData {
if data.count != length {
return false
}
return data.withUnsafeBytes { (bytes2: UnsafePointer<UInt8>) -> Bool in
let bytes1 = bytes
return memcmp(bytes1, bytes2, length) == 0
}
}
#endif
return false
}
open func isEqual(to other: Data) -> Bool {
if length != other.count {
return false
}
return other.withUnsafeBytes { (bytes2: UnsafePointer<UInt8>) -> Bool in
let bytes1 = bytes
return memcmp(bytes1, bytes2, length) == 0
}
}
open override func copy() -> Any {
return copy(with: nil)
}
open func copy(with zone: NSZone? = nil) -> Any {
return self
}
open override func mutableCopy() -> Any {
return mutableCopy(with: nil)
}
open func mutableCopy(with zone: NSZone? = nil) -> Any {
return NSMutableData(bytes: UnsafeMutableRawPointer(mutating: bytes), length: length, copy: true, deallocator: nil)
}
private func byteDescription(limit: Int? = nil) -> String {
var s = ""
var i = 0
while i < self.length {
if i > 0 && i % 4 == 0 {
// if there's a limit, and we're at the barrier where we'd add the ellipses, don't add a space.
if let limit = limit, self.length > limit && i == self.length - (limit / 2) { /* do nothing */ }
else { s += " " }
}
let byte = bytes.load(fromByteOffset: i, as: UInt8.self)
var byteStr = String(byte, radix: 16, uppercase: false)
if byte <= 0xf { byteStr = "0\(byteStr)" }
s += byteStr
// if we've hit the midpoint of the limit, skip to the last (limit / 2) bytes.
if let limit = limit, self.length > limit && i == (limit / 2) - 1 {
s += " ... "
i = self.length - (limit / 2)
} else {
i += 1
}
}
return s
}
override open var debugDescription: String {
return "<\(byteDescription(limit: 1024))>"
}
/// A string that contains a hexadecimal representation of the data object’s contents in a property list format.
override open var description: String {
return "<\(byteDescription())>"
}
// MARK: - NSCoding methods
open func encode(with aCoder: NSCoder) {
if let aKeyedCoder = aCoder as? NSKeyedArchiver {
aKeyedCoder._encodePropertyList(self, forKey: "NS.data")
} else {
let bytePtr = self.bytes.bindMemory(to: UInt8.self, capacity: self.length)
aCoder.encodeBytes(bytePtr, length: self.length)
}
}
public required init?(coder aDecoder: NSCoder) {
super.init()
guard aDecoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
if type(of: aDecoder) == NSKeyedUnarchiver.self || aDecoder.containsValue(forKey: "NS.data") {
guard let data = aDecoder._decodePropertyListForKey("NS.data") as? NSData else {
return nil
}
_init(bytes: UnsafeMutableRawPointer(mutating: data.bytes), length: data.length, copy: true)
} else {
let result : Data? = aDecoder.withDecodedUnsafeBufferPointer(forKey: "NS.bytes") {
guard let buffer = $0 else { return nil }
return Data(buffer: buffer)
}
guard let r = result else { return nil }
_init(bytes: UnsafeMutableRawPointer(mutating: r._nsObject.bytes), length: r.count, copy: true)
}
}
public static var supportsSecureCoding: Bool {
return true
}
// MARK: - IO
internal struct NSDataReadResult {
var bytes: UnsafeMutableRawPointer?
var length: Int
var deallocator: ((_ buffer: UnsafeMutableRawPointer, _ length: Int) -> Void)!
func toNSData() -> NSData {
if bytes == nil {
return NSData()
}
return NSData(bytesNoCopy: bytes!, length: length, deallocator: deallocator)
}
func toData() -> Data {
guard let bytes = bytes else {
return Data()
}
return Data(bytesNoCopy: bytes, count: length, deallocator: Data.Deallocator.custom(deallocator))
}
}
internal static func readBytesFromFileWithExtendedAttributes(_ path: String, options: ReadingOptions) throws -> NSDataReadResult {
guard let handle = FileHandle(path: path, flags: O_RDONLY, createMode: 0) else {
throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno), userInfo: nil)
}
let result = try handle._readDataOfLength(Int.max, untilEOF: true)
return result
}
/// Writes the data object's bytes to the file specified by a given path.
open func write(toFile path: String, options writeOptionsMask: WritingOptions = []) throws {
func doWrite(_ fh: FileHandle) throws {
try self.enumerateByteRangesUsingBlockRethrows { (buf, range, stop) in
if range.length > 0 {
try fh._writeBytes(buf: buf, length: range.length)
}
}
try fh.synchronize()
}
let fm = FileManager.default
// The destination file path may not exist so provide a default file permissions of RW user only
let permissions = (try? fm._permissionsOfItem(atPath: path)) ?? 0o600
if writeOptionsMask.contains(.atomic) {
let (newFD, auxFilePath) = try _NSCreateTemporaryFile(path)
let fh = FileHandle(fileDescriptor: newFD, closeOnDealloc: true)
do {
try doWrite(fh)
// Moving a file on Windows (via _NSCleanupTemporaryFile)
// requires that there be no open handles to the file
fh.closeFile()
try _NSCleanupTemporaryFile(auxFilePath, path)
try fm.setAttributes([.posixPermissions: NSNumber(value: permissions)], ofItemAtPath: path)
} catch {
let savedErrno = errno
try? fm.removeItem(atPath: auxFilePath)
throw _NSErrorWithErrno(savedErrno, reading: false, path: path)
}
} else {
var flags = O_WRONLY | O_CREAT | O_TRUNC
if writeOptionsMask.contains(.withoutOverwriting) {
flags |= O_EXCL
}
guard let fh = FileHandle(path: path, flags: flags, createMode: permissions) else {
throw _NSErrorWithErrno(errno, reading: false, path: path)
}
try doWrite(fh)
}
}
/// Writes the data object's bytes to the file specified by a given path.
/// NOTE: the 'atomically' flag is ignored if the url is not of a type the supports atomic writes
open func write(toFile path: String, atomically useAuxiliaryFile: Bool) -> Bool {
do {
try write(toFile: path, options: useAuxiliaryFile ? .atomic : [])
} catch {
return false
}
return true
}
/// Writes the data object's bytes to the location specified by a given URL.
/// NOTE: the 'atomically' flag is ignored if the url is not of a type the supports atomic writes
open func write(to url: URL, atomically: Bool) -> Bool {
if url.isFileURL {
return write(toFile: url.path, atomically: atomically)
}
return false
}
/// Writes the data object's bytes to the location specified by a given URL.
///
/// - parameter url: The location to which the data objects's contents will be written.
/// - parameter writeOptionsMask: An option set specifying file writing options.
///
/// - throws: This method returns Void and is marked with the `throws` keyword to indicate that it throws an error in the event of failure.
///
/// This method is invoked in a `try` expression and the caller is responsible for handling any errors in the `catch` clauses of a `do` statement, as described in [Error Handling](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html#//apple_ref/doc/uid/TP40014097-CH42) in [The Swift Programming Language](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/index.html#//apple_ref/doc/uid/TP40014097) and [Error Handling](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/AdoptingCocoaDesignPatterns.html#//apple_ref/doc/uid/TP40014216-CH7-ID10) in [Using Swift with Cocoa and Objective-C](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/index.html#//apple_ref/doc/uid/TP40014216).
open func write(to url: URL, options writeOptionsMask: WritingOptions = []) throws {
guard url.isFileURL else {
let userInfo = [NSLocalizedDescriptionKey : "The folder at “\(url)” does not exist or is not a file URL.", // NSLocalizedString() not yet available
NSURLErrorKey : url.absoluteString] as Dictionary<String, Any>
throw NSError(domain: NSCocoaErrorDomain, code: 4, userInfo: userInfo)
}
try write(toFile: url.path, options: writeOptionsMask)
}
// MARK: - Bytes
/// Copies a number of bytes from the start of the data object into a given buffer.
open func getBytes(_ buffer: UnsafeMutableRawPointer, length: Int) {
if funnelsAreAbstract {
let actualCount = Swift.min(length, self.length)
let sourceBuffer = UnsafeRawBufferPointer(start: bytes, count: actualCount)
let destinationBuffer = UnsafeMutableRawBufferPointer(start: buffer, count: actualCount)
sourceBuffer.copyBytes(to: destinationBuffer)
} else {
let bytePtr = buffer.bindMemory(to: UInt8.self, capacity: length)
CFDataGetBytes(_cfObject, CFRangeMake(0, length), bytePtr)
}
}
/// Copies a range of bytes from the data object into a given buffer.
open func getBytes(_ buffer: UnsafeMutableRawPointer, range: NSRange) {
if funnelsAreAbstract {
precondition(range.location >= 0 && range.length >= 0)
let actualCount = Swift.min(range.length, self.length - range.location)
let sourceBuffer = UnsafeRawBufferPointer(start: bytes.advanced(by: range.location), count: actualCount)
let destinationBuffer = UnsafeMutableRawBufferPointer(start: buffer, count: actualCount)
sourceBuffer.copyBytes(to: destinationBuffer)
} else {
let bytePtr = buffer.bindMemory(to: UInt8.self, capacity: range.length)
CFDataGetBytes(_cfObject, CFRangeMake(range.location, range.length), bytePtr)
}
}
/// Returns a new data object containing the data object's bytes that fall within the limits specified by a given range.
open func subdata(with range: NSRange) -> Data {
if range.length == 0 {
return Data()
}
if range.location == 0 && range.length == self.length {
return Data(referencing: self)
}
let p = self.bytes.advanced(by: range.location).bindMemory(to: UInt8.self, capacity: range.length)
return Data(bytes: p, count: range.length)
}
/// Finds and returns the range of the first occurrence of the given data, within the given range, subject to given options.
open func range(of dataToFind: Data, options mask: SearchOptions = [], in searchRange: NSRange) -> NSRange {
let dataToFind = dataToFind._nsObject
guard dataToFind.length > 0 else {return NSRange(location: NSNotFound, length: 0)}
guard let searchRange = Range(searchRange) else {fatalError("invalid range")}
precondition(searchRange.upperBound <= self.length, "range outside the bounds of data")
let basePtr = self.bytes.bindMemory(to: UInt8.self, capacity: self.length)
let baseData = UnsafeBufferPointer<UInt8>(start: basePtr, count: self.length)[searchRange]
let searchPtr = dataToFind.bytes.bindMemory(to: UInt8.self, capacity: dataToFind.length)
let search = UnsafeBufferPointer<UInt8>(start: searchPtr, count: dataToFind.length)
let location : Int?
let anchored = mask.contains(.anchored)
if mask.contains(.backwards) {
location = NSData.searchSubSequence(search.reversed(), inSequence: baseData.reversed(),anchored : anchored).map {$0.base-search.count}
} else {
location = NSData.searchSubSequence(search, inSequence: baseData,anchored : anchored)
}
return location.map {NSRange(location: $0, length: search.count)} ?? NSRange(location: NSNotFound, length: 0)
}
private static func searchSubSequence<T : Collection, T2 : Sequence>(_ subSequence : T2, inSequence seq: T,anchored : Bool) -> T.Index? where T.Iterator.Element : Equatable, T.Iterator.Element == T2.Iterator.Element {
for index in seq.indices {
if seq.suffix(from: index).starts(with: subSequence) {
return index
}
if anchored {return nil}
}
return nil
}
internal func enumerateByteRangesUsingBlockRethrows(_ block: (UnsafeRawPointer, NSRange, UnsafeMutablePointer<Bool>) throws -> Void) throws {
var err : Swift.Error? = nil
self.enumerateBytes() { (buf, range, stop) -> Void in
do {
try block(buf, range, stop)
} catch {
err = error
}
}
if let err = err {
throw err
}
}
/// Enumerates each range of bytes in the data object using a block.
/// 'block' is called once for each contiguous region of memory in the data object (once total for contiguous NSDatas),
/// until either all bytes have been enumerated, or the 'stop' parameter is set to true.
open func enumerateBytes(_ block: (UnsafeRawPointer, NSRange, UnsafeMutablePointer<Bool>) -> Void) {
var stop = false
withUnsafeMutablePointer(to: &stop) { stopPointer in
if (stopPointer.pointee) {
return
}
block(bytes, NSRange(location: 0, length: length), stopPointer)
}
}
// MARK: - Base64 Methods
/// Creates a Base64 encoded String from the data object using the given options.
open func base64EncodedString(options: Base64EncodingOptions = []) -> String {
var decodedBytes = [UInt8](repeating: 0, count: self.length)
getBytes(&decodedBytes, length: decodedBytes.count)
let encodedBytes = NSData.base64EncodeBytes(decodedBytes, options: options)
let characters = encodedBytes.map { Character(UnicodeScalar($0)) }
return String(characters)
}
/// Creates a Base64, UTF-8 encoded Data from the data object using the given options.
open func base64EncodedData(options: Base64EncodingOptions = []) -> Data {
var decodedBytes = [UInt8](repeating: 0, count: self.length)
getBytes(&decodedBytes, length: decodedBytes.count)
let encodedBytes = NSData.base64EncodeBytes(decodedBytes, options: options)
return Data(bytes: encodedBytes, count: encodedBytes.count)
}
/// The ranges of ASCII characters that are used to encode data in Base64.
private static let base64ByteMappings: [Range<UInt8>] = [
65 ..< 91, // A-Z
97 ..< 123, // a-z
48 ..< 58, // 0-9
43 ..< 44, // +
47 ..< 48, // /
]
/**
Padding character used when the number of bytes to encode is not divisible by 3
*/
private static let base64Padding : UInt8 = 61 // =
/**
This method takes a byte with a character from Base64-encoded string
and gets the binary value that the character corresponds to.
- parameter byte: The byte with the Base64 character.
- returns: Base64DecodedByte value containing the result (Valid , Invalid, Padding)
*/
private enum Base64DecodedByte {
case valid(UInt8)
case invalid
case padding
}
private static func base64DecodeByte(_ byte: UInt8) -> Base64DecodedByte {
guard byte != base64Padding else {return .padding}
var decodedStart: UInt8 = 0
for range in base64ByteMappings {
if range.contains(byte) {
let result = decodedStart + (byte - range.lowerBound)
return .valid(result)
}
decodedStart += range.upperBound - range.lowerBound
}
return .invalid
}
/**
This method takes six bits of binary data and encodes it as a character
in Base64.
The value in the byte must be less than 64, because a Base64 character
can only represent 6 bits.
- parameter byte: The byte to encode
- returns: The ASCII value for the encoded character.
*/
private static func base64EncodeByte(_ byte: UInt8) -> UInt8 {
assert(byte < 64)
var decodedStart: UInt8 = 0
for range in base64ByteMappings {
let decodedRange = decodedStart ..< decodedStart + (range.upperBound - range.lowerBound)
if decodedRange.contains(byte) {
return range.lowerBound + (byte - decodedStart)
}
decodedStart += range.upperBound - range.lowerBound
}
return 0
}
/**
This method decodes Base64-encoded data.
If the input contains any bytes that are not valid Base64 characters,
this will return nil.
- parameter bytes: The Base64 bytes
- parameter options: Options for handling invalid input
- returns: The decoded bytes.
*/
private static func base64DecodeBytes(_ bytes: [UInt8], options: Base64DecodingOptions = []) -> [UInt8]? {
var decodedBytes = [UInt8]()
decodedBytes.reserveCapacity((bytes.count/3)*2)
var currentByte : UInt8 = 0
var validCharacterCount = 0
var paddingCount = 0
var index = 0
for base64Char in bytes {
let value : UInt8
switch base64DecodeByte(base64Char) {
case .valid(let v):
value = v
validCharacterCount += 1
case .invalid:
if options.contains(.ignoreUnknownCharacters) {
continue
} else {
return nil
}
case .padding:
paddingCount += 1
continue
}
//padding found in the middle of the sequence is invalid
if paddingCount > 0 {
return nil
}
switch index%4 {
case 0:
currentByte = (value << 2)
case 1:
currentByte |= (value >> 4)
decodedBytes.append(currentByte)
currentByte = (value << 4)
case 2:
currentByte |= (value >> 2)
decodedBytes.append(currentByte)
currentByte = (value << 6)
case 3:
currentByte |= value
decodedBytes.append(currentByte)
default:
fatalError()
}
index += 1
}
guard (validCharacterCount + paddingCount)%4 == 0 else {
//invalid character count
return nil
}
return decodedBytes
}
/**
This method encodes data in Base64.
- parameter bytes: The bytes you want to encode
- parameter options: Options for formatting the result
- returns: The Base64-encoding for those bytes.
*/
private static func base64EncodeBytes(_ bytes: [UInt8], options: Base64EncodingOptions = []) -> [UInt8] {
var result = [UInt8]()
result.reserveCapacity((bytes.count/3)*4)
let lineOptions : (lineLength : Int, separator : [UInt8])? = {
let lineLength: Int
if options.contains(.lineLength64Characters) { lineLength = 64 }
else if options.contains(.lineLength76Characters) { lineLength = 76 }
else {
return nil
}
var separator = [UInt8]()
if options.contains(.endLineWithCarriageReturn) { separator.append(13) }
if options.contains(.endLineWithLineFeed) { separator.append(10) }
//if the kind of line ending to insert is not specified, the default line ending is Carriage Return + Line Feed.
if separator.isEmpty { separator = [13,10] }
return (lineLength,separator)
}()
var currentLineCount = 0
let appendByteToResult : (UInt8) -> Void = {
result.append($0)
currentLineCount += 1
if let options = lineOptions, currentLineCount == options.lineLength {
result.append(contentsOf: options.separator)
currentLineCount = 0
}
}
var currentByte : UInt8 = 0
for (index,value) in bytes.enumerated() {
switch index%3 {
case 0:
currentByte = (value >> 2)
appendByteToResult(NSData.base64EncodeByte(currentByte))
currentByte = ((value << 6) >> 2)
case 1:
currentByte |= (value >> 4)
appendByteToResult(NSData.base64EncodeByte(currentByte))
currentByte = ((value << 4) >> 2)
case 2:
currentByte |= (value >> 6)
appendByteToResult(NSData.base64EncodeByte(currentByte))
currentByte = ((value << 2) >> 2)
appendByteToResult(NSData.base64EncodeByte(currentByte))
default:
fatalError()
}
}
//add padding
switch bytes.count%3 {
case 0: break //no padding needed
case 1:
appendByteToResult(NSData.base64EncodeByte(currentByte))
appendByteToResult(self.base64Padding)
appendByteToResult(self.base64Padding)
case 2:
appendByteToResult(NSData.base64EncodeByte(currentByte))
appendByteToResult(self.base64Padding)
default:
fatalError()
}
return result
}
}
// MARK: -
extension NSData : _CFBridgeable, _SwiftBridgeable {
typealias SwiftType = Data
internal var _swiftObject: SwiftType { return Data(referencing: self) }
}
extension Data : _NSBridgeable, _CFBridgeable {
typealias CFType = CFData
typealias NSType = NSData
internal var _cfObject: CFType { return _nsObject._cfObject }
internal var _nsObject: NSType { return _bridgeToObjectiveC() }
}
extension CFData : _NSBridgeable, _SwiftBridgeable {
typealias NSType = NSData
typealias SwiftType = Data
internal var _nsObject: NSType { return unsafeBitCast(self, to: NSType.self) }
internal var _swiftObject: SwiftType { return Data(referencing: self._nsObject) }
}
// MARK: -
open class NSMutableData : NSData {
internal var _cfMutableObject: CFMutableData { return unsafeBitCast(self, to: CFMutableData.self) }
public override init() {
super.init(bytes: nil, length: 0)
}
// NOTE: the deallocator block here is implicitly @escaping by virtue of it being optional
fileprivate override init(bytes: UnsafeMutableRawPointer?, length: Int, copy: Bool = false, deallocator: (/*@escaping*/ (UnsafeMutableRawPointer, Int) -> Void)? = nil) {
super.init(bytes: bytes, length: length, copy: copy, deallocator: deallocator)
}
/// Initializes a data object filled with a given number of bytes copied from a given buffer.
public override init(bytes: UnsafeRawPointer?, length: Int) {
super.init(bytes: UnsafeMutableRawPointer(mutating: bytes), length: length, copy: true, deallocator: nil)
}
/// Returns an initialized mutable data object capable of holding the specified number of bytes.
public init?(capacity: Int) {
super.init(bytes: nil, length: 0)
}
/// Initializes and returns a mutable data object containing a given number of zeroed bytes.
public init?(length: Int) {
super.init(bytes: nil, length: 0)
self.length = length
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public override init(bytesNoCopy bytes: UnsafeMutableRawPointer, length: Int) {
super.init(bytesNoCopy: bytes, length: length)
}
public override init(bytesNoCopy bytes: UnsafeMutableRawPointer, length: Int, deallocator: ((UnsafeMutableRawPointer, Int) -> Void)? = nil) {
super.init(bytesNoCopy: bytes, length: length, deallocator: deallocator)
}
public override init(bytesNoCopy bytes: UnsafeMutableRawPointer, length: Int, freeWhenDone: Bool) {
super.init(bytesNoCopy: bytes, length: length, freeWhenDone: freeWhenDone)
}
public override init(data: Data) {
super.init(data: data)
}
public override init?(contentsOfFile path: String) {
super.init(contentsOfFile: path)
}
public override init(contentsOfFile path: String, options: NSData.ReadingOptions = []) throws {
try super.init(contentsOfFile: path, options: options)
}
public override init?(contentsOf url: URL) {
super.init(contentsOf: url)
}
public override init(contentsOf url: URL, options: NSData.ReadingOptions = []) throws {
try super.init(contentsOf: url, options: options)
}
public override init?(base64Encoded base64Data: Data, options: NSData.Base64DecodingOptions = []) {
super.init(base64Encoded: base64Data, options: options)
}
public override init?(base64Encoded base64Data: String, options: NSData.Base64DecodingOptions = []) {
super.init(base64Encoded: base64Data, options: options)
}
// MARK: - Funnel Methods
/// A pointer to the data contained by the mutable data object.
open var mutableBytes: UnsafeMutableRawPointer {
requireFunnelOverridden()
return UnsafeMutableRawPointer(CFDataGetMutableBytePtr(_cfMutableObject))
}
/// The number of bytes contained in the mutable data object.
open override var length: Int {
get {
requireFunnelOverridden()
return CFDataGetLength(_cfObject)
}
set {
requireFunnelOverridden()
CFDataSetLength(_cfMutableObject, newValue)
}
}
// MARK: - NSObject
open override func copy(with zone: NSZone? = nil) -> Any {
return NSData(bytes: bytes, length: length)
}
// MARK: - Mutability
/// Appends to the data object a given number of bytes from a given buffer.
open func append(_ bytes: UnsafeRawPointer, length: Int) {
guard length > 0 else { return }
if funnelsAreAbstract {
self.length += length
UnsafeRawBufferPointer(start: bytes, count: length).copyBytes(to: UnsafeMutableRawBufferPointer(start: mutableBytes, count: length))
} else {
let bytePtr = bytes.bindMemory(to: UInt8.self, capacity: length)
CFDataAppendBytes(_cfMutableObject, bytePtr, length)
}
}
/// Appends the content of another data object to the data object.
open func append(_ other: Data) {
let otherLength = other.count
other.withUnsafeBytes {
append($0, length: otherLength)
}
}
/// Increases the length of the data object by a given number of bytes.
open func increaseLength(by extraLength: Int) {
if funnelsAreAbstract {
self.length += extraLength
} else {
CFDataSetLength(_cfMutableObject, CFDataGetLength(_cfObject) + extraLength)
}
}
/// Replaces with a given set of bytes a given range within the contents of the data object.
open func replaceBytes(in range: NSRange, withBytes bytes: UnsafeRawPointer) {
if funnelsAreAbstract {
replaceBytes(in: range, withBytes: bytes, length: range.length)
} else {
let bytePtr = bytes.bindMemory(to: UInt8.self, capacity: length)
CFDataReplaceBytes(_cfMutableObject, CFRangeMake(range.location, range.length), bytePtr, length)
}
}
/// Replaces with zeroes the contents of the data object in a given range.
open func resetBytes(in range: NSRange) {
memset(mutableBytes.advanced(by: range.location), 0, range.length)
}
/// Replaces the entire contents of the data object with the contents of another data object.
open func setData(_ data: Data) {
length = data.count
data.withUnsafeBytes {
replaceBytes(in: NSRange(location: 0, length: length), withBytes: $0)
}
}
/// Replaces with a given set of bytes a given range within the contents of the data object.
open func replaceBytes(in range: NSRange, withBytes replacementBytes: UnsafeRawPointer?, length replacementLength: Int) {
precondition(range.location + range.length <= self.length)
if funnelsAreAbstract {
let delta = replacementLength - range.length
if delta != 0 {
let originalLength = self.length
self.length += delta
if delta > 0 {
UnsafeRawBufferPointer(start: mutableBytes.advanced(by: range.location), count: originalLength).copyBytes(to: UnsafeMutableRawBufferPointer(start: mutableBytes.advanced(by: range.location + range.length), count: originalLength))
}
}
UnsafeRawBufferPointer(start: replacementBytes, count: replacementLength).copyBytes(to: UnsafeMutableRawBufferPointer(start: mutableBytes.advanced(by: range.location), count: replacementLength))
} else {
let bytePtr = replacementBytes?.bindMemory(to: UInt8.self, capacity: replacementLength)
CFDataReplaceBytes(_cfMutableObject, CFRangeMake(range.location, range.length), bytePtr, replacementLength)
}
}
}
extension NSData {
internal func _isCompact() -> Bool {
var regions = 0
enumerateBytes { (_, _, stop) in
regions += 1
if regions > 1 {
stop.pointee = true
}
}
return regions <= 1
}
}
extension NSData : _StructTypeBridgeable {
public typealias _StructType = Data
public func _bridgeToSwift() -> Data {
return Data._unconditionallyBridgeFromObjectiveC(self)
}
}
internal func _CFSwiftDataCreateCopy(_ data: CFTypeRef) -> Unmanaged<AnyObject> {
return Unmanaged<AnyObject>.passRetained((data as! NSData).copy() as! NSObject)
}
internal func _CFSwiftDataGetLength(_ data: CFTypeRef) -> CFIndex {
return (data as! NSData).length
}
internal func _CFSwiftDataGetBytesPtr(_ data: CFTypeRef) -> UnsafeRawPointer? {
return (data as! NSData).bytes
}
internal func _CFSwiftDataGetMutableBytesPtr(_ data: CFTypeRef) -> UnsafeMutableRawPointer? {
return (data as! NSMutableData).mutableBytes
}
internal func _CFSwiftDataGetBytes(_ data: CFTypeRef, _ range: CFRange, _ buffer: UnsafeMutableRawPointer) -> Void {
(data as! NSData).getBytes(buffer, range: NSMakeRange(range.location, range.length))
}
internal func _CFSwiftDataSetLength(_ data: CFTypeRef, _ newLength: CFIndex) {
(data as! NSMutableData).length = newLength
}
internal func _CFSwiftDataIncreaseLength(_ data: CFTypeRef, _ extraLength: CFIndex) {
(data as! NSMutableData).increaseLength(by: extraLength)
}
internal func _CFSwiftDataAppendBytes(_ data: CFTypeRef, _ buffer: UnsafeRawPointer, length: CFIndex) {
(data as! NSMutableData).append(buffer, length: length)
}
internal func _CFSwiftDataReplaceBytes(_ data: CFTypeRef, _ range: CFRange, _ buffer: UnsafeRawPointer?, _ count: CFIndex) {
(data as! NSMutableData).replaceBytes(in: NSMakeRange(range.location, range.length), withBytes: buffer, length: count)
}
extension NSData {
var funnelsAreAbstract: Bool {
return type(of: self) != NSData.self && type(of: self) != NSMutableData.self
}
func requireFunnelOverridden() {
if funnelsAreAbstract {
NSRequiresConcreteImplementation()
}
}
}
| apache-2.0 | cc96db16d81b41f0b715829c2494a4ca | 40.341959 | 924 | 0.626375 | 4.756194 | false | false | false | false |
BGDigital/mcwa | mcwa/mcwa/Tools/Player.swift | 1 | 1779 | import UIKit
import AVFoundation
import MediaPlayer
protocol PlayerDelegate : class {
func soundFinished(sender : AnyObject)
}
class Player : NSObject, AVAudioPlayerDelegate {
var player : AVAudioPlayer!
var forever = false
weak var delegate : PlayerDelegate?
func playFileAtPath(path:String) {
self.player?.delegate = nil
self.player?.stop()
let fileURL = NSURL(fileURLWithPath: path)
guard let p = try? AVAudioPlayer(contentsOfURL: fileURL) else {return} // nicer
self.player = p
// error-checking omitted
self.player.prepareToPlay()
self.player.delegate = self
if self.forever {
self.player.numberOfLoops = -1
}
// player.enableRate = true
// player.rate = 1.2 // cool feature
self.player.play()
// cute little demo
let mpic = MPNowPlayingInfoCenter.defaultCenter()
mpic.nowPlayingInfo = [
MPMediaItemPropertyTitle:"This Is a Test",
MPMediaItemPropertyArtist:"Matt Neuburg"
]
}
// delegate method
func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool) { // *
self.delegate?.soundFinished(self)
}
/*
NB! delegate interruption methods deprecated in iOS 8
func audioPlayerBeginInterruption(player: AVAudioPlayer!) {
print("audio player interrupted")
}
func audioPlayerEndInterruption(player: AVAudioPlayer!, withOptions flags: Int) {
print("audio player ended interruption, options \(flags)")
}
*/
func stop () {
self.player?.pause()
}
deinit {
self.player?.delegate = nil
}
} | mit | 8a80156dcd122f4c9a46b65f5eb84b66 | 25.567164 | 91 | 0.608207 | 5.082857 | false | false | false | false |
mlilback/rc2SwiftClient | Networking/Rc2RestClient.swift | 1 | 10619 | //
// Rc2RestClient.swift
//
// Copyright ©2016 Mark Lilback. This file is licensed under the ISC license.
//
import Rc2Common
import Foundation
import MJLLogger
import ReactiveSwift
import ZIPFoundation
import Model
private let wspaceDirName = "defaultWorkspaceFiles"
public final class Rc2RestClient {
let conInfo: ConnectionInfo
let sessionConfig: URLSessionConfiguration
fileprivate var urlSession: URLSession?
let fileManager: Rc2FileManager
private let infoLock = DispatchSemaphore(value: 1)
public init(_ conInfo: ConnectionInfo, fileManager: Rc2FileManager = Rc2DefaultFileManager())
{
self.conInfo = conInfo
self.fileManager = fileManager
self.sessionConfig = conInfo.urlSessionConfig
if nil == sessionConfig.httpAdditionalHeaders {
sessionConfig.httpAdditionalHeaders = [:]
}
self.sessionConfig.httpAdditionalHeaders!["Accept"] = "application/json"
urlSession = URLSession(configuration: sessionConfig, delegate: nil, delegateQueue: OperationQueue.main)
}
fileprivate func request(_ path: String, method: String) -> URLRequest
{
let url = conInfo.host.url!.appendingPathComponent(conInfo.host.urlPrefix + "/" + path)
var request = URLRequest(url: url)
request.httpMethod = method
return request
}
public func updateConnectInfo() {
infoLock.wait()
var request = URLRequest(url: URL(string: conInfo.host.urlPrefix + "/info", relativeTo: conInfo.host.url!)!)
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("Bearer \(conInfo.authToken)", forHTTPHeaderField: "Authorization")
let handler = { (data: Data?, response: URLResponse?, error: Error?) in
defer { self.infoLock.signal() }
guard let httpResponse = response as? HTTPURLResponse,
let infoData = data,
httpResponse.statusCode == 200,
let bulkInfo: BulkUserInfo = try? self.conInfo.decode(data: infoData)
else {
Log.warn("failed to reload /info: \(error?.localizedDescription ?? "-")", .network)
return
}
self.conInfo.update(bulkInfo: bulkInfo)
}
self.urlSession!.dataTask(with: request, completionHandler: handler).resume()
}
/// creates a workspace on the server
///
/// - Parameters:
/// - workspace: name of the workspace to create
/// - project: project to create the workspace in
/// - Returns: SignalProducer that returns the new workspace or an error
public func create(workspace: String, project: AppProject) -> SignalProducer<AppWorkspace, Rc2Error>
{
return SignalProducer<AppWorkspace, Rc2Error> { observer, _ in
var req = self.request("proj/\(project.projectId)/wspace", method: "POST")
let zippedUrl = self.defaultWorkspaceFiles()
if zippedUrl != nil, let zippedData = try? Data(contentsOf: zippedUrl!) {
req.addValue("application/octet-stream", forHTTPHeaderField: "Content-Type")
req.addValue(workspace, forHTTPHeaderField: "Rc2-WorkspaceName")
req.httpBody = zippedData
} else {
req.addValue("application/json", forHTTPHeaderField: "Content-Type")
}
req.addValue("application/json", forHTTPHeaderField: "Accept")
let handler = { (data: Data?, response: URLResponse?, error: Error?) in
do {
let results: CreateWorkspaceResult = try self.handleResponse(data: data, response: response, error: error)
self.conInfo.update(bulkInfo: results.bulkInfo)
let wspace = try self.conInfo.workspace(withId: results.wspaceId, in: project)
observer.send(value: wspace)
observer.sendCompleted()
} catch let nferror as ConnectionInfo.Errors {
Log.warn("created workspace not found", .network)
observer.send(error: Rc2Error(type: .network, nested: nferror, explanation: "created workspace not found"))
} catch let rc2error as Rc2Error {
observer.send(error: rc2error)
} catch {
Log.warn("error parsing create workspace response \(error)", .network)
observer.send(error: Rc2Error(type: .cocoa, nested: error, explanation: "unknown error parsing create workspace response"))
}
}
self.urlSession!.dataTask(with: req, completionHandler: handler).resume()
}
}
/// remove a workspace from the server
///
/// - Parameter workspace: the workspace to remove
/// - Returns: SignalProducer for the updated bulk info, or an error
public func remove(workspace: AppWorkspace) -> SignalProducer<(), Rc2Error>
{
var request = self.request("/proj/\(workspace.projectId)/wspace/\(workspace.wspaceId)", method: "DELETE")
request.addValue("application/json", forHTTPHeaderField: "Accept")
return SignalProducer<(), Rc2Error> { observer, _ in
let handler = { (data: Data?, response: URLResponse?, error: Error?) in
do {
let bulkInfo: BulkUserInfo = try self.handleResponse(data: data, response: response, error: error)
self.conInfo.update(bulkInfo: bulkInfo)
observer.send(value: ())
observer.sendCompleted()
} catch let rc2error as Rc2Error {
observer.send(error: rc2error)
} catch {
Log.info("error removing workspace: \(error)", .network)
observer.send(error: Rc2Error(type: .cocoa, nested: error, explanation: "unknown error removing workspace"))
}
}
self.urlSession!.dataTask(with: request, completionHandler: handler).resume()
}
}
/// creates a file on the server
///
/// - Parameters:
/// - fileName: name of the file with extension
/// - workspace: workspace to contain the file
/// - contentUrl: optional URL to use as a template for the file
/// - Returns: SignalProducer for the file to add to the workspace, or an error
public func create(fileName: String, workspace: AppWorkspace, contentUrl: URL?) -> SignalProducer<File, Rc2Error>
{
return SignalProducer<File, Rc2Error> { observer, _ in
var req = self.request("file/\(workspace.wspaceId)", method: "POST")
req.addValue("0", forHTTPHeaderField: "Content-Length")
req.addValue("application/octet-string", forHTTPHeaderField: "Content-Encoding")
req.addValue(fileName, forHTTPHeaderField: "Rc2-Filename")
req.addValue(self.conInfo.authToken, forHTTPHeaderField: "Rc2-Auth")
let handler = { (data: Data?, response: URLResponse?, error: Error?) in
do {
let file: File = try self.handleResponse(data: data, response: response, error: error)
observer.send(value: file)
observer.sendCompleted()
} catch let err as Rc2Error {
observer.send(error: err)
} catch {
Log.warn("error parsing create workspace response \(error)", .network)
observer.send(error: Rc2Error(type: .cocoa, nested: error, explanation: "unknown error parsing create workspace response"))
}
}
if let contentUrl = contentUrl {
self.urlSession!.uploadTask(with: req, fromFile: contentUrl, completionHandler: handler).resume()
} else {
self.urlSession!.dataTask(with: req, completionHandler: handler).resume()
}
}
}
/// Downloads a SessionImage based on its id, saving to disk in the specified destination
///
/// - Parameters:
/// - imageId: the id of the image to download
/// - wspace: the workspace the image belongs to
/// - destination: a folder to save the image in, where its name will be imageId.png
/// - Returns: a signal producer that will return the file system URL containing the downloaded image
public func downloadImage(imageId: Int, from wspace: AppWorkspace, destination: URL) -> SignalProducer<URL, Rc2Error>
{
return SignalProducer<URL, Rc2Error> { observer, _ in
var req = self.request("workspaces/\(wspace.wspaceId)/images/\(imageId)", method: "GET")
req.addValue("image/png", forHTTPHeaderField: "Accept")
let task = self.urlSession!.downloadTask(with: req) { (dloadUrl, response, error) -> Void in
let hresponse = response as? HTTPURLResponse
guard error == nil && hresponse?.statusCode == 200 else {
let err = Rc2Error(type: .file, nested: FileError.failedToSave)
observer.send(error: err)
return
}
let fileUrl = URL(fileURLWithPath: "\(imageId).png", isDirectory: false, relativeTo: destination)
do {
try self.fileManager.move(tempFile: dloadUrl!, to: fileUrl, file: nil)
} catch {
observer.send(error: Rc2Error(type: .file, nested: FileError.failedToDownload, severity: .warning, explanation: "image \(imageId)"))
}
}
task.resume()
}
}
/// returns array of default files to add to any new workspace
/// -Rreturns: URL to a zip file with the default files to add
private func defaultWorkspaceFiles() -> URL? {
let fm = FileManager()
do {
let defaultDirectoryUrl = try AppInfo.subdirectory(type: .applicationSupportDirectory, named: wspaceDirName)
if try fm.contentsOfDirectory(atPath: defaultDirectoryUrl.path).isEmpty,
let templateDir = (Bundle(for: type(of: self)).resourceURL?.appendingPathComponent(wspaceDirName, isDirectory: true))
{
// copy all template files to user-editable directory
for aUrl in try fm.contentsOfDirectory(at: templateDir, includingPropertiesForKeys: nil, options: .skipsHiddenFiles)
{
try fm.copyItem(at: aUrl, to: defaultDirectoryUrl.appendingPathComponent(aUrl.lastPathComponent))
}
}
let destUrl = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("\(UUID().uuidString).zip")
do {
try fm.zipItem(at: defaultDirectoryUrl, to: destUrl, shouldKeepParent: false)
return destUrl
} catch {
Log.warn("failed to create zip file to upload: \(error)", .network)
}
} catch {
Log.warn("error loading default workspace files: \(error)", .network)
}
return nil
}
/// parses the response from a URLSessionTask callback
///
/// - Parameters:
/// - data: data parameter from callback
/// - response: response parameter from callback
/// - error: error parameter from callback
/// - Returns: decoded object from data
/// - Throws: server error wrapped as Rc2Error
private func handleResponse<T: Decodable>(data: Data?, response: URLResponse?, error: Error?) throws -> T
{
guard nil == error else { throw Rc2Error(type: .cocoa, nested: error) }
switch response?.httpResponse?.statusCode ?? 500 {
case 200, 201:
do {
let object: T = try conInfo.decode(data: data!)
return object
} catch {
throw Rc2Error(type: .invalidJson, explanation: "error parsing create REST response")
}
case 422:
throw Rc2Error(type: .invalidArgument, nested: NetworkingError.errorFor(response: response!.httpResponse!, data: data!), explanation: "Workspace already exists with that name")
default:
// swiftlint:disable:next force_cast
throw Rc2Error(type: .network, nested: NetworkingError.invalidHttpStatusCode(response as! HTTPURLResponse))
}
}
}
| isc | 76f5cdb80191934e84b290d9edfaa6cc | 41.64257 | 179 | 0.714918 | 3.824928 | false | false | false | false |
manuelescrig/SuggestionsBox | Example/SuggestionsBox/AppDelegate.swift | 1 | 2664 | //
// AppDelegate.swift
// Example
//
// Created by Manuel Escrig Ventura on 12/05/16.
// Copyright © 2016 Manuel Escrig Ventura. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
UIApplication.shared.statusBarStyle = .lightContent
UINavigationBar.appearance().shadowImage = UIImage()
UINavigationBar.appearance().barTintColor = UIColor(red:19/255.0, green:100/255.0, blue:155/255.0, alpha: 1.0)
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName : UIColor.white,
NSFontAttributeName: UIFont(name: "HelveticaNeue-Medium", size: 19)!]
UINavigationBar.appearance().tintColor = UIColor.white
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit | 9317d49dc9ff43c62787d062748ceebc | 50.211538 | 285 | 0.733383 | 5.513458 | false | false | false | false |
richardpiazza/CodeQuickKit | Sources/CodeQuickKit/Swift/Sequence+SplitBefore.swift | 1 | 932 | public extension Sequence {
/// Splits a sequence at each instance of the supplied separator.
/// [Stack Overflow](https://stackoverflow.com/questions/39592563/split-string-in-swift-by-their-capital-letters)
func splitBefore(separator isSeparator: (Iterator.Element) throws -> Bool) rethrows -> [AnySequence<Iterator.Element>] {
var result: [AnySequence<Iterator.Element>] = []
var subSequence: [Iterator.Element] = []
var iterator = self.makeIterator()
while let element = iterator.next() {
if try isSeparator(element) {
if !subSequence.isEmpty {
result.append(AnySequence(subSequence))
}
subSequence = [element]
} else {
subSequence.append(element)
}
}
result.append(AnySequence(subSequence))
return result
}
}
| mit | a1ae8e150e64d17aa915bfe0388f2299 | 37.833333 | 124 | 0.584764 | 5.037838 | false | false | false | false |
nineteen-apps/swift | lessons-02/lesson4/Sources/cpf.swift | 1 | 2867 | // -*-swift-*-
// The MIT License (MIT)
//
// Copyright (c) 2017 - Nineteen
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// Created: 2017-06-20 by Ronaldo Faria Lima
//
// This file purpose: Classe que realiza o cálculo do dígito verificador do CPF
// para verificação de sua validade.
import Foundation
struct CPF: Checksum {
let cpf: String
fileprivate var checkDigits: Int? {
return Int(cpf.substring(from: cpf.index(cpf.endIndex, offsetBy: -2)))
}
init (cpf: String) {
self.cpf = cpf
}
func isValid() -> Bool {
return checkDigits == calculateCheckDigits()
}
fileprivate func calculateCheckDigits() -> Int? {
if let firstDigit = calculateCheckDigit(for: 10), let secondDigit = calculateCheckDigit(for: 11) {
return firstDigit * 10 + secondDigit
}
return nil
}
private func calculateCheckDigit(for weight: Int) -> Int? {
var ckDigit = 0
var currWeight = weight
for i in cpf.characters.indices {
if currWeight < 1 {
break
}
if let digit = Int(String(cpf[i])) {
ckDigit += digit * currWeight
} else {
return nil
}
currWeight -= 1
}
let remainder = ckDigit % 11
ckDigit = remainder < 2 ? 0 : 11 - remainder
return ckDigit
}
func validate() throws {
if cpf.characters.count != 11 {
throw ValidationError.wrongNumberOfDigits
}
if let _ = cpf.rangeOfCharacter(from: CharacterSet.letters) {
throw ValidationError.foundLetters
}
if let _ = cpf.rangeOfCharacter(from: CharacterSet.punctuationCharacters) {
throw ValidationError.foundPunctuation
}
}
}
| mit | f1d5839fa5db723d79b7306bb43b8d12 | 33.493976 | 106 | 0.647223 | 4.501572 | false | false | false | false |
jose-camallonga/sample-base | SampleApp/Networking Layer/Models/ListItem.swift | 1 | 2897 | //
// Item.swift
// SampleApp
//
// Created by Jose Camallonga on 26/09/2017.
// Copyright © 2017 Jose Camallonga. All rights reserved.
//
import Foundation
struct ListItemData: Codable {
var data: [ListItem]
}
struct ListItem: Codable {
var id: String
var names: Name
var abbreviation: String
var weblink: String
var released: Int
var releaseDate: String
var ruleset: Ruleset
var romhack: Bool
var gametypes: [String]
var platforms: [String]
var regions: [String]
var genres: [String]
var engines: [String]
var developers: [String]
var publishers: [String]
var moderators: [String : String]
var created: String
var assets: Assets
var links: [Link]
enum CodingKeys: String, CodingKey {
case id
case names
case abbreviation
case weblink
case released
case releaseDate = "release-date"
case ruleset
case romhack
case gametypes
case platforms
case regions
case genres
case engines
case developers
case publishers
case moderators
case created
case assets
case links
}
}
struct Name: Codable {
var international: String
var japanese: String?
var twitch: String
}
struct Ruleset: Codable {
var showMilliseconds: Bool
var requireVerification: Bool
var requireVideo: Bool
var runTimes: [String]
var defaultTime: String
var emulatorsAllowed: Bool
enum CodingKeys: String, CodingKey {
case showMilliseconds = "show-milliseconds"
case requireVerification = "require-verification"
case requireVideo = "require-video"
case runTimes = "run-times"
case defaultTime = "default-time"
case emulatorsAllowed = "emulators-allowed"
}
}
struct Assets: Codable {
var logo: AssetInfo
var coverTiny: AssetInfo
var coverSmall: AssetInfo?
var coverMedium: AssetInfo?
var coverLarge: AssetInfo?
var icon: AssetInfo?
var trophyFirst: AssetInfo?
var trophySecond: AssetInfo?
var trophyThird: AssetInfo?
var trophyFourth: AssetInfo?
var background: AssetInfo?
var foreground: AssetInfo?
enum CodingKeys: String, CodingKey {
case logo
case coverTiny = "cover-tiny"
case coverSmall = "cover-small"
case coverMedium = "cover-medium"
case coverLarge = "cover-large"
case icon
case trophyFirst = "trophy-1st"
case trophySecond = "trophy-2nd"
case trophyThird = "trophy-3rd"
case trophyFourth = "trophy-4th"
case background
case foreground
}
}
struct AssetInfo: Codable {
var uri: String
var width: Int
var height: Int
}
struct Link: Codable {
var rel: String
var id: String?
var uri: String
}
| mit | 436dc9954a4801c5f3cb74bb0c63cb1e | 22.544715 | 58 | 0.633978 | 4.209302 | false | false | false | false |
stilsons/cs212 | ClickCounter/FirstApp/ViewController.swift | 1 | 1485 | //
// ViewController.swift
// FirstApp
//
// Created by Jason Schatz on 9/3/15.
// Copyright (c) 2015 Jason Schatz. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var count: Int = 0
var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Set the view's background color
view.backgroundColor = UIColor.orangeColor()
// Create a label object, add as subview of view
let labelFrame = CGRect(x: 160, y: 150, width: 200, height: 100)
label = UILabel(frame: labelFrame)
label.font = UIFont.systemFontOfSize(120)
label.text = "0"
view.addSubview(label)
// Create a button, add it as a subview
let buttonFrame = CGRect(x: 100, y: 250, width: 200, height: 100)
let button = UIButton(type: UIButtonType.System)
button.frame = buttonFrame
button.setTitle("Click", forState: UIControlState.Normal)
view.addSubview(button)
// Add a target/action to the button
button.addTarget(self, action: Selector("bumpUpTheCount"), forControlEvents: UIControlEvents.TouchDown)
button.addTarget(self, action: Selector("printClick"), forControlEvents: UIControlEvents.TouchDown)
}
func bumpUpTheCount() {
count++
label.text = "\(count)"
}
func printClick() {
print("clicked.", terminator: "")
}
}
| mit | 37b77d238d39f06e19430623c6567b5d | 26 | 111 | 0.613468 | 4.419643 | false | false | false | false |
wesj/firefox-ios-1 | Client/Frontend/Widgets/TwoLineCell.swift | 1 | 5767 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
private let ImageSize: CGFloat = 24
private let ImageMargin: CGFloat = 20
private let TextColor = UIAccessibilityDarkerSystemColorsEnabled() ? UIColor.blackColor() : UIColor(rgb: 0x333333)
private let DetailTextColor = UIAccessibilityDarkerSystemColorsEnabled() ? UIColor.darkGrayColor() : UIColor.grayColor()
class TwoLineTableViewCell: UITableViewCell {
private let twoLineHelper: TwoLineCellHelper!
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: UITableViewCellStyle.Subtitle, reuseIdentifier: reuseIdentifier)
twoLineHelper = TwoLineCellHelper(container: self, textLabel: textLabel!, detailTextLabel: detailTextLabel!, imageView: imageView!)
indentationWidth = 0
layoutMargins = UIEdgeInsetsZero
separatorInset = UIEdgeInsetsMake(0, ImageSize + 2 * ImageMargin, 0, 0)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
twoLineHelper.layoutSubviews()
}
func setLines(text: String?, detailText: String?) {
twoLineHelper.setLines(text, detailText: detailText)
}
}
class TwoLineCollectionViewCell: UICollectionViewCell {
private let twoLineHelper: TwoLineCellHelper!
let textLabel = UILabel()
let detailTextLabel = UILabel()
let imageView = UIImageView()
override init() {
super.init()
}
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(textLabel)
contentView.addSubview(detailTextLabel)
contentView.addSubview(imageView)
twoLineHelper = TwoLineCellHelper(container: self, textLabel: textLabel, detailTextLabel: detailTextLabel, imageView: imageView)
layoutMargins = UIEdgeInsetsZero
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
twoLineHelper.layoutSubviews()
}
func setLines(text: String?, detailText: String?) {
twoLineHelper.setLines(text, detailText: detailText)
}
}
class TwoLineHeaderFooterView: UITableViewHeaderFooterView {
private let twoLineHelper: TwoLineCellHelper!
// UITableViewHeaderFooterView includes textLabel and detailTextLabel, so we can't override
// them. Unfortunately, they're also used in ways that interfere with us just using them: I get
// hard crashes in layout if I just use them; it seems there's a battle over adding to the
// contentView. So we add our own members, and cover up the other ones.
let _textLabel = UILabel()
let _detailTextLabel = UILabel()
let imageView = UIImageView()
// Yes, this is strange.
override var textLabel: UILabel {
return _textLabel
}
// Yes, this is strange.
override var detailTextLabel: UILabel {
return _detailTextLabel
}
override init() {
super.init()
}
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
}
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(_textLabel)
contentView.addSubview(_detailTextLabel)
contentView.addSubview(imageView)
twoLineHelper = TwoLineCellHelper(container: self, textLabel: _textLabel, detailTextLabel: _detailTextLabel, imageView: imageView)
layoutMargins = UIEdgeInsetsZero
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
twoLineHelper.layoutSubviews()
}
}
private class TwoLineCellHelper {
private let container: UIView
let textLabel: UILabel
let detailTextLabel: UILabel
let imageView: UIImageView
init(container: UIView, textLabel: UILabel, detailTextLabel: UILabel, imageView: UIImageView) {
self.container = container
self.textLabel = textLabel
self.detailTextLabel = detailTextLabel
self.imageView = imageView
textLabel.font = UIFont(name: "HelveticaNeue", size: 14)
textLabel.textColor = TextColor
detailTextLabel.font = UIFont(name: "HelveticaNeue", size: 10)
detailTextLabel.textColor = DetailTextColor
imageView.contentMode = .ScaleAspectFill
}
func layoutSubviews() {
let height = container.frame.height
let textLeft = ImageSize + 2 * ImageMargin
let textLabelHeight = textLabel.intrinsicContentSize().height
let detailTextLabelHeight = detailTextLabel.intrinsicContentSize().height
let contentHeight = textLabelHeight + detailTextLabelHeight + 1
imageView.frame = CGRectMake(ImageMargin, (height - ImageSize) / 2, ImageSize, ImageSize)
textLabel.frame = CGRectMake(textLeft, (height - contentHeight) / 2,
container.frame.width - textLeft - ImageMargin, textLabelHeight)
detailTextLabel.frame = CGRectMake(textLeft, textLabel.frame.maxY + 5,
container.frame.width - textLeft - ImageMargin, detailTextLabelHeight)
}
func setLines(text: String?, detailText: String?) {
if text?.isEmpty ?? true {
textLabel.text = detailText
detailTextLabel.text = nil
} else {
textLabel.text = text
detailTextLabel.text = detailText
}
}
}
| mpl-2.0 | 52c2ba13d68917908b77d770821fe70f | 32.923529 | 139 | 0.691868 | 5.237965 | false | false | false | false |
googlecast/CastVideos-ios | CastVideos-swift/Classes/Toast.swift | 1 | 3350 | // Copyright 2022 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
// Coordinate to ensure two toasts are never active at once.
var isToastActive: Bool = false
var activeToast: Toast?
class Toast: UIView {
var messageLabel: UILabel!
class func displayMessage(_ message: String, for timeInterval: TimeInterval, in view: UIView?) {
guard let view = view else { return }
if !isToastActive {
isToastActive = true
// Compute toast frame dimensions.
let hostHeight: CGFloat = view.frame.size.height
let hostWidth: CGFloat = view.frame.size.width
let horizontalOffset: CGFloat = 0
let toastHeight: CGFloat = 48
let toastWidth: CGFloat = hostWidth
let verticalOffset: CGFloat = hostHeight - toastHeight
let toastRect = CGRect(x: horizontalOffset, y: verticalOffset, width: toastWidth, height: toastHeight)
// Init and stylize the toast and message.
let toast = Toast(frame: toastRect)
toast.backgroundColor = UIColor(red: CGFloat((50 / 255.0)), green: CGFloat((50 / 255.0)),
blue: CGFloat((50 / 255.0)), alpha: CGFloat(1))
toast.messageLabel = UILabel(frame: CGRect(x: CGFloat(0), y: CGFloat(0), width: toastWidth, height: toastHeight))
toast.messageLabel.text = message
toast.messageLabel.textColor = UIColor.white
toast.messageLabel.textAlignment = .center
toast.messageLabel.font = UIFont.systemFont(ofSize: CGFloat(18))
toast.messageLabel.adjustsFontSizeToFitWidth = true
// Put the toast on top of the host view.
toast.addSubview(toast.messageLabel)
view.insertSubview(toast, aboveSubview: view.subviews.last!)
activeToast = toast
UIDevice.current.beginGeneratingDeviceOrientationNotifications()
NotificationCenter.default.addObserver(self, selector: #selector(orientationChanged),
name: UIDevice.orientationDidChangeNotification, object: nil)
// Set the toast's timeout
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() +
Double(Int64(timeInterval * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: { () -> Void in
toast.removeFromSuperview()
NotificationCenter.default.removeObserver(self)
isToastActive = false
activeToast = nil
})
}
}
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func touchesEnded(_: Set<UITouch>, with _: UIEvent?) {
removeFromSuperview()
isToastActive = false
}
@objc class func orientationChanged(_: Notification) {
if isToastActive {
activeToast?.removeFromSuperview()
isToastActive = false
}
}
}
| apache-2.0 | 5250e635ceacc7aaa0f90fdd390828c6 | 39.853659 | 119 | 0.688358 | 4.539295 | false | false | false | false |
khizkhiz/swift | benchmark/single-source/CaptureProp.swift | 2 | 952 | //===--- CaptureProp.swift ------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
func sum(x:Int, y:Int) -> Int {
return x + y
}
@inline(never)
func benchCaptureProp<S : Sequence
>(
s:S, _ f:(S.Iterator.Element, S.Iterator.Element)->S.Iterator.Element) -> S.Iterator.Element {
var it = s.makeIterator()
let initial = it.next()!
return IteratorSequence(it).reduce(initial, combine: f)
}
public func run_CaptureProp(N: Int) {
let a = 1...10_000
for _ in 1...100*N {
benchCaptureProp(a, sum)
}
}
| apache-2.0 | 700278a07ade2f7a47a2d91657406e68 | 28.75 | 96 | 0.588235 | 3.823293 | false | false | false | false |
eKasztany/4ania | ios/Queue/Pods/PopupDialog/PopupDialog/Classes/PopupDialogDefaultViewController.swift | 3 | 4403 | //
// PopupDialogDefaultViewController.swift
//
// Copyright (c) 2016 Orderella Ltd. (http://orderella.co.uk)
// Author - Martin Wildfeuer (http://www.mwfire.de)
//
// 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
final public class PopupDialogDefaultViewController: UIViewController {
public var standardView: PopupDialogDefaultView {
return view as! PopupDialogDefaultView
}
override public func loadView() {
super.loadView()
view = PopupDialogDefaultView(frame: .zero)
}
}
public extension PopupDialogDefaultViewController {
// MARK: - Setter / Getter
// MARK: Content
/// The dialog image
public var image: UIImage? {
get { return standardView.imageView.image }
set {
standardView.imageView.image = newValue
standardView.imageView.isHidden = newValue != nil ? false : true
standardView.pv_layoutIfNeededAnimated()
}
}
/// The title text of the dialog
public var titleText: String? {
get { return standardView.titleLabel.text }
set {
standardView.titleLabel.text = newValue
//standardView.titleLabel.hidden = newValue != nil ? false : true
standardView.pv_layoutIfNeededAnimated()
}
}
/// The message text of the dialog
public var messageText: String? {
get { return standardView.messageLabel.text }
set {
standardView.messageLabel.text = newValue
//standardView.messageLabel.hidden = newValue != nil ? false : true
standardView.pv_layoutIfNeededAnimated()
}
}
// MARK: Appearance
/// The font and size of the title label
public dynamic var titleFont: UIFont {
get { return standardView.titleFont }
set {
standardView.titleFont = newValue
standardView.pv_layoutIfNeededAnimated()
}
}
/// The color of the title label
public dynamic var titleColor: UIColor? {
get { return standardView.titleLabel.textColor }
set {
standardView.titleColor = newValue
standardView.pv_layoutIfNeededAnimated()
}
}
/// The text alignment of the title label
public dynamic var titleTextAlignment: NSTextAlignment {
get { return standardView.titleTextAlignment }
set {
standardView.titleTextAlignment = newValue
standardView.pv_layoutIfNeededAnimated()
}
}
/// The font and size of the body label
public dynamic var messageFont: UIFont {
get { return standardView.messageFont}
set {
standardView.messageFont = newValue
standardView.pv_layoutIfNeededAnimated()
}
}
/// The color of the message label
public dynamic var messageColor: UIColor? {
get { return standardView.messageColor }
set {
standardView.messageColor = newValue
standardView.pv_layoutIfNeededAnimated()
}
}
/// The text alignment of the message label
public dynamic var messageTextAlignment: NSTextAlignment {
get { return standardView.messageTextAlignment }
set {
standardView.messageTextAlignment = newValue
standardView.pv_layoutIfNeededAnimated()
}
}
}
| apache-2.0 | 7a9b78af5a0e7cfdd71d41e9f317f6ab | 32.610687 | 81 | 0.661821 | 4.903118 | false | false | false | false |
PGSSoft/ParallaxView | Example-tvOS/ParallaxViewExample/ViewAnyViewController.swift | 1 | 4281 | //
// ViewAnyViewController.swift
// ParallaxViewExample
//
// Created by Łukasz Śliwiński on 16/06/16.
// Copyright © 2016 Łukasz Śliwiński. All rights reserved.
//
import UIKit
import ParallaxView
class ViewAnyViewController: UIViewController {
// MARK: IBOutlets
@IBOutlet weak var anyView: UIFocusableView!
@IBOutlet weak var anyLabel: UIFocusableLabel! {
didSet {
// Without setting userInteractionEnabled, label can't be focusable
anyLabel.isUserInteractionEnabled = true
anyLabel.layer.shadowColor = UIColor.black.cgColor
anyLabel.layer.shadowOpacity = 0.5
anyLabel.layer.shadowOffset = CGSize(width: 0, height: 5)
// Avoid cliping to fully show the shadow
anyLabel.clipsToBounds = false
}
}
var buttonParallaxEffectOptions: ParallaxEffectOptions!
@IBOutlet weak var anyButton: UIButton! {
didSet {
// Define custom glow for the parallax effect
let customGlowContainer = UIView(frame: anyButton.bounds)
customGlowContainer.clipsToBounds = true
customGlowContainer.backgroundColor = UIColor.clear
anyButton.subviews.first?.subviews.last?.addSubview(customGlowContainer)
buttonParallaxEffectOptions = ParallaxEffectOptions(glowContainerView: customGlowContainer)
// Add gray background color to make glow effect be more visible
anyButton.setBackgroundImage(getImageWithColor(UIColor.lightGray, size: anyButton.bounds.size), for: .normal)
}
}
// MARK: UIViewController
override func viewDidLoad() {
super.viewDidLoad()
}
override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {
coordinator.addCoordinatedAnimations({ [unowned self] in
// Add parallax effect only to controls inside this view controller
if let nextFocusedView = context.nextFocusedView, nextFocusedView.isDescendant(of: self.view) {
switch context.nextFocusedView {
case is UIButton:
// Custom parallax effect for the button
var buttonParallaxEffectOptions = self.buttonParallaxEffectOptions!
self.anyButton.addParallaxMotionEffects(with: &buttonParallaxEffectOptions)
case is UIFocusableLabel:
// Custom parallax effect for the label
var labelParallaxEffectOptions = ParallaxEffectOptions()
labelParallaxEffectOptions.glowAlpha = 0.0
labelParallaxEffectOptions.shadowPanDeviation = 10
self.anyLabel.addParallaxMotionEffects(with: &labelParallaxEffectOptions)
default:
// For the anyView use default options
context.nextFocusedView?.addParallaxMotionEffects()
}
}
// Remove parallax effect for the view that lost focus
switch context.previouslyFocusedView {
case is UIButton:
// Because anyButton uses custom glow container we have to pass it to remove parallax effect correctly
self.anyButton.removeParallaxMotionEffects(with: self.buttonParallaxEffectOptions!)
default:
context.previouslyFocusedView?.removeParallaxMotionEffects()
}
}, completion: nil)
}
// MARK: Convenience
func getImageWithColor(_ color: UIColor, size: CGSize) -> UIImage {
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
color.setFill()
UIRectFill(rect)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
}
}
// UIView is not focusable by default, we need to change it
class UIFocusableView: UIView {
override var canBecomeFocused : Bool {
return true
}
}
// UILabel is not focusable by default, we need to change it
class UIFocusableLabel: UILabel {
override var canBecomeFocused : Bool {
return true
}
}
| mit | 0dbafbe54b3f8d6eef8932435a9602ed | 36.491228 | 121 | 0.65606 | 5.3425 | false | false | false | false |
mvader/advent-of-code | 2020/20/02.swift | 1 | 6263 | import Foundation
enum Border: Hashable {
case top(String)
case left(String)
case right(String)
case bottom(String)
func value() -> String {
switch self {
case .top(let v): return v
case .left(let v): return v
case .bottom(let v): return v
case .right(let v): return v
}
}
}
func gridFlips(_ x: [String]) -> [[String]] {
return [
x,
x.reversed(),
x.map { String($0.reversed()) },
x.reversed().map { String($0.reversed()) },
]
}
func gridRotations(_ x: [String]) -> [[String]] {
var rotations = [x.map { [Character]($0) }]
for _ in 1...4 {
let last = rotations.last!
var tile = last
for y in 0..<tile.count {
for x in 0..<tile.count {
tile[x][y] = last[tile.count - y - 1][x]
}
}
rotations.append(tile)
}
return rotations.map { $0.map { String($0) } }
}
func gridPermutations(_ x: [String]) -> [[String]] {
var permutations = Set<[String]>()
for flip in gridFlips(x) {
for rotation in gridRotations(flip) {
permutations.update(with: rotation)
}
}
return [[String]](permutations)
}
struct Tile: Hashable {
let id: Int
let tile: [String]
func borders() -> [Border] {
let top = tile.first!
let bottom = tile.last!
let left = String(tile.map { $0.first! })
let right = String(tile.map { $0.last! })
return [.top(top), .left(left), .bottom(bottom), .right(right)]
}
func flips() -> [Tile] {
return gridFlips(tile).map { Tile(id: id, tile: $0) }
}
func rotations() -> [Tile] {
return gridRotations(tile).map { Tile(id: id, tile: $0) }
}
func permutations() -> [Tile] {
return gridPermutations(tile).map { Tile(id: id, tile: $0) }
}
func withoutBorders() -> Tile {
let t = tile.dropFirst().dropLast().map { String($0.dropFirst().dropLast()) }
return Tile(id: id, tile: t)
}
}
func parseInput(_ input: String) -> [Tile] {
return input.components(separatedBy: "\n\n").map { tile in
let lines = tile.components(separatedBy: "\n")
let id = Int(String(lines.first!.components(separatedBy: " ").last!.dropLast()))!
return Tile(id: id, tile: [String](lines.dropFirst()))
}
}
func assemble(_ tiles: [Tile]) -> [[Tile]] {
var borders = [Border: [Tile]]()
let side = Int(Double(tiles.count).squareRoot())
var grid = [[Tile?]](repeatElement([Tile?](repeatElement(nil, count: side)), count: side))
var permutations = tiles.flatMap { $0.permutations() }
for perm in permutations {
for border in perm.borders() {
borders.updateValue((borders[border] ?? []) + [perm], forKey: border)
}
}
for y in 0..<side {
for x in 0..<side {
let tile = permutations.first { t in
let bs = t.borders()
let (top, left, bottom, right) = (bs[0], bs[1], bs[2], bs[3])
// Discard if is the top edge and does not have an unmatched top border.
if y == 0 && borders[top]!.filter({ $0.id != t.id }).count > 0 {
return false
}
// Discard if is not on the bottom edge and the bottom border has no matching top border.
if y < side - 1 && borders[.top(bottom.value())]!.filter({ $0.id != t.id }).count == 0 {
return false
}
// Discard if is not on the right edge and the right border has no matching left border.
if x < side - 1 && borders[.left(right.value())]!.filter({ $0.id != t.id }).count == 0 {
return false
}
// Discard if is not on an edge and the top border does not match the previous bottom border.
if y > 0 && top.value() != grid[y - 1][x]!.borders()[2].value() {
return false
}
// Discard if is the left edge and does not have an unmatched left border.
if x == 0 && borders[left]!.filter({ $0.id != t.id }).count > 0 {
return false
}
// Discard if is not on an edge and the left border does not match the previous right border.
if x > 0 && left.value() != grid[y][x - 1]!.borders()[3].value() {
return false
}
// Discard if is the bottom edge and does not have an unmatched bottom border.
if y == side - 1 && borders[bottom]!.filter({ $0.id != t.id }).count > 0 {
return false
}
// Discard if is the right edge and does not have an unmatched right border.
if x == side - 1 && borders[right]!.filter({ $0.id != t.id }).count > 0 {
return false
}
return true
}!
grid[y][x] = tile
permutations = permutations.filter { $0.id != tile.id }
}
}
return grid.map { $0.map { $0!.withoutBorders() } }
}
func combineImage(_ image: [[Tile]]) -> [String] {
var result = [String](repeatElement("", count: image.count * image[0][0].tile.count))
for (i, row) in image.enumerated() {
for col in row {
for (j, line) in col.tile.enumerated() {
let idx = i * col.tile.count + j
result[idx] = result[idx] + line
}
}
}
return result
}
let seaMonster = [
(0, 1), (1, 2), (4, 2),
(5, 1), (6, 1), (7, 2),
(10, 2), (11, 1), (12, 1),
(13, 2), (16, 2), (17, 1),
(18, 1), (19, 1), (18, 0),
]
func detectSeaMonsters(_ img: [[Character]]) -> [[(Int, Int)]] {
var result = [[(Int, Int)]]()
for y in 0..<(img.count - 3) {
for x in 0..<(img[0].count - 20) {
let monster = seaMonster.map { pos in (x + pos.0, y + pos.1) }
if monster.allSatisfy({ img[$0.1][$0.0] == Character("#") }) {
result.append(monster)
}
}
}
return result
}
func waterRoughness(_ image: [String]) -> Int? {
for img in gridPermutations(image) {
var img = img.map { [Character]($0) }
let monsters = detectSeaMonsters(img)
if monsters.count == 0 {
continue
}
for monster in monsters {
for (x, y) in monster {
img[y][x] = Character(".")
}
}
var roughness = 0
for row in img {
for col in row {
if col == Character("#") {
roughness += 1
}
}
}
return roughness
}
return nil
}
let input = try String(contentsOfFile: "./input.txt", encoding: .utf8)
let image = assemble(parseInput(input))
let combinedImage = combineImage(image)
print(waterRoughness(combinedImage)!)
| mit | d9afab1696c8cfc295c3982d6874fc13 | 26.712389 | 101 | 0.560115 | 3.41122 | false | false | false | false |
nanthi1990/SwiftForms | SwiftForms/cells/base/FormBaseCell.swift | 2 | 3377 | //
// FormBaseCell.swift
// SwiftForms
//
// Created by Miguel Angel Ortuno on 20/08/14.
// Copyright (c) 2014 Miguel Angel Ortuño. All rights reserved.
//
import UIKit
public class FormBaseCell: UITableViewCell {
/// MARK: Properties
public var rowDescriptor: FormRowDescriptor! {
didSet {
self.update()
}
}
public weak var formViewController: FormViewController!
private var customConstraints: [AnyObject] = []
/// MARK: Init
public required override init(style: UITableViewCellStyle, reuseIdentifier: String!) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
public required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
/// MARK: Public interface
public func configure() {
/// override
}
public func update() {
/// override
}
public func defaultVisualConstraints() -> [String] {
/// override
return []
}
public func constraintsViews() -> [String : UIView] {
/// override
return [:]
}
public func firstResponderElement() -> UIResponder? {
/// override
return nil
}
public func inputAccesoryView() -> UIToolbar {
let actionBar = UIToolbar()
actionBar.translucent = true
actionBar.sizeToFit()
actionBar.barStyle = .Default
let doneButton = UIBarButtonItem(title: NSLocalizedString("Done", comment: ""), style: .Done, target: self, action: "handleDoneAction:")
let flexible = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
actionBar.items = [flexible, doneButton]
return actionBar
}
internal func handleDoneAction(_: UIBarButtonItem) {
firstResponderElement()?.resignFirstResponder()
}
public class func formRowCellHeight() -> CGFloat {
return 44.0
}
public class func formRowCanBecomeFirstResponder() -> Bool {
return false
}
public class func formViewController(formViewController: FormViewController, didSelectRow: FormBaseCell) {
}
/// MARK: Constraints
public override func updateConstraints() {
if customConstraints.count > 0 {
contentView.removeConstraints(customConstraints)
}
var views = constraintsViews()
customConstraints.removeAll()
var visualConstraints: NSArray!
if let visualConstraintsClosure = rowDescriptor.configuration[FormRowDescriptor.Configuration.VisualConstraintsClosure] as? VisualConstraintsClosure {
visualConstraints = visualConstraintsClosure(self)
}
else {
visualConstraints = self.defaultVisualConstraints()
}
for visualConstraint in visualConstraints {
let constraints = NSLayoutConstraint.constraintsWithVisualFormat(visualConstraint as! String, options: NSLayoutFormatOptions(0), metrics: nil, views: views)
for constraint in constraints {
customConstraints.append(constraint)
}
}
contentView.addConstraints(customConstraints)
super.updateConstraints()
}
}
| mit | 8960dccf9fea49ab01496f86453fe37e | 26.900826 | 168 | 0.618483 | 5.731749 | false | false | false | false |
calebkleveter/UIWebKit | Sources/UIWebKit/UIWebPage.swift | 1 | 4200 | // The MIT License (MIT)
//
// Copyright (c) 2016 Caleb Kleveter
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
import Vapor
import HTTP
/// Represents a web page and contains all the HTML elements.
open class UIWebPage {
/// The head in a web page.
public var head: UIElement
/// The header of the page.
public var header: UIElement
/// The section between the header and the footer of the page.
public var section: UIElement
/// The footer of the page.
public var footer: UIElement
/// Dependancies that will be loaded into the webpage such as Bootstrap or JQuery.
private(set) var dependancies: [Dependency] = []
/// Creates a web page with a head, header, section and footer.
///
/// - returns: A UIWebPage with all the neccasary elements.
public init() {
self.head = UIElement(element: .head)
self.header = UIElement(element: .header)
self.section = UIElement(element: .section)
self.footer = UIElement(element: .footer)
}
/// Creates an instance of `UIWebPage` with the basic required elements.
///
/// - Parameter title: The title of the page.
convenience public init(title: String) {
self.init()
self.head.inject("<title>\(title)</title>")
}
/// For custom configuration of the web page before it is rendered. Over-ride this method to do anything before page rendering.
open func configure() {}
/// Renders the current page to a View with bytes that can be returned from a droplet route.
///
/// - Returns: A view that contains the pages HTML in bytes.
/// - Throws: Any errors that get thrown when creating the view.
public func render() -> View {
self.configure()
var html = ""
html.append("<!DOCTYPE html>")
for dependency in dependancies {
if let cssTags = dependency.htmlTags[.css] {
for tag in cssTags {
head.inject(tag)
}
}
}
html.append(head.render())
html.append("<body>")
html.append(header.render())
html.append(section.render())
html.append(footer.render())
for dependency in dependancies {
if let jsTags = dependency.htmlTags[.javaScript] {
for tag in jsTags {
html.append(tag)
}
}
}
html.append("</body>")
return View(bytes: html.bytes)
}
/// Adds dependancies that will be loaded into the webpage.
///
/// - Parameter dependancy: The dependancy that will added to the webpage.
public func `import`(_ dependency: Dependency) {
self.dependancies.append(dependency)
}
}
extension UIWebPage: ResponseRepresentable {
/// Handles auto rendering for routes.
///
/// - Returns: A response containing the view from rendering.
/// - Throws: Any errors generated from creating the view.
public func makeResponse()throws -> Response {
return render().makeResponse()
}
}
| mit | 7e692672f3d50eab47122d629ffcf93f | 35.206897 | 131 | 0.641905 | 4.585153 | false | false | false | false |
lfkdsk/JustUiKit | JustUiKit/layout/JustViewGroup.swift | 1 | 2957 | /// MIT License
///
/// Copyright (c) 2017 JustWe
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in all
/// copies or substantial portions of the Software.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
/// SOFTWARE.
import Foundation
import UIKit
open class JustViewGroup: UIView, JustViewParent, JustViewManager {
private var parentView: JustViewParent? = nil;
private var isChanged: Bool = false
public init() {
super.init(frame: CGRect.zero)
isChanged = false
}
public override init(frame groupFrame: CGRect) {
super.init(frame: groupFrame)
isChanged = false
}
public init(frame groupFrame: CGRect,
parentView: JustViewParent) {
super.init(frame: groupFrame)
self.parentView = parentView
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public func onLayout(_ changed: Bool = false,
_ top: CGFloat,
_ left: CGFloat,
_ right: CGFloat,
_ bottom: CGFloat) {
}
public func onMeasure(_ size: CGSize) {
}
override open func layoutSubviews() {
let top = frame.origin.y
let left = frame.origin.x
let right = frame.size.width + left
let bottom = frame.size.height + top
onMeasure(frame.size)
onLayout(isChanged, top, left, right, bottom)
}
public func getParent() -> JustViewParent {
return parentView!
}
public func requestLayout() {
}
public func setParent(viewGroup: JustViewParent) {
self.parentView = viewGroup
}
public func hasParent() -> Bool {
return parentView != nil
}
public func updateView(view: UIView, params: LayoutParams) {
}
public func removeView(view: UIView) {
// self.willRemoveSubview(view)
}
public func addView(view: UIView) {
}
}
| mit | 766eb8cf240776ed9d5c9070213bd644 | 27.432692 | 85 | 0.637132 | 4.514504 | false | false | false | false |
glock45/swifter | Sources/Swifter/String+File.swift | 1 | 4145 | //
// String+File.swift
// Swifter
//
// Copyright © 2016 Damian Kołakowski. All rights reserved.
//
import Foundation
extension String {
public enum FileError: Error {
case error(Int32)
}
public class File {
internal let pointer: UnsafeMutablePointer<FILE>
public init(_ pointer: UnsafeMutablePointer<FILE>) {
self.pointer = pointer
}
public func close() -> Void {
fclose(pointer)
}
public func read(_ data: inout [UInt8]) throws -> Int {
if data.count <= 0 {
return data.count
}
let count = fread(&data, 1, data.count, self.pointer)
if count == data.count {
return count
}
if feof(self.pointer) != 0 {
return count
}
if ferror(self.pointer) != 0 {
throw FileError.error(errno)
}
throw FileError.error(0)
}
public func write(_ data: [UInt8]) throws -> Void {
if data.count <= 0 {
return
}
try data.withUnsafeBufferPointer {
if fwrite($0.baseAddress, 1, data.count, self.pointer) != data.count {
throw FileError.error(errno)
}
}
}
}
public static var PATH_SEPARATOR = "/"
public func openNewForWriting() throws -> File {
return try openFileForMode(self, "wb")
}
public func openForReading() throws -> File {
return try openFileForMode(self, "rb")
}
public func openForWritingAndReading() throws -> File {
return try openFileForMode(self, "r+b")
}
public func openFileForMode(_ path: String, _ mode: String) throws -> File {
guard let file = path.withCString({ pathPointer in mode.withCString({ fopen(pathPointer, $0) }) }) else {
throw FileError.error(errno)
}
return File(file)
}
public func exists() throws -> Bool {
return try self.withStat {
if let _ = $0 {
return true
}
return false
}
}
public func directory() throws -> Bool {
return try self.withStat {
if let stat = $0 {
return stat.st_mode & S_IFMT == S_IFDIR
}
return false
}
}
public func files() throws -> [String] {
guard let dir = self.withCString({ opendir($0) }) else {
throw FileError.error(errno)
}
defer { closedir(dir) }
var results = [String]()
while let ent = readdir(dir) {
var name = ent.pointee.d_name
let fileName = withUnsafePointer(to: &name) { (ptr) -> String? in
#if os(Linux)
return String.fromCString([CChar](UnsafeBufferPointer<CChar>(start: UnsafePointer(unsafeBitCast(ptr, UnsafePointer<CChar>.self)), count: 256)))
#else
var buffer = [CChar](UnsafeBufferPointer(start: unsafeBitCast(ptr, to: UnsafePointer<CChar>.self), count: Int(ent.pointee.d_namlen)))
buffer.append(0)
return String(validatingUTF8: buffer)
#endif
}
if let fileName = fileName {
results.append(fileName)
}
}
return results
}
public static func currentWorkingDirectory() throws -> String {
guard let path = getcwd(nil, 0) else {
throw FileError.error(errno)
}
return String(cString: path)
}
private func withStat<T>(_ closure: ((stat?) throws -> T)) throws -> T {
return try self.withCString({
var statBuffer = stat()
if stat($0, &statBuffer) == 0 {
return try closure(statBuffer)
}
if errno == ENOENT {
return try closure(nil)
}
throw FileError.error(errno)
})
}
}
| bsd-3-clause | 46a0cc549591d6926a781f51f6402736 | 28.805755 | 163 | 0.505189 | 4.767549 | false | false | false | false |
jpmcglone/AnyAPI | Pods/Nimble/Carthage/Checkouts/CwlPreconditionTesting/Sources/CwlPreconditionTesting/CwlCatchBadInstruction.swift | 12 | 10117 | //
// CwlCatchBadInstruction.swift
// CwlPreconditionTesting
//
// Created by Matt Gallagher on 2016/01/10.
// Copyright © 2016 Matt Gallagher ( https://www.cocoawithlove.com ). All rights reserved.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
// IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
#if (os(macOS) || os(iOS)) && arch(x86_64)
import Foundation
import Swift
#if SWIFT_PACKAGE
import CwlMachBadInstructionHandler
#endif
private enum PthreadError: Error { case code(Int32) }
private enum MachExcServer: Error { case code(kern_return_t) }
/// A quick function for converting Mach error results into Swift errors
private func kernCheck(_ f: () -> Int32) throws {
let r = f()
guard r == KERN_SUCCESS else {
throw NSError(domain: NSMachErrorDomain, code: Int(r), userInfo: nil)
}
}
extension request_mach_exception_raise_t {
mutating func withMsgHeaderPointer<R>(in block: (UnsafeMutablePointer<mach_msg_header_t>) -> R) -> R {
return withUnsafeMutablePointer(to: &self) { p -> R in
return p.withMemoryRebound(to: mach_msg_header_t.self, capacity: 1) { ptr -> R in
return block(ptr)
}
}
}
}
extension reply_mach_exception_raise_state_t {
mutating func withMsgHeaderPointer<R>(in block: (UnsafeMutablePointer<mach_msg_header_t>) -> R) -> R {
return withUnsafeMutablePointer(to: &self) { p -> R in
return p.withMemoryRebound(to: mach_msg_header_t.self, capacity: 1) { ptr -> R in
return block(ptr)
}
}
}
}
/// A structure used to store context associated with the Mach message port
private struct MachContext {
var masks = execTypesCountTuple<exception_mask_t>()
var count: mach_msg_type_number_t = 0
var ports = execTypesCountTuple<mach_port_t>()
var behaviors = execTypesCountTuple<exception_behavior_t>()
var flavors = execTypesCountTuple<thread_state_flavor_t>()
var currentExceptionPort: mach_port_t = 0
var handlerThread: pthread_t? = nil
static func internalMutablePointers<R>(_ m: UnsafeMutablePointer<execTypesCountTuple<exception_mask_t>>, _ c: UnsafeMutablePointer<mach_msg_type_number_t>, _ p: UnsafeMutablePointer<execTypesCountTuple<mach_port_t>>, _ b: UnsafeMutablePointer<execTypesCountTuple<exception_behavior_t>>, _ f: UnsafeMutablePointer<execTypesCountTuple<thread_state_flavor_t>>, _ block: (UnsafeMutablePointer<exception_mask_t>, UnsafeMutablePointer<mach_msg_type_number_t>, UnsafeMutablePointer<mach_port_t>, UnsafeMutablePointer<exception_behavior_t>, UnsafeMutablePointer<thread_state_flavor_t>) -> R) -> R {
return m.withMemoryRebound(to: exception_mask_t.self, capacity: 1) { masksPtr in
return c.withMemoryRebound(to: mach_msg_type_number_t.self, capacity: 1) { countPtr in
return p.withMemoryRebound(to: mach_port_t.self, capacity: 1) { portsPtr in
return b.withMemoryRebound(to: exception_behavior_t.self, capacity: 1) { behaviorsPtr in
return f.withMemoryRebound(to: thread_state_flavor_t.self, capacity: 1) { flavorsPtr in
return block(masksPtr, countPtr, portsPtr, behaviorsPtr, flavorsPtr)
}
}
}
}
}
}
mutating func withUnsafeMutablePointers<R>(in block: @escaping (UnsafeMutablePointer<exception_mask_t>, UnsafeMutablePointer<mach_msg_type_number_t>, UnsafeMutablePointer<mach_port_t>, UnsafeMutablePointer<exception_behavior_t>, UnsafeMutablePointer<thread_state_flavor_t>) -> R) -> R {
return MachContext.internalMutablePointers(&masks, &count, &ports, &behaviors, &flavors, block)
}
}
/// A function for receiving mach messages and parsing the first with mach_exc_server (and if any others are received, throwing them away).
private func machMessageHandler(_ arg: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer? {
let context = arg.assumingMemoryBound(to: MachContext.self).pointee
var request = request_mach_exception_raise_t()
var reply = reply_mach_exception_raise_state_t()
var handledfirstException = false
repeat { do {
// Request the next mach message from the port
request.Head.msgh_local_port = context.currentExceptionPort
request.Head.msgh_size = UInt32(MemoryLayout<request_mach_exception_raise_t>.size)
let requestSize = request.Head.msgh_size
try kernCheck { request.withMsgHeaderPointer { requestPtr in
mach_msg(requestPtr, MACH_RCV_MSG | MACH_RCV_INTERRUPT, 0, requestSize, context.currentExceptionPort, 0, UInt32(MACH_PORT_NULL))
} }
// Prepare the reply structure
reply.Head.msgh_bits = MACH_MSGH_BITS(MACH_MSGH_BITS_REMOTE(request.Head.msgh_bits), 0)
reply.Head.msgh_local_port = UInt32(MACH_PORT_NULL)
reply.Head.msgh_remote_port = request.Head.msgh_remote_port
reply.Head.msgh_size = UInt32(MemoryLayout<reply_mach_exception_raise_state_t>.size)
reply.NDR = NDR_record
if !handledfirstException {
// Use the MiG generated server to invoke our handler for the request and fill in the rest of the reply structure
guard request.withMsgHeaderPointer(in: { requestPtr in reply.withMsgHeaderPointer { replyPtr in
mach_exc_server(requestPtr, replyPtr)
} }) != 0 else { throw MachExcServer.code(reply.RetCode) }
handledfirstException = true
} else {
// If multiple fatal errors occur, don't handle subsquent errors (let the program crash)
reply.RetCode = KERN_FAILURE
}
// Send the reply
let replySize = reply.Head.msgh_size
try kernCheck { reply.withMsgHeaderPointer { replyPtr in
mach_msg(replyPtr, MACH_SEND_MSG, replySize, 0, UInt32(MACH_PORT_NULL), 0, UInt32(MACH_PORT_NULL))
} }
} catch let error as NSError where (error.domain == NSMachErrorDomain && (error.code == Int(MACH_RCV_PORT_CHANGED) || error.code == Int(MACH_RCV_INVALID_NAME))) {
// Port was already closed before we started or closed while we were listening.
// This means the controlling thread shut down.
return nil
} catch {
// Should never be reached but this is testing code, don't try to recover, just abort
fatalError("Mach message error: \(error)")
} } while true
}
/// Run the provided block. If a mach "BAD_INSTRUCTION" exception is raised, catch it and return a BadInstructionException (which captures stack information about the throw site, if desired). Otherwise return nil.
/// NOTE: This function is only intended for use in test harnesses – use in a distributed build is almost certainly a bad choice. If a "BAD_INSTRUCTION" exception is raised, the block will be exited before completion via Objective-C exception. The risks associated with an Objective-C exception apply here: most Swift/Objective-C functions are *not* exception-safe. Memory may be leaked and the program will not necessarily be left in a safe state.
/// - parameter block: a function without parameters that will be run
/// - returns: if an EXC_BAD_INSTRUCTION is raised during the execution of `block` then a BadInstructionException will be returned, otherwise `nil`.
public func catchBadInstruction(in block: @escaping () -> Void) -> BadInstructionException? {
// Suppress Swift runtime's direct triggering of the debugger and exclusivity checking which crashes when we throw past it
let previousExclusivity = _swift_disableExclusivityChecking
let previousReporting = _swift_reportFatalErrorsToDebugger
_swift_disableExclusivityChecking = true
_swift_reportFatalErrorsToDebugger = false
defer {
_swift_reportFatalErrorsToDebugger = previousReporting
_swift_disableExclusivityChecking = previousExclusivity
}
var context = MachContext()
var result: BadInstructionException? = nil
do {
var handlerThread: pthread_t? = nil
defer {
// 8. Wait for the thread to terminate *if* we actually made it to the creation point
// The mach port should be destroyed *before* calling pthread_join to avoid a deadlock.
if handlerThread != nil {
pthread_join(handlerThread!, nil)
}
}
try kernCheck {
// 1. Create the mach port
mach_port_allocate(mach_task_self_, MACH_PORT_RIGHT_RECEIVE, &context.currentExceptionPort)
}
defer {
// 7. Cleanup the mach port
mach_port_destroy(mach_task_self_, context.currentExceptionPort)
}
try kernCheck {
// 2. Configure the mach port
mach_port_insert_right(mach_task_self_, context.currentExceptionPort, context.currentExceptionPort, MACH_MSG_TYPE_MAKE_SEND)
}
let currentExceptionPtr = context.currentExceptionPort
try kernCheck { context.withUnsafeMutablePointers { masksPtr, countPtr, portsPtr, behaviorsPtr, flavorsPtr in
// 3. Apply the mach port as the handler for this thread
thread_swap_exception_ports(mach_thread_self(), EXC_MASK_BAD_INSTRUCTION, currentExceptionPtr, Int32(bitPattern: UInt32(EXCEPTION_STATE) | MACH_EXCEPTION_CODES), x86_THREAD_STATE64, masksPtr, countPtr, portsPtr, behaviorsPtr, flavorsPtr)
} }
defer { context.withUnsafeMutablePointers { masksPtr, countPtr, portsPtr, behaviorsPtr, flavorsPtr in
// 6. Unapply the mach port
_ = thread_swap_exception_ports(mach_thread_self(), EXC_MASK_BAD_INSTRUCTION, 0, EXCEPTION_DEFAULT, THREAD_STATE_NONE, masksPtr, countPtr, portsPtr, behaviorsPtr, flavorsPtr)
} }
try withUnsafeMutablePointer(to: &context) { c throws in
// 4. Create the thread
let e = pthread_create(&handlerThread, nil, machMessageHandler, c)
guard e == 0 else { throw PthreadError.code(e) }
// 5. Run the block
result = BadInstructionException.catchException(in: block)
}
} catch {
// Should never be reached but this is testing code, don't try to recover, just abort
fatalError("Mach port error: \(error)")
}
return result
}
#endif
| mit | 66fa837d6d413c21769b33d3067d774b | 47.392344 | 592 | 0.746787 | 3.802256 | false | false | false | false |
tylow/surftranslate | surftranslate/SURF_Translate/DeckTableViewController.swift | 1 | 9259 | //
// DeckTableViewController.swift
// SURF_Translate
//
// Created by Legeng Liu on 6/1/16.
// Copyright © 2016 SURF. All rights reserved.
//
import UIKit
class DeckTableViewController: UITableViewController, UINavigationControllerDelegate{
//MARK: Properties:
//keeps array of Deck objects
var decks = [Deck]()
//favoriteDecks is used *internally* to keep track of all my favorite decks. For sorting purposes etc.
// every time a Deck is favorited, add it to the favoriteDecks array, but also have it in the normal decks array, because the tableview controller displays the decks array. favoriteDecks is not displayed and only used to keep track internally.
var favoriteDecks = [Deck]()
//implementing search. "nil" means no new view controller needed when searching
let searchController = UISearchController(searchResultsController: nil)
var filteredDecks = [Deck]()
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()
//making sample Cards and Decks to test stuff
var sampleCards = [Card]()
var sampleCards2 = [Card]()
var sampleCards3 = [Card]()
let card1 = Card(firstPhrase: "1", secondPhrase: "2", numTimesUsed: 0)!
let card2 = Card(firstPhrase: "english", secondPhrase: "arabic", numTimesUsed : 0)!
let card3 = Card(firstPhrase: "I need water", secondPhrase: "أحتاج إلى الماء", numTimesUsed :0)!
let card4 = Card(firstPhrase: "Hello", secondPhrase: "Salaam", numTimesUsed: 0)!
sampleCards += [card1, card2, card3, card4]
sampleCards2 += [card1, card3, card4]
sampleCards3 += [card3, card4]
let deck1 = Deck(name: "Refugee", cards: sampleCards, language1: "English", language2: "Arabic", isFavorite: true)!
let deck2 = Deck(name: "UNHCR Phrasebook", cards: sampleCards2, language1: "English", language2: "Arabic", isFavorite: true)!
let deck3 = Deck(name: "UNHCR Phrasebook Extended extended extended extended extended dddddddddddddddddddddddddddddddd", cards: sampleCards, language1: "English", language2: "Arabic", isFavorite: false)!
let deck4 = Deck(name: "Doctors to Refugees", cards: sampleCards, language1: "English", language2: "Arabic", isFavorite: false)!
let deck5 = Deck(name: "Commonly used in camp", cards: sampleCards, language1: "English", language2: "Arabic", isFavorite: false)!
let deck6 = Deck(name: "Customized deck", cards: sampleCards, language1: "English", language2: "Arabic", isFavorite: false)!
let deck7 = Deck(name: "Imported Online", cards: sampleCards3, language1: "English", language2: "Arabic", isFavorite: false)!
decks += [deck1, deck2, deck3, deck4, deck5, deck6, deck7]
//filtering favorited decks from all decks
favoriteDecks = decks.filter{$0.isFavorite == true}
//MARK: search
searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
searchController.hidesNavigationBarDuringPresentation = true //maybe we should set this to true?
definesPresentationContext = true
tableView.tableHeaderView = searchController.searchBar
}
func filterContentForSearchText(searchText: String){
filteredDecks = decks.filter{deck in
return deck.name.lowercaseString.containsString(searchText.lowercaseString)
}
tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
//when searching, return the # of Decks that fit search criteria, otherwise return total #
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searchController.active && searchController.searchBar.text != "" {
return filteredDecks.count
} else {
return decks.count
}
}
//lets DeckTableViewController set the values inside each cell to decks that are already filtered
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "DeckTableViewCell" //this unique identifier can be edited in Attributes section of Cell object
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! DeckTableViewCell
var deck: Deck
if searchController.active && searchController.searchBar.text != "" {
deck = filteredDecks[indexPath.row]
} else {
deck = decks[indexPath.row]
}
cell.deckName.text = deck.name
cell.numberOfCards.text = "Cards:" + String(deck.cards.count)
cell.deckFavoriteControl.isFavorite = deck.isFavorite
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
var selectedDeck: Deck
if segue.identifier == "showCards"{
let showCardsViewController = segue.destinationViewController as! CardTableViewController
if let selectedDeckCell = sender as? DeckTableViewCell{
let indexPath = tableView.indexPathForCell(selectedDeckCell)!
if searchController.active && searchController.searchBar.text != "" {
selectedDeck = filteredDecks[indexPath.row]
} else {
selectedDeck = decks[indexPath.row]
}
showCardsViewController.cards = selectedDeck.cards
showCardsViewController.navigationItem.title? = selectedDeck.name
}
} else if segue.identifier == "AddDeck"{
print ("add new deck")
}
}
@IBAction func unwindToDeckList(sender: UIStoryboardSegue) {
if let sourceViewController = sender.sourceViewController as? NewDeckViewController, newDeck = sourceViewController.newDeck {
// if new made Deck is favorited, then this code below puts it on top, below the other Favorited decks.
if newDeck.isFavorite == true{
let newIndexPath = NSIndexPath(forRow: favoriteDecks.count, inSection: 0)
decks.insert(newDeck, atIndex: favoriteDecks.count)
tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Bottom)
favoriteDecks.append(newDeck)
// if not a Favorite, then put on bottom of all the decks
} else {
let newIndexPath = NSIndexPath(forRow: decks.count, inSection: 0)
decks.append(newDeck)
tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Bottom)
}
}
}
}
extension DeckTableViewController: UISearchResultsUpdating{
func updateSearchResultsForSearchController(searchController: UISearchController) {
filterContentForSearchText(searchController.searchBar.text!)
}
}
| agpl-3.0 | a435034951884ac5126fc4b1cbfc4ae3 | 41.022727 | 248 | 0.659924 | 5.096472 | false | false | false | false |
diwu/LeetCode-Solutions-in-Swift | Solutions/Solutions/Medium/Medium_053_Maximum_Subarray.swift | 1 | 814 | /*
https://leetcode.com/problems/maximum-subarray/
#53 Maximum Subarray
Level: medium
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [−2,1,−3,4,−1,2,1,−5,4],
the contiguous subarray [4,−1,2,1] has the largest sum = 6.
Inspired by @john6 at https://leetcode.com/discuss/1832/ive-idea-stucked-the-exception-situation-could-somebody-help
*/
import Foundation
struct Medium_053_Maximum_Subarray {
static func maxSubArray(_ n: [Int]) -> Int {
let nums = n
var best = nums[0];
var current = nums[0];
for i in 1..<nums.count {
current = max(current + nums[i], nums[i]);
best = max(current, best);
}
return best;
}
}
| mit | 520dd3ada08224971475304cbe8265dc | 23.363636 | 116 | 0.624378 | 3.308642 | false | false | false | false |
nebhale/LoggerLogger | LoggerLogger/InMemoryDateFormatterPool.swift | 1 | 1678 | /*
Copyright 2015 the original author or authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
/**
An in-memory implementation of `DateFormatterPool`.
*/
public final class InMemoryDateFormatterPool: DateFormatterPool {
private let monitor = Monitor()
private var dateFormatters = [String : NSDateFormatter]()
/**
Returns an `NSDateFormatter` for a given `format`. Implementations should return the **same** instance for all subsequent calls that pass the same `format`.
- parameter format: The format to return an `NSDateFormatter` for
- returns: A new or previously created `NSDateFormatter` for this `format`
*/
public func get(format: String) -> NSDateFormatter {
return syncronized(self.monitor) {
if let candidate = self.dateFormatters[format] {
return candidate
} else {
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
dateFormatter.dateFormat = format
self.dateFormatters[format] = dateFormatter
return dateFormatter
}
}
}
} | apache-2.0 | 6094b10481b10a4581c12f99577dc1e8 | 32.58 | 161 | 0.695471 | 4.979228 | false | false | false | false |
PedroTrujilloV/TIY-Assignments | 19--Keep-On-The-Sunny-Side/Forecaster/GitHub Friends/DetailViewController.swift | 1 | 3167 | //
// ViewController.swift
// GitHub Friends
//
// Created by Pedro Trujillo on 10/29/15.
// Copyright © 2015 Pedro Trujillo. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController
{
var userImageView:UIImageView!
var imagePath = "gravatar.png"
var userImage:UIImage!
var cityData: CityData!
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view.
self.view.backgroundColor = UIColor.whiteColor()
//
self.loadImage(cityData.largeImageURL)
self.setLabels(cityData.login,x: view.center.x, y: userImageView.center.y * 0.4)
self.setLabels(cityData.name,x: view.center.x, y: userImageView.center.y * 1.6)
self.setLabels(cityData.email,x: view.center.x, y: userImageView.center.y * 1.7)
self.setLabels(cityData.location,x: view.center.x, y: userImageView.center.y * 1.8)
self.setLabels(cityData.company,x: view.center.x, y: userImageView.center.y * 1.9)
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setLabels( labelString:String = "Penpenuche", x :CGFloat = 0, y :CGFloat = 0)
{
let loginLabel:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 60))
//self.loginLabel.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width * 0.9 , height: self.view.frame.size.width * 0.1)
loginLabel.text = labelString
loginLabel.center.x = x
loginLabel.center.y = y
loginLabel.numberOfLines = 1
loginLabel.textAlignment = .Center
view.addSubview(loginLabel)
}
func loadImage(var ImagePath:String = "")
{
if ImagePath == ""
{ImagePath = self.imagePath}
else
{self.imagePath = ImagePath}
if let url = NSURL(string: ImagePath)
{
if let data = NSData(contentsOfURL: url)
{
self.userImage = UIImage(data: data)
self.userImageView = UIImageView(image: userImage!)
self.userImageView!.contentMode = UIViewContentMode.ScaleAspectFit
self.userImageView.frame = CGRect(x: 0, y: 0 , width: self.view.frame.size.width * 0.9 , height: self.view.frame.size.width * 0.9 )
self.userImageView.center.x = view.center.x
self.userImageView.center.y = UIScreen.mainScreen().bounds.height * 0.5
view.addSubview(userImageView)
}
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| cc0-1.0 | 565204c652ba13aa74f95998ebde118b | 31.639175 | 147 | 0.608023 | 4.272605 | false | false | false | false |
oisinlavery/HackingWithSwift | project4-oisin/project4-oisin/TableViewController.swift | 1 | 4105 | //
// TableViewController.swift
// project4-oisin
//
// Created by Oisín Lavery on 10/2/15.
// Copyright © 2015 Oisín Lavery. All rights reserved.
//
import UIKit
class TableViewController: UITableViewController {
var websites = ["apple.com", "hackingwithswift.com", "reddit.com", "google.com"]
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()
// tableView.delegate = self
// tableView.dataSource = self
// tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
title = "Websites"
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return websites.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
cell.textLabel?.text = websites[indexPath.row]
return cell
}
// override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//// tableView.deselectRowAtIndexPath(indexPath, animated: true)
// let row = indexPath.row
// performSegueWithIdentifier("showWebsiteSegue", sender: row)
// }
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if segue.identifier == "showWebViewSegue" {
if let indexPath = self.tableView.indexPathForSelectedRow {
let controller = (segue.destinationViewController as! UINavigationController).topViewController as! WebViewController
controller.website = websites[indexPath.row]
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
}
}
| unlicense | d6b6baa9590862730e8cb7c67df12706 | 35.300885 | 157 | 0.685275 | 5.50604 | false | false | false | false |
algolia/algoliasearch-client-swift | Sources/AlgoliaSearchClient/Models/Insights/InsightsEvent+Resources.swift | 1 | 2813 | //
// InsightsEvent+Resources.swift
//
//
// Created by Vladislav Fitc on 23/04/2020.
//
import Foundation
extension InsightsEvent {
public enum Resources: Equatable {
case objectIDs([ObjectID])
case filters([String])
case objectIDsWithPositions([(ObjectID, Int)])
public static func == (lhs: InsightsEvent.Resources, rhs: InsightsEvent.Resources) -> Bool {
switch (lhs, rhs) {
case (.objectIDs(let lValue), .objectIDs(let rValue)):
return lValue == rValue
case (.filters(let lValue), .filters(let rValue)):
return lValue == rValue
case (.objectIDsWithPositions(let lValue), .objectIDsWithPositions(let rValue)):
return lValue.map { $0.0 } == rValue.map { $0.0 } && lValue.map { $0.1 } == rValue.map { $0.1 }
default:
return false
}
}
}
}
extension InsightsEvent.Resources: Codable {
enum CodingKeys: String, CodingKey {
case objectIDs
case filters
case positions
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let objectIDsDecodingError: Error
let filtersDecodingError: Error
do {
let objectIDs = try container.decode([ObjectID].self, forKey: .objectIDs)
if let positions = try? container.decode([Int].self, forKey: .positions) {
self = .objectIDsWithPositions(zip(objectIDs, positions).map { $0 })
} else {
self = .objectIDs(objectIDs)
}
return
} catch let error {
objectIDsDecodingError = error
}
do {
let filters = try container.decode([String].self, forKey: .filters)
self = .filters(filters)
return
} catch let error {
filtersDecodingError = error
}
let compositeError = CompositeError.with(objectIDsDecodingError, filtersDecodingError)
typealias Keys = InsightsEvent.Resources.CodingKeys
let context = DecodingError.Context(codingPath: decoder.codingPath,
debugDescription: "Neither \(Keys.filters.rawValue), nor \(Keys.objectIDs.rawValue) key found on decoder",
underlyingError: compositeError)
throw DecodingError.dataCorrupted(context)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
switch self {
case .filters(let filters):
try container.encode(filters, forKey: .filters)
case .objectIDsWithPositions(let objectIDswithPositions):
try container.encode(objectIDswithPositions.map { $0.0 }, forKey: .objectIDs)
try container.encode(objectIDswithPositions.map { $0.1 }, forKey: .positions)
case .objectIDs(let objectsIDs):
try container.encode(objectsIDs, forKey: .objectIDs)
}
}
}
| mit | 3ae9039b87d4fc84588ceb1be083b323 | 28.610526 | 146 | 0.658372 | 4.354489 | false | false | false | false |
orangeince/EtuGitLabBot | Sources/main.swift | 1 | 2751 | //
// main.swift
// PerfectTemplate
//
// Created by Kyle Jessup on 2015-11-05.
// Copyright (C) 2015 PerfectlySoft, Inc.
//
//===----------------------------------------------------------------------===//
//
// This source file is part of the Perfect.org open source project
//
// Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors
// Licensed under Apache License v2.0
//
// See http://perfect.org/licensing.html for license information
//
//===----------------------------------------------------------------------===//
//
import PerfectLib
import PerfectHTTP
import PerfectHTTPServer
// Create HTTP server.
let server = HTTPServer()
// Register your own routes and handlers
var routes = Routes()
routes.add(method: .get, uri: "/", handler: {
request, response in
response.setHeader(.contentType, value: "text/html")
response.appendBody(string: "<html><title>Hello, world!</title><body>Hello, world!</body></html>")
response.completed()
}
)
routes.add(
method: .post, uri: "/etugit/", handler: {
request, response in
if let bodyStr = request.postBodyString {
print("received request body:\n\(bodyStr)")
GitlabServant.shared.didReceived(message: bodyStr)
}
response.appendBody(string: "ok")
response.completed()
}
)
routes.add(
method: .post, uri: "/etugit/activate_subscribe/", handler: {
request, response in
if let userIdStr = request.param(name: "user_id"),
let userId = Int(userIdStr) {
let mrFilterLabel = request.param(name: "mr_label")
GitlabServant.shared.activate(subscriber: userId, filterLabel: mrFilterLabel)
}
response.appendBody(string: "ok")
response.completed()
}
)
routes.add(method: .get, uri: "/etugit/feed/", handler: {
request, response in
if let userIdStr = request.param(name: "user_id"),
let userId = Int(userIdStr) {
response.appendBody(string: GitlabServant.shared.getFeedFor(subscriber: userId))
} else {
response.appendBody(string: "error: no user_id")
}
response.completed()
}
)
// Add the routes to the server.
server.addRoutes(routes)
// Set a listen port of 8181
server.serverPort = 12322
// Set a document root.
// This is optional. If you do not want to serve static content then do not set this.
// Setting the document root will automatically add a static file handler for the route /**
server.documentRoot = "./webroot"
// Gather command line options and further configure the server.
// Run the server with --help to see the list of supported arguments.
// Command line arguments will supplant any of the values set above.
configureServer(server)
do {
// Launch the HTTP server.
try server.start()
} catch PerfectError.networkError(let err, let msg) {
print("Network error thrown: \(err) \(msg)")
}
| apache-2.0 | f7920fc19d4a8a351988ea3e2472f31e | 27.957895 | 100 | 0.672483 | 3.629288 | false | false | false | false |
antonio081014/LeeCode-CodeBase | Swift/lowest-common-ancestor-of-deepest-leaves.swift | 2 | 2291 | /**
* https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves/
*
*
*/
// Date: Sat Dec 12 23:44:14 PST 2020
/**
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init() { self.val = 0; self.left = nil; self.right = nil; }
* public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
* public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
* self.val = val
* self.left = left
* self.right = right
* }
* }
*/
extension TreeNode: Hashable {
public static func == (lhs: TreeNode, rhs: TreeNode) -> Bool {
return lhs.val == rhs.val
}
public func hash(into hasher: inout Hasher) {
hasher.combine(val)
}
}
class Solution {
func lcaDeepestLeaves(_ root: TreeNode?) -> TreeNode? {
guard let root = root else { return nil }
var queue = [root]
var path = [root : [root]]
var level = 0
while queue.isEmpty == false {
level += 1
var size = queue.count
while size > 0 {
size -= 1
let node = queue.removeFirst()
let parent = path[node, default: [node]]
if let left = node.left {
queue.append(left)
path[left] = parent + [left]
}
if let right = node.right {
queue.append(right)
path[right] = parent + [right]
}
}
}
let filteredPaths = (path.filter{ $0.value.count == level }).values
// print("\(filteredPaths)")
var index = 0
repeat {
var node: TreeNode? = nil
if (filteredPaths.first?.count) ?? 0 <= index { break }
for p in filteredPaths {
if node == nil {
node = p[index]
} else {
if p[index].val != node!.val {
return p[index - 1]
}
}
}
index += 1
} while true
return filteredPaths.first?[index - 1]
}
} | mit | 48dae2e84650d6b9af48e60fcd00f289 | 29.972973 | 85 | 0.470973 | 4.135379 | false | false | false | false |
xasos/3DSnap | iOS/Taking Photos with the Camera/SecondPictureViewController.swift | 1 | 5045 | import UIKit
import MobileCoreServices
import Alamofire
var image2string : String = String()
class SecondPictureViewController: UIViewController,
UINavigationControllerDelegate, UIImagePickerControllerDelegate {
var imageView : UIImageView?
/* We will use this variable to determine if the viewDidAppear:
method of our view controller is already called or not. If not, we will
display the camera view */
var beenHereBefore = false
var controller: UIImagePickerController?
var count = 0
func imagePickerController(picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [String: AnyObject]){
print("Picker returned successfully")
let mediaType:AnyObject? = info[UIImagePickerControllerMediaType]
if let type:AnyObject = mediaType{
if type is String{
let stringType = type as! String
if stringType == kUTTypeMovie as String{
let urlOfVideo = info[UIImagePickerControllerMediaURL] as? NSURL
if let url = urlOfVideo{
print("Video URL = \(url)")
}
}
else if stringType == kUTTypeImage as String{
/* Let's get the metadata. This is only for images. Not videos */
let metadata = info[UIImagePickerControllerMediaMetadata]
as? NSDictionary
if let theMetaData = metadata{
let image = info[UIImagePickerControllerOriginalImage]
as? UIImage
if let theImage = image{
// print("Image Metadata = \(theMetaData)")
// print("Image = \(theImage)")
var imageData = UIImageJPEGRepresentation(theImage, 0.9)
var base64String = imageData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0)) // encode the image
image2string = base64String
}
}
}
}
}
picker.dismissViewControllerAnimated(true) { () -> Void in
self.performSegueWithIdentifier("sendSnapSegue", sender: nil)
}
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
print("Picker was cancelled")
picker.dismissViewControllerAnimated(true, completion: nil)
}
func isCameraAvailable() -> Bool{
return UIImagePickerController.isSourceTypeAvailable(.Camera)
}
func cameraSupportsMedia(mediaType: String,
sourceType: UIImagePickerControllerSourceType) -> Bool{
let availableMediaTypes =
UIImagePickerController.availableMediaTypesForSourceType(sourceType) as
[String]?
if let types = availableMediaTypes{
for type in types{
if type == mediaType{
return true
}
}
}
return false
}
func doesCameraSupportTakingPhotos() -> Bool{
return cameraSupportsMedia(kUTTypeImage as String, sourceType: .Camera)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if beenHereBefore{
/* Only display the picker once as the viewDidAppear: method gets
called whenever the view of our view controller gets displayed */
return;
} else {
beenHereBefore = true
}
if isCameraAvailable() && doesCameraSupportTakingPhotos(){
controller = UIImagePickerController()
if let theController = controller{
theController.sourceType = .Camera
theController.delegate = self
print("image string: \(image1string)")
let overlayView = imageView
overlayView!.frame = CGRect(x: 0, y: 40, width: 350, height: 450)
overlayView!.backgroundColor = UIColor.clearColor().colorWithAlphaComponent(0.2)
overlayView?.alpha = 0.5
theController.cameraOverlayView = overlayView
theController.mediaTypes = [kUTTypeImage as String]
theController.allowsEditing = true
theController.delegate = self
presentViewController(theController, animated: true, completion: nil)
}
} else {
print("Camera is not available")
}
}
}
| mit | e445420e297180fac7ef2e5d080167c6 | 37.51145 | 154 | 0.535778 | 6.682119 | false | false | false | false |
pisarm/Gojira | Carthage/Checkouts/Bond/Bond/Extensions/OSX/NSTableView+Bond.swift | 7 | 5267 | //
// The MIT License (MIT)
//
// Copyright (c) 2015 Michail Pishchagin (@mblsha)
//
// 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
public protocol BNDTableViewDelegate {
typealias Element
func createCell(row: Int, array: ObservableArray<Element>, tableView: NSTableView) -> NSTableCellView
}
class BNDTableViewDataSource<DelegateType: BNDTableViewDelegate>: NSObject, NSTableViewDataSource, NSTableViewDelegate {
private let array: ObservableArray<DelegateType.Element>
private weak var tableView: NSTableView!
private var delegate: DelegateType?
private init(array: ObservableArray<DelegateType.Element>, tableView: NSTableView, delegate: DelegateType) {
self.tableView = tableView
self.delegate = delegate
self.array = array
super.init()
tableView.setDataSource(self)
tableView.setDelegate(self)
tableView.reloadData()
array.observeNew { [weak self] arrayEvent in
guard let unwrappedSelf = self,
tableView = unwrappedSelf.tableView else { return }
switch arrayEvent.operation {
case .Batch(let operations):
tableView.beginUpdates()
for diff in changeSetsFromBatchOperations(operations) {
BNDTableViewDataSource.applyRowUnitChangeSet(diff, tableView: tableView)
}
tableView.endUpdates()
case .Reset:
tableView.reloadData()
default:
tableView.beginUpdates()
BNDTableViewDataSource.applyRowUnitChangeSet(arrayEvent.operation.changeSet(), tableView: tableView)
tableView.endUpdates()
}
}.disposeIn(bnd_bag)
}
private class func applyRowUnitChangeSet(changeSet: ObservableArrayEventChangeSet, tableView: NSTableView) {
switch changeSet {
case .Inserts(let indices):
// FIXME: How to use .Automatic effect a-la UIKit?
tableView.insertRowsAtIndexes(NSIndexSet(set: indices), withAnimation: .EffectNone)
case .Updates(let indices):
tableView.reloadDataForRowIndexes(NSIndexSet(set: indices), columnIndexes: NSIndexSet())
case .Deletes(let indices):
tableView.removeRowsAtIndexes(NSIndexSet(set: indices), withAnimation: .EffectNone)
}
}
/// MARK - NSTableViewDataSource
@objc func numberOfRowsInTableView(tableView: NSTableView) -> Int {
return array.count
}
/// MARK - NSTableViewDelegate
@objc func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? {
return delegate?.createCell(row, array: array, tableView: tableView)
}
override func forwardingTargetForSelector(aSelector: Selector) -> AnyObject? {
guard let delegate = delegate as? AnyObject
where delegate.respondsToSelector(aSelector) else {
return self
}
return delegate
}
override func respondsToSelector(aSelector: Selector) -> Bool {
guard let delegate = delegate as? AnyObject
where delegate.respondsToSelector(aSelector) else {
return super.respondsToSelector(aSelector)
}
return true
}
}
extension NSTableView {
private struct AssociatedKeys {
static var BondDataSourceKey = "bnd_BondDataSourceKey"
}
}
public extension EventProducerType where EventType: ObservableArrayEventType {
private typealias ElementType = EventType.ObservableArrayEventSequenceType.Generator.Element
public func bindTo<DelegateType: BNDTableViewDelegate where DelegateType.Element == ElementType>(tableView: NSTableView, delegate: DelegateType) -> DisposableType {
let array: ObservableArray<ElementType>
if let downcastedarray = self as? ObservableArray<ElementType> {
array = downcastedarray
} else {
array = self.crystallize()
}
let dataSource = BNDTableViewDataSource<DelegateType>(array: array, tableView: tableView, delegate: delegate)
objc_setAssociatedObject(tableView, &NSTableView.AssociatedKeys.BondDataSourceKey, dataSource, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return BlockDisposable { [weak tableView] in
if let tableView = tableView {
objc_setAssociatedObject(tableView, &NSTableView.AssociatedKeys.BondDataSourceKey, nil, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
}
| mit | cc5931303b28c9f2f05e5eeceb06dd35 | 36.892086 | 166 | 0.742168 | 4.940901 | false | false | false | false |
pvzig/SlackKit | SKCore/Sources/File.swift | 2 | 6968 | //
// File.swift
//
// Copyright © 2017 Peter Zignego. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
public struct File: Equatable {
public let id: String?
public let created: Int?
public let name: String?
public let title: String?
public let mimeType: String?
public let fileType: String?
public let prettyType: String?
public let user: String?
public let mode: String?
public var editable: Bool?
public let isExternal: Bool?
public let externalType: String?
public let size: Int?
public let urlPrivate: String?
public let urlPrivateDownload: String?
public let thumb64: String?
public let thumb80: String?
public let thumb360: String?
public let thumb360gif: String?
public let thumb360w: String?
public let thumb360h: String?
public let thumb480: String?
public let thumb480gif: String?
public let thumb480w: String?
public let thumb480h: String?
public let thumb720: String?
public let thumb720gif: String?
public let thumb720w: String?
public let thumb720h: String?
public let thumb960: String?
public let thumb960gif: String?
public let thumb960w: String?
public let thumb960h: String?
public let thumb1024: String?
public let thumb1024gif: String?
public let thumb1024w: String?
public let thumb1024h: String?
public let permalink: String?
public let editLink: String?
public let preview: String?
public let previewHighlight: String?
public let lines: Int?
public let linesMore: Int?
public var isPublic: Bool?
public var publicSharedURL: Bool?
public var channels: [String]?
public var groups: [String]?
public var ims: [String]?
public let initialComment: Comment?
public var stars: Int?
public var isStarred: Bool?
public var pinnedTo: [String]?
public var comments = [String: Comment]()
public var reactions = [Reaction]()
//swiftlint:disable function_body_length
public init(file: [String: Any]?) {
id = file?["id"] as? String
created = file?["created"] as? Int
name = file?["name"] as? String
title = file?["title"] as? String
mimeType = file?["mimetype"] as? String
fileType = file?["filetype"] as? String
prettyType = file?["pretty_type"] as? String
user = file?["user"] as? String
mode = file?["mode"] as? String
editable = file?["editable"] as? Bool
isExternal = file?["is_external"] as? Bool
externalType = file?["external_type"] as? String
size = file?["size"] as? Int
urlPrivate = file?["url_private"] as? String
urlPrivateDownload = file?["url_private_download"] as? String
thumb64 = file?["thumb_64"] as? String
thumb80 = file?["thumb_80"] as? String
thumb360 = file?["thumb_360"] as? String
thumb360gif = file?["thumb_360_gif"] as? String
thumb360w = file?["thumb_360_w"] as? String
thumb360h = file?["thumb_360_h"] as? String
thumb480 = file?["thumb_480"] as? String
thumb480gif = file?["thumb_480_gif"] as? String
thumb480w = file?["thumb_480_w"] as? String
thumb480h = file?["thumb_480_h"] as? String
thumb720 = file?["thumb_720"] as? String
thumb720gif = file?["thumb_720_gif"] as? String
thumb720w = file?["thumb_720_w"] as? String
thumb720h = file?["thumb_720_h"] as? String
thumb960 = file?["thumb_960"] as? String
thumb960gif = file?["thumb_960_gif"] as? String
thumb960w = file?["thumb_960_w"] as? String
thumb960h = file?["thumb_960_h"] as? String
thumb1024 = file?["thumb_1024"] as? String
thumb1024gif = file?["thumb_1024_gif"] as? String
thumb1024w = file?["thumb_1024_w"] as? String
thumb1024h = file?["thumb_1024_h"] as? String
permalink = file?["permalink"] as? String
editLink = file?["edit_link"] as? String
preview = file?["preview"] as? String
previewHighlight = file?["preview_highlight"] as? String
lines = file?["lines"] as? Int
linesMore = file?["lines_more"] as? Int
isPublic = file?["is_public"] as? Bool
publicSharedURL = file?["public_url_shared"] as? Bool
channels = file?["channels"] as? [String]
groups = file?["groups"] as? [String]
ims = file?["ims"] as? [String]
initialComment = Comment(comment: file?["initial_comment"] as? [String: Any])
stars = file?["num_stars"] as? Int
isStarred = file?["is_starred"] as? Bool
pinnedTo = file?["pinned_to"] as? [String]
reactions = Reaction.reactionsFromArray(file?["reactions"] as? [[String: Any]])
}
public init(id: String?) {
self.id = id
created = nil
name = nil
title = nil
mimeType = nil
fileType = nil
prettyType = nil
user = nil
mode = nil
isExternal = nil
externalType = nil
size = nil
urlPrivate = nil
urlPrivateDownload = nil
thumb64 = nil
thumb80 = nil
thumb360 = nil
thumb360gif = nil
thumb360w = nil
thumb360h = nil
thumb480 = nil
thumb480gif = nil
thumb480w = nil
thumb480h = nil
thumb720 = nil
thumb720gif = nil
thumb720w = nil
thumb720h = nil
thumb960 = nil
thumb960gif = nil
thumb960w = nil
thumb960h = nil
thumb1024 = nil
thumb1024gif = nil
thumb1024w = nil
thumb1024h = nil
permalink = nil
editLink = nil
preview = nil
previewHighlight = nil
lines = nil
linesMore = nil
initialComment = nil
}
public static func == (lhs: File, rhs: File) -> Bool {
return lhs.id == rhs.id
}
}
| mit | 8126057469da2b15e684c2abd5c55f3b | 36.456989 | 87 | 0.626812 | 4.110324 | false | false | false | false |
piars777/TheMovieDatabaseSwiftWrapper | Sources/Models/SearchMDB.swift | 1 | 5349 | //
// SearchMDB.swift
// TMDBSwift
//
// Created by piars777 on 26/05/2016.
// Copyright © 2016 George. All rights reserved.
//
//TODO: Search/multi
import Foundation
public struct SearchMDB{
///Search for companies by name.
public static func company(api_key: String!, query: String, page: Int?, completion: (clientReturn: ClientReturn, company: [parent_companymdb]? ) -> ()) -> (){
Client.Search("company", api_key: api_key, query: query, page: page, language: nil, include_adult: nil, year: nil, primary_release_year: nil, search_type: nil, first_air_date_year: nil){
apiReturn in
var company = [parent_companymdb]()
if apiReturn.error == nil{
if(apiReturn.json!["results"].count > 0){
company = parent_companymdb.initialize(json: apiReturn.json!["results"])
}
}
completion(clientReturn: apiReturn, company: company)
}
}
///Search for collections by name. Overview and collectionItems will return nil
public static func collection(api_key: String!, query: String, page: Int?, language: String?, completion: (clientReturn: ClientReturn, collection: [CollectionMDB]? ) -> ()) -> (){
Client.Search("collection", api_key: api_key, query: query, page: page, language: language, include_adult: nil, year: nil, primary_release_year: nil, search_type: nil, first_air_date_year: nil){
apiReturn in
var collection = [CollectionMDB]()
if apiReturn.error == nil{
if(apiReturn.json!["results"].count > 0){
collection = CollectionMDB.initialize(json: apiReturn.json!["results"])
}
}
completion(clientReturn: apiReturn, collection: collection)
}
}
///Search for keywords by name.
public static func keyword(api_key: String!, query: String, page: Int?, completion: (clientReturn: ClientReturn, keyword: [KeywordsMDB]? ) -> ()) -> (){
Client.Search("keyword", api_key: api_key, query: query, page: page, language: nil, include_adult: nil, year: nil, primary_release_year: nil, search_type: nil, first_air_date_year: nil){
apiReturn in
var keyword = [KeywordsMDB]()
if apiReturn.error == nil{
if(apiReturn.json!["results"].count > 0){
keyword = KeywordsMDB.initialize(json: apiReturn.json!["results"])
}
}
completion(clientReturn: apiReturn, keyword: keyword)
}
}
///Search for lists by name and description.
public static func list(api_key: String!, query: String, page: Int?, include_adult: Bool?, completion: (clientReturn: ClientReturn, list: [ListsMDB]? ) -> ()) -> (){
Client.Search("list", api_key: api_key, query: query, page: page, language: nil, include_adult: include_adult, year: nil, primary_release_year: nil, search_type: nil, first_air_date_year: nil){
apiReturn in
var list = [ListsMDB]()
if apiReturn.error == nil{
if(apiReturn.json!["results"].count > 0){
list = ListsMDB.initialize(json: apiReturn.json!["results"])
}
}
completion(clientReturn: apiReturn, list: list)
}
}
///Search for movies by title.
public static func movie(api_key: String!, query: String, language: String?, page: Int?, includeAdult: Bool?, year: Int?, primaryReleaseYear: Int?, completion: (clientReturn: ClientReturn, movie: [MovieMDB]?) -> ()) -> (){
Client.Search("movie", api_key: api_key, query: query, page: page, language: language, include_adult: includeAdult, year: year, primary_release_year: primaryReleaseYear, search_type: nil, first_air_date_year: nil) { apiReturn in
var movie = [MovieMDB]?()
if(apiReturn.error == nil){
if(apiReturn.json!["results"].count > 0){
movie = MovieMDB.initialize(json: apiReturn.json!["results"])
}
}
completion(clientReturn: apiReturn, movie: movie)
}
}
///Search for people by name.
public static func person(api_key: String!, query: String, page: Int?, includeAdult: Bool?, completion: (clientReturn: ClientReturn, person: [PersonResults]?) -> ()) -> (){
Client.Search("person", api_key: api_key, query: query, page: page, language: nil, include_adult: includeAdult, year: nil, primary_release_year: nil, search_type: nil, first_air_date_year: nil) { apiReturn in
var person = [PersonResults]?()
if(apiReturn.error == nil){
if(apiReturn.json!["results"].count > 0){
person = PersonResults.initialize(json: apiReturn.json!["results"])
}
}
completion(clientReturn: apiReturn, person: person)
}
}
///Search for TV shows by title.
public static func tv(api_key: String!, query: String, page: Int?, language: String?, first_air_date_year: String?, completion: (clientReturn: ClientReturn, tvShows: [TVMDB]?) -> ()) -> (){
Client.Search("tv", api_key: api_key, query: query, page: page, language: language, include_adult: nil, year: nil, primary_release_year: nil, search_type: nil, first_air_date_year: first_air_date_year) { apiReturn in
var person = [TVMDB]?()
if(apiReturn.error == nil){
if(apiReturn.json!["results"].count > 0){
person = TVMDB.initialize(json: apiReturn.json!["results"])
}
}
completion(clientReturn: apiReturn, tvShows: person)
}
}
} | mit | 5b1f9dcaaed72c4afe9fa375a8474b90 | 42.487805 | 232 | 0.641361 | 3.929464 | false | false | false | false |
Sweefties/SwiftyPageController | SwiftyPageController/Classes/SwiftyPageController.swift | 1 | 19373 | //
// ViewController.swift
// ContainerControllerTest
//
// Created by Alexander on 8/1/17.
// Copyright © 2017 CryptoTicker. All rights reserved.
//
import UIKit
public protocol SwiftyPageControllerDelegate: class {
func swiftyPageController(_ controller: SwiftyPageController, willMoveToController toController: UIViewController)
func swiftyPageController(_ controller: SwiftyPageController, didMoveToController toController: UIViewController)
func swiftyPageController(_ controller: SwiftyPageController, alongSideTransitionToController toController: UIViewController)
}
public protocol SwiftyPageControllerAnimatorProtocol {
var animationDuration: TimeInterval { get }
var animationProgress: Float { get set }
var animationSpeed: Float { get set }
func setupAnimation(fromController: UIViewController, toController: UIViewController, panGesture: UIPanGestureRecognizer, animationDirection: SwiftyPageController.AnimationDirection)
func didFinishAnimation(fromController: UIViewController, toController: UIViewController)
}
extension SwiftyPageControllerAnimatorProtocol {
public var animationDuration: TimeInterval {
return 1.0
}
}
open class SwiftyPageController: UIViewController {
// MARK: - Types
public enum AnimatorType {
case `default`
case parallax
case custom(SwiftyPageControllerAnimatorProtocol)
var controller: SwiftyPageControllerAnimatorProtocol {
get {
switch self {
case .`default`:
return AnimatorControllers.default
case .parallax:
return AnimatorControllers.parallax
case .custom(let controller):
if AnimatorControllers.custom == nil {
AnimatorControllers.custom = controller
}
return AnimatorControllers.custom!
}
}
set {
switch self {
case .`default`:
AnimatorControllers.default = newValue as! SwiftyPageControllerAnimatorDefault
case .parallax:
AnimatorControllers.parallax = newValue as! SwiftyPageControllerAnimatorParallax
case .custom(_):
AnimatorControllers.custom = newValue
}
}
}
}
public enum AnimationDirection {
case left
case right
}
// MARK: - Variables
public weak var delegate: SwiftyPageControllerDelegate?
public private(set) var selectedIndex: Int?
public var panGesture: UIPanGestureRecognizer!
public var isEnabledAnimation = true
public var animator: AnimatorType = .default
public var containerPaddings: UIEdgeInsets? {
didSet {
topContainerConstraint.constant = containerPaddings?.top ?? 0
bottompContainerConstraint.constant = -(containerPaddings?.bottom ?? 0.0)
leadingContainerConstraint.constant = containerPaddings?.left ?? 0
trailingContainerConstraint.constant = -(containerPaddings?.right ?? 0.0)
view.setNeedsLayout()
}
}
public var selectedController: UIViewController {
return viewControllers[selectedIndex ?? 0]
}
public var containerInsets: UIEdgeInsets? {
didSet {
for viewController in viewControllers {
setupContentInsets(in: viewController)
}
}
}
public var viewControllers: [UIViewController] = [] {
willSet {
for viewController in viewControllers {
if (viewController.viewIfLoaded != nil) {
viewController.view.removeFromSuperview()
}
viewController.removeFromParentViewController()
}
}
didSet {
if viewIfLoaded != nil {
selectController(atIndex: viewControllers.index(of: selectedController)!, animated: false)
}
}
}
fileprivate var nextIndex: Int?
fileprivate var isAnimating = false
fileprivate var previousTopLayoutGuideLength: CGFloat!
fileprivate enum AnimatorControllers {
static var `default` = SwiftyPageControllerAnimatorDefault()
static var parallax = SwiftyPageControllerAnimatorParallax()
static var custom: SwiftyPageControllerAnimatorProtocol?
}
// container view
fileprivate var containerView = UIView(frame: CGRect.zero)
fileprivate var leadingContainerConstraint: NSLayoutConstraint!
fileprivate var trailingContainerConstraint: NSLayoutConstraint!
fileprivate var topContainerConstraint: NSLayoutConstraint!
fileprivate var bottompContainerConstraint: NSLayoutConstraint!
// interactive
fileprivate var timerForInteractiveTransition: Timer?
fileprivate var interactiveTransitionInProgress = false
fileprivate var toControllerInteractive: UIViewController?
fileprivate var fromControllerInteractive: UIViewController?
fileprivate var animationDirectionInteractive: AnimationDirection!
fileprivate var willFinishAnimationTransition = true
fileprivate var timerVelocity = 1.0
// MARK: - Life Cycle
override open func viewDidLoad() {
super.viewDidLoad()
setupController()
}
open override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
setupContentInsets(in: selectedController)
}
// MARK: - Setup
fileprivate func setupController() {
// setup pan gesture
panGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePanAction(_:)))
view.addGestureRecognizer(panGesture)
// setup container view
containerView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(containerView)
leadingContainerConstraint = containerView.leadingAnchor.constraint(equalTo: view.leadingAnchor)
leadingContainerConstraint.isActive = true
trailingContainerConstraint = containerView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
trailingContainerConstraint.isActive = true
topContainerConstraint = containerView.topAnchor.constraint(equalTo: view.topAnchor)
topContainerConstraint.isActive = true
bottompContainerConstraint = containerView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
bottompContainerConstraint.isActive = true
view.layoutIfNeeded()
// select controller
selectController(atIndex: selectedIndex ?? 0)
// assignment variable
previousTopLayoutGuideLength = topLayoutGuide.length
}
fileprivate func setupContentInsets(in controller: UIViewController) {
if controller.viewIfLoaded != nil {
if let scrollView = controller.view.subviews.first as? UIScrollView {
customAdjustScrollViewInsets(in: scrollView, isAutomaticallyAdjustsScrollViewInsets: controller.automaticallyAdjustsScrollViewInsets)
}
if let scrollView = controller.view as? UIScrollView {
customAdjustScrollViewInsets(in: scrollView, isAutomaticallyAdjustsScrollViewInsets: controller.automaticallyAdjustsScrollViewInsets)
}
}
}
// MARK: - Actions
fileprivate func customAdjustScrollViewInsets(in scrollView: UIScrollView, isAutomaticallyAdjustsScrollViewInsets: Bool) {
if let containerInsets = containerInsets {
scrollView.contentInset = containerInsets
scrollView.scrollIndicatorInsets = scrollView.contentInset
} else if isAutomaticallyAdjustsScrollViewInsets {
scrollView.contentInset = UIEdgeInsets(top: topLayoutGuide.length, left: 0.0, bottom: bottomLayoutGuide.length, right: 0.0)
scrollView.scrollIndicatorInsets = scrollView.contentInset
}
// restore content offset
if abs(scrollView.contentOffset.y) == topLayoutGuide.length {
previousTopLayoutGuideLength = topLayoutGuide.length
}
scrollView.contentOffset.y += previousTopLayoutGuideLength - topLayoutGuide.length
previousTopLayoutGuideLength = topLayoutGuide.length
}
fileprivate func transition(fromController: UIViewController, toController: UIViewController, animationDirection: AnimationDirection) {
if fromController == toController {
return
}
// setup frame
toController.view.frame = containerView.bounds
containerView.addSubview(toController.view)
// setup insets
setupContentInsets(in: toController)
// setup animation
animator.controller.setupAnimation(fromController: fromController, toController: toController, panGesture: panGesture, animationDirection: animationDirection)
// call delegate 'willMoveToController' method
delegate?.swiftyPageController(self, willMoveToController: toController)
// assignment variables
fromControllerInteractive = fromController
toControllerInteractive = toController
animationDirectionInteractive = animationDirection
// handle end of transition in case no pan gesture
if panGesture.state != .changed {
willFinishAnimationTransition = true
DispatchQueue.main.asyncAfter(deadline: .now() + animator.controller.animationDuration / Double(animator.controller.animationSpeed), execute: {
self.finishTransition(isCancelled: false)
})
}
}
fileprivate func finishTransition(isCancelled: Bool) {
if let fromController = fromControllerInteractive, let toController = toControllerInteractive {
// drop timer
timerForInteractiveTransition?.invalidate()
timerForInteractiveTransition = nil
// call delegate 'didMoveToController' method
delegate?.swiftyPageController(self, didMoveToController: isCancelled ? fromController : toController)
// remove toController from hierarchy
if isCancelled {
toController.view.removeFromSuperview()
toController.removeFromParentViewController()
} else {
fromController.didMove(toParentViewController: nil)
fromController.view.removeFromSuperview()
fromController.removeFromParentViewController()
// present toController
toController.didMove(toParentViewController: self)
}
// change selectedIndex
selectedIndex = viewControllers.index(of: isCancelled ? fromController : toController)!
// clear variables
isAnimating = false
toControllerInteractive = nil
fromControllerInteractive = nil
animator.controller.animationProgress = 0.0
// call delegate 'didFinishAnimation' method
animator.controller.didFinishAnimation(fromController: fromController, toController: toController)
// logic for transition between child view controllers
if let nextIndex = nextIndex {
if viewControllers[nextIndex] == (isCancelled ? fromController : toController) {
self.nextIndex = nil
} else {
transitionToIndex(index: nextIndex)
}
}
}
}
fileprivate func startTimerForInteractiveTransition() {
isAnimating = true
let timeInterval = 0.001
if willFinishAnimationTransition {
toControllerInteractive?.view.layer.position.x = UIScreen.main.bounds.width / 2.0
} else {
toControllerInteractive?.view.layer.position.x = animationDirectionInteractive == .left ? containerView.bounds.width * 2.0 : -containerView.bounds.width / 2.0
}
timerForInteractiveTransition = Timer.scheduledTimer(timeInterval: timeInterval / timerVelocity, target: self, selector: #selector(finishAnimationTransition), userInfo: nil, repeats: true)
}
func finishAnimationTransition() {
if let fromController = fromControllerInteractive, let toController = toControllerInteractive {
let timeOffset: Double = Double(animator.controller.animationProgress) * Double(animator.controller.animationDuration)
let delta: Float = 0.002
if willFinishAnimationTransition {
animator.controller.animationProgress += delta
} else {
animator.controller.animationProgress -= delta
}
toController.view.layer.timeOffset = CFTimeInterval(timeOffset)
fromController.view.layer.timeOffset = CFTimeInterval(timeOffset)
if animator.controller.animationProgress >= 1.0 {
finishTransition(isCancelled: false)
} else if animator.controller.animationProgress <= 0.0 {
finishTransition(isCancelled: true)
}
}
}
fileprivate func transitionToIndex(index: Int) {
if !isViewLoaded {
return
}
self.delegate?.swiftyPageController(self, willMoveToController: viewControllers[index])
let newController = viewControllers[index]
let direction: AnimationDirection = index - selectedIndex! > 0 ? .left : .right
transition(fromController: viewControllers[selectedIndex!], toController: newController, animationDirection: direction)
}
fileprivate func selectController(atIndex index: Int) {
selectedIndex = index
if !isViewLoaded {
return
}
// setup first controller
let controller = viewControllers[index]
// setup frame
controller.view.frame = containerView.bounds
// setup insets
setupContentInsets(in: controller)
// call delegate 'willMoveToController' method
delegate?.swiftyPageController(self, willMoveToController: controller)
// show controller
containerView.addSubview(controller.view)
controller.didMove(toParentViewController: self)
// call delegate 'didMoveToController' methode
self.delegate?.swiftyPageController(self, didMoveToController: controller)
}
public func selectController(atIndex index: Int, animated: Bool) {
assert(viewControllers.count != 0, "Array 'viewControllers' count couldn't be 0")
// add child view controller if it hasn't been added
if !childViewControllers.contains(viewControllers[index]) {
addChildViewController(viewControllers[index])
}
// select controller
if selectedIndex == nil {
selectController(atIndex: index)
} else {
if animated && isEnabledAnimation {
if isAnimating || interactiveTransitionInProgress {
nextIndex = index
} else {
transitionToIndex(index: index)
}
} else {
selectController(atIndex: index)
}
}
}
func handlePanAction(_ sender: UIPanGestureRecognizer) {
let translation = sender.translation(in: view)
switch sender.state {
case .changed:
if isAnimating {
return
}
// select controller
if !interactiveTransitionInProgress {
if translation.x > 0 {
// select previous controller
let index = selectedIndex! - 1
if index >= 0 {
selectController(atIndex: index, animated: isEnabledAnimation)
interactiveTransitionInProgress = true
}
} else {
// select next controller
let index = selectedIndex! + 1
if index <= viewControllers.count - 1 {
selectController(atIndex: index, animated: isEnabledAnimation)
interactiveTransitionInProgress = true
}
}
}
// cancel transition in case of changing direction
if (translation.x > 0 && animationDirectionInteractive != .right) || (translation.x < 0 && animationDirectionInteractive != .left) {
interactiveTransitionInProgress = false
finishTransition(isCancelled: true)
}
// set layer position
toControllerInteractive?.view.layer.position.x = translation.x > 0 ? containerView.bounds.width * 2.0 : -containerView.bounds.width / 2.0
// interactive animation
animator.controller.animationProgress = fmin(fmax(Float(abs(translation.x) / containerView.bounds.width), 0.0), 2.0)
willFinishAnimationTransition = animator.controller.animationProgress > 0.4
let timeOffset = animator.controller.animationProgress * Float(animator.controller.animationDuration)
toControllerInteractive?.view.layer.timeOffset = CFTimeInterval(timeOffset)
fromControllerInteractive?.view.layer.timeOffset = CFTimeInterval(timeOffset)
case .cancelled, .ended:
interactiveTransitionInProgress = false
if isAnimating {
return
}
// finish animation relatively velocity
let velocity = sender.velocity(in: view)
if animationDirectionInteractive == .left ? (velocity.x > 0) : (velocity.x < 0) {
timerVelocity = 1.0
willFinishAnimationTransition = false
} else {
let velocityTreshold: CGFloat = 32.0
if abs(velocity.x) > velocityTreshold {
timerVelocity = 2.0
willFinishAnimationTransition = true
} else {
timerVelocity = 1.0
}
}
if fromControllerInteractive != nil, toControllerInteractive != nil {
startTimerForInteractiveTransition()
}
default:
break
}
}
func swipeAction(direction: AnimationDirection) {
if direction == .right {
let index = selectedIndex! - 1
if index >= 0 {
selectController(atIndex: index, animated: isEnabledAnimation)
}
} else {
let index = selectedIndex! + 1
if index <= viewControllers.count - 1 {
selectController(atIndex: index, animated: isEnabledAnimation)
}
}
}
}
| mit | 2c56529b0cfef5bc9c3060eb8e1c41a2 | 38.860082 | 196 | 0.6274 | 6.255086 | false | false | false | false |
dotfold/tic-tac-toe | TicTacToe/Board.swift | 1 | 647 | //
// Board.swift
// TicTacToe
//
// Created by James McNamee on 3/4/17.
// Copyright © 2017 James McNamee. All rights reserved.
//
import UIKit
import Foundation
let BOARD_CELL_COUNT = 9
struct Position {
var x: Int
var y: Int
}
struct Cell {
var owner: Player?
var position: Position
var uiElement: UIButton
init (uiElement: UIButton, position: Position) {
self.uiElement = uiElement
self.position = position
}
init (owner: Player, uiElement: UIButton, position: Position) {
self.owner = owner
self.uiElement = uiElement
self.position = position
}
}
| mit | a14e1ab37fbd462f4b6d5771f6682848 | 18 | 67 | 0.630031 | 3.712644 | false | false | false | false |
ethanneff/organize | Organize/Modal+Reminder.swift | 1 | 15145 | //
// Modal+Reminder.swift
// Organize
//
// Created by Ethan Neff on 6/7/16.
// Copyright © 2016 Ethan Neff. All rights reserved.
//
import UIKit
class ModalReminder: Modal {
// MARK: - properties
var reminder: Reminder? {
didSet {
updateSelected()
}
}
private var header: UILabel!
private var buttonOne: UIButton!
private var buttonTwo: UIButton!
private var buttonThree: UIButton!
private var buttonFour: UIButton!
private var buttonFive: UIButton!
private var buttonSix: UIButton!
private var buttonSeven: UIButton!
private var buttonEight: UIButton!
private var buttonNine: UIButton!
private var topSeparatorOne: UIView!
private var topSeparatorTwo: UIView!
private var topSeparatorThree: UIView!
private var midSeparatorOne: UIView!
private var midSeparatorTwo: UIView!
private let buttonHeight: CGFloat = 75
private let buttonMultiplier: CGFloat = 0.18
private let buttonRows: CGFloat = 3
private let buttonColumns: CGFloat = 3
private let buttonTitleRows: Int = 2
private let buttonTitleFontSize: CGFloat = 13
private let modalTitleText: String = "Pick a reminder"
private let modalHeightPadding: CGFloat = 60
private let modalWidthPadding: CGFloat = 100
enum OutputKeys: String {
case ReminderType
}
// MARK: - init
override init() {
super.init()
createViews()
createConstraints()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init coder not implemented")
}
// MARK: - deinit
deinit {
}
// MARK: - create
private func createViews() {
header = createTitle(title: modalTitleText)
buttonOne = createButton(reminderType: ReminderType.Later)
buttonTwo = createButton(reminderType: ReminderType.Evening)
buttonThree = createButton(reminderType: ReminderType.Tomorrow)
buttonFour = createButton(reminderType: ReminderType.Weekend)
buttonFive = createButton(reminderType: ReminderType.Week)
buttonSix = createButton(reminderType: ReminderType.Month)
buttonSeven = createButton(reminderType: ReminderType.Someday)
buttonEight = createButton(reminderType: ReminderType.None)
buttonNine = createButton(reminderType: ReminderType.Date)
topSeparatorOne = createSeparator()
topSeparatorTwo = createSeparator()
topSeparatorThree = createSeparator()
midSeparatorOne = createSeparator()
midSeparatorTwo = createSeparator()
modal.addSubview(header)
modal.addSubview(buttonOne)
modal.addSubview(buttonTwo)
modal.addSubview(buttonThree)
modal.addSubview(buttonFour)
modal.addSubview(buttonFive)
modal.addSubview(buttonSix)
modal.addSubview(buttonSeven)
modal.addSubview(buttonEight)
modal.addSubview(buttonNine)
modal.addSubview(topSeparatorOne)
modal.addSubview(topSeparatorTwo)
modal.addSubview(topSeparatorThree)
modal.addSubview(midSeparatorOne)
modal.addSubview(midSeparatorTwo)
}
private func createConstraints() {
constraintHeader(header: header)
NSLayoutConstraint.activateConstraints([
NSLayoutConstraint(item: modal, attribute: .CenterX, relatedBy: .Equal, toItem: view, attribute: .CenterX, multiplier: 1, constant: 0),
NSLayoutConstraint(item: modal, attribute: .CenterY, relatedBy: .Equal, toItem: view, attribute: .CenterY, multiplier: 1, constant: 0),
NSLayoutConstraint(item: modal, attribute: .Width, relatedBy: .Equal, toItem: view, attribute: .Width, multiplier: buttonMultiplier*buttonColumns, constant: modalWidthPadding),
NSLayoutConstraint(item: modal, attribute: .Height, relatedBy: .Equal, toItem: view, attribute: .Height, multiplier: buttonMultiplier*buttonRows, constant: modalHeightPadding),
])
NSLayoutConstraint.activateConstraints([
NSLayoutConstraint(item: buttonOne, attribute: .Leading, relatedBy: .Equal, toItem: modal, attribute: .Leading, multiplier: 1, constant: 0),
NSLayoutConstraint(item: buttonOne, attribute: .Bottom, relatedBy: .Equal, toItem: topSeparatorTwo, attribute: .Bottom, multiplier: 1, constant: 0),
NSLayoutConstraint(item: buttonOne, attribute: .Height, relatedBy: .Equal, toItem: view, attribute: .Height, multiplier: buttonMultiplier, constant: 0),
])
NSLayoutConstraint.activateConstraints([
NSLayoutConstraint(item: buttonTwo, attribute: .Leading, relatedBy: .Equal, toItem: midSeparatorOne, attribute: .Trailing, multiplier: 1, constant: 0),
NSLayoutConstraint(item: buttonTwo, attribute: .Bottom, relatedBy: .Equal, toItem: topSeparatorTwo, attribute: .Bottom, multiplier: 1, constant: 0),
NSLayoutConstraint(item: buttonTwo, attribute: .Width, relatedBy: .Equal, toItem: buttonOne, attribute: .Width, multiplier: 1, constant: 0),
NSLayoutConstraint(item: buttonTwo, attribute: .Height, relatedBy: .Equal, toItem: view, attribute: .Height, multiplier: buttonMultiplier, constant: 0),
])
NSLayoutConstraint.activateConstraints([
NSLayoutConstraint(item: buttonThree, attribute: .Trailing, relatedBy: .Equal, toItem: modal, attribute: .Trailing, multiplier: 1, constant: 0),
NSLayoutConstraint(item: buttonThree, attribute: .Leading, relatedBy: .Equal, toItem: midSeparatorTwo, attribute: .Trailing, multiplier: 1, constant: 0),
NSLayoutConstraint(item: buttonThree, attribute: .Bottom, relatedBy: .Equal, toItem: topSeparatorTwo, attribute: .Bottom, multiplier: 1, constant: 0),
NSLayoutConstraint(item: buttonThree, attribute: .Width, relatedBy: .Equal, toItem: buttonOne, attribute: .Width, multiplier: 1, constant: 0),
NSLayoutConstraint(item: buttonThree, attribute: .Height, relatedBy: .Equal, toItem: view, attribute: .Height, multiplier: buttonMultiplier, constant: 0),
])
NSLayoutConstraint.activateConstraints([
NSLayoutConstraint(item: buttonFour, attribute: .Leading, relatedBy: .Equal, toItem: modal, attribute: .Leading, multiplier: 1, constant: 0),
NSLayoutConstraint(item: buttonFour, attribute: .Bottom, relatedBy: .Equal, toItem: topSeparatorThree, attribute: .Bottom, multiplier: 1, constant: 0),
NSLayoutConstraint(item: buttonFour, attribute: .Height, relatedBy: .Equal, toItem: view, attribute: .Height, multiplier: buttonMultiplier, constant: 0),
])
NSLayoutConstraint.activateConstraints([
NSLayoutConstraint(item: buttonFive, attribute: .Leading, relatedBy: .Equal, toItem: midSeparatorOne, attribute: .Trailing, multiplier: 1, constant: 0),
NSLayoutConstraint(item: buttonFive, attribute: .Bottom, relatedBy: .Equal, toItem: topSeparatorThree, attribute: .Bottom, multiplier: 1, constant: 0),
NSLayoutConstraint(item: buttonFive, attribute: .Width, relatedBy: .Equal, toItem: buttonFour, attribute: .Width, multiplier: 1, constant: 0),
NSLayoutConstraint(item: buttonFive, attribute: .Height, relatedBy: .Equal, toItem: view, attribute: .Height, multiplier: buttonMultiplier, constant: 0),
])
NSLayoutConstraint.activateConstraints([
NSLayoutConstraint(item: buttonSix, attribute: .Trailing, relatedBy: .Equal, toItem: modal, attribute: .Trailing, multiplier: 1, constant: 0),
NSLayoutConstraint(item: buttonSix, attribute: .Leading, relatedBy: .Equal, toItem: midSeparatorTwo, attribute: .Trailing, multiplier: 1, constant: 0),
NSLayoutConstraint(item: buttonSix, attribute: .Bottom, relatedBy: .Equal, toItem: topSeparatorThree, attribute: .Bottom, multiplier: 1, constant: 0),
NSLayoutConstraint(item: buttonSix, attribute: .Width, relatedBy: .Equal, toItem: buttonFour, attribute: .Width, multiplier: 1, constant: 0),
NSLayoutConstraint(item: buttonSix, attribute: .Height, relatedBy: .Equal, toItem: view, attribute: .Height, multiplier: buttonMultiplier, constant: 0),
])
NSLayoutConstraint.activateConstraints([
NSLayoutConstraint(item: buttonSeven, attribute: .Leading, relatedBy: .Equal, toItem: modal, attribute: .Leading, multiplier: 1, constant: 0),
NSLayoutConstraint(item: buttonSeven, attribute: .Bottom, relatedBy: .Equal, toItem: modal, attribute: .Bottom, multiplier: 1, constant: 0),
NSLayoutConstraint(item: buttonSeven, attribute: .Height, relatedBy: .Equal, toItem: view, attribute: .Height, multiplier: buttonMultiplier, constant: 0),
])
NSLayoutConstraint.activateConstraints([
NSLayoutConstraint(item: buttonEight, attribute: .Leading, relatedBy: .Equal, toItem: midSeparatorOne, attribute: .Trailing, multiplier: 1, constant: 0),
NSLayoutConstraint(item: buttonEight, attribute: .Bottom, relatedBy: .Equal, toItem: modal, attribute: .Bottom, multiplier: 1, constant: 0),
NSLayoutConstraint(item: buttonEight, attribute: .Width, relatedBy: .Equal, toItem: buttonSeven, attribute: .Width, multiplier: 1, constant: 0),
NSLayoutConstraint(item: buttonEight, attribute: .Height, relatedBy: .Equal, toItem: view, attribute: .Height, multiplier: buttonMultiplier, constant: 0),
])
NSLayoutConstraint.activateConstraints([
NSLayoutConstraint(item: buttonNine, attribute: .Trailing, relatedBy: .Equal, toItem: modal, attribute: .Trailing, multiplier: 1, constant: 0),
NSLayoutConstraint(item: buttonNine, attribute: .Leading, relatedBy: .Equal, toItem: midSeparatorTwo, attribute: .Trailing, multiplier: 1, constant: 0),
NSLayoutConstraint(item: buttonNine, attribute: .Bottom, relatedBy: .Equal, toItem: modal, attribute: .Bottom, multiplier: 1, constant: 0),
NSLayoutConstraint(item: buttonNine, attribute: .Width, relatedBy: .Equal, toItem: buttonSeven, attribute: .Width, multiplier: 1, constant: 0),
NSLayoutConstraint(item: buttonNine, attribute: .Height, relatedBy: .Equal, toItem: view, attribute: .Height, multiplier: buttonMultiplier, constant: 0),
])
NSLayoutConstraint.activateConstraints([
NSLayoutConstraint(item: topSeparatorOne, attribute: .Trailing, relatedBy: .Equal, toItem: modal, attribute: .Trailing, multiplier: 1, constant: 0),
NSLayoutConstraint(item: topSeparatorOne, attribute: .Leading, relatedBy: .Equal, toItem: modal, attribute: .Leading, multiplier: 1, constant: 0),
NSLayoutConstraint(item: topSeparatorOne, attribute: .Bottom, relatedBy: .Equal, toItem: buttonOne, attribute: .Top, multiplier: 1, constant: 0),
NSLayoutConstraint(item: topSeparatorOne, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: separatorHeight),
])
NSLayoutConstraint.activateConstraints([
NSLayoutConstraint(item: topSeparatorTwo, attribute: .Trailing, relatedBy: .Equal, toItem: modal, attribute: .Trailing, multiplier: 1, constant: 0),
NSLayoutConstraint(item: topSeparatorTwo, attribute: .Leading, relatedBy: .Equal, toItem: modal, attribute: .Leading, multiplier: 1, constant: 0),
NSLayoutConstraint(item: topSeparatorTwo, attribute: .Bottom, relatedBy: .Equal, toItem: buttonFour, attribute: .Top, multiplier: 1, constant: 0),
NSLayoutConstraint(item: topSeparatorTwo, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: separatorHeight),
])
NSLayoutConstraint.activateConstraints([
NSLayoutConstraint(item: topSeparatorThree, attribute: .Trailing, relatedBy: .Equal, toItem: modal, attribute: .Trailing, multiplier: 1, constant: 0),
NSLayoutConstraint(item: topSeparatorThree, attribute: .Leading, relatedBy: .Equal, toItem: modal, attribute: .Leading, multiplier: 1, constant: 0),
NSLayoutConstraint(item: topSeparatorThree, attribute: .Bottom, relatedBy: .Equal, toItem: buttonSeven, attribute: .Top, multiplier: 1, constant: 0),
NSLayoutConstraint(item: topSeparatorThree, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: separatorHeight),
])
NSLayoutConstraint.activateConstraints([
NSLayoutConstraint(item: midSeparatorOne, attribute: .Leading, relatedBy: .Equal, toItem: buttonSeven, attribute: .Trailing, multiplier: 1, constant: 0),
NSLayoutConstraint(item: midSeparatorOne, attribute: .Bottom, relatedBy: .Equal, toItem: modal, attribute: .Bottom, multiplier: 1, constant: 0),
NSLayoutConstraint(item: midSeparatorOne, attribute: .Top, relatedBy: .Equal, toItem: topSeparatorOne, attribute: .Top, multiplier: 1, constant: 0),
NSLayoutConstraint(item: midSeparatorOne, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: separatorHeight),
])
NSLayoutConstraint.activateConstraints([
NSLayoutConstraint(item: midSeparatorTwo, attribute: .Leading, relatedBy: .Equal, toItem: buttonEight, attribute: .Trailing, multiplier: 1, constant: 0),
NSLayoutConstraint(item: midSeparatorTwo, attribute: .Bottom, relatedBy: .Equal, toItem: modal, attribute: .Bottom, multiplier: 1, constant: 0),
NSLayoutConstraint(item: midSeparatorTwo, attribute: .Top, relatedBy: .Equal, toItem: topSeparatorOne, attribute: .Top, multiplier: 1, constant: 0),
NSLayoutConstraint(item: midSeparatorTwo, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: separatorHeight),
])
}
private func createButton(reminderType reminderType: ReminderType) -> UIButton {
let button = UIButton()
button.tag = reminderType.hashValue
button.setTitle(reminderType.title, forState: .Normal)
button.tintColor = Constant.Color.button
button.setImage(reminderType.imageView(color: Constant.Color.button).image, forState: .Normal)
button.setImage(reminderType.imageView(color: Constant.Color.border).image, forState: .Highlighted)
button.setTitleColor(Constant.Color.button, forState: .Normal)
button.setTitleColor(Constant.Color.border, forState: .Highlighted)
button.titleLabel?.font = reminderType == .None ? .boldSystemFontOfSize(buttonTitleFontSize) : .systemFontOfSize(buttonTitleFontSize)
button.addTarget(self, action: #selector(buttonPressed(_:)), forControlEvents: .TouchUpInside)
button.titleLabel?.textAlignment = .Center
button.titleLabel?.numberOfLines = buttonTitleRows
button.alignImageAndTitleVertically(spacing: 0)
button.translatesAutoresizingMaskIntoConstraints = false
return button
}
private func updateSelected() {
for view in modal.subviews {
if let button = view as? UIButton, type = ReminderType(rawValue: button.tag) {
if reminder?.type == type && reminder?.date.timeIntervalSinceNow > 0 {
button.backgroundColor = Constant.Color.selected
} else {
button.backgroundColor = Constant.Color.background
}
}
}
}
// MARK: - buttons
func buttonPressed(button: UIButton) {
Util.animateButtonPress(button: button)
hide() {
if let completion = self.completion, let type = ReminderType(rawValue: button.tag) {
completion(output: [OutputKeys.ReminderType.rawValue: type.rawValue])
}
}
}
} | mit | ada02ddca5a6b09ce690e2c02b9f08da | 57.25 | 182 | 0.733888 | 4.547748 | false | false | false | false |
kotdark/RAReorderableLayout | RAReorderableLayout-Demo/RAReorderableLayout-Demo/AppDelegate.swift | 1 | 6207 | //
// AppDelegate.swift
// RAReorderableLayout-Demo
//
// Created by Ryo Aoyama on 10/29/14.
// Copyright (c) 2014 Ryo Aoyama. 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.ryo.RAReorderableLayout_Demo" 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("RAReorderableLayout_Demo", 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("RAReorderableLayout_Demo.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 as [NSObject : AnyObject])
// 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()
}
}
}
}
| mit | 821a967070cba3866d3fb391f87fc279 | 54.918919 | 290 | 0.71806 | 5.726015 | false | false | false | false |
chenjiang3/RDVTabBarControllerSwift | Example/RDVTabBarControllerSwift/RDVFirstViewController.swift | 1 | 2374 | //
// RDVFirstViewController.swift
// RDVTabBarControllerSwift
//
// Created by chenjiang on 2017/2/3.
// Copyright © 2017年 CocoaPods. All rights reserved.
//
import UIKit
class RDVFirstViewController: UITableViewController {
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.title = "First"
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.rdv_tabBarItem?.badgeValue = "3"
if let tabBar = self.rdv_tabBarController?.tabBar, tabBar.translucent == true {
let insets = UIEdgeInsets(top: 0, left: 0,
bottom: tabBar.frame.height,
right: 0)
self.tableView.contentInset = insets
self.tableView.scrollIndicatorInsets = insets
}
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
if UIDevice.current.userInterfaceIdiom == .pad {
return .all
} else {
return .portrait
}
}
func configureCell(_ cell: UITableViewCell, forIndexPath indexPath: IndexPath) {
cell.textLabel?.text = "\(self.title!) Controller Cell \(indexPath.row)"
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 30
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "Cell"
if let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) {
configureCell(cell, forIndexPath: indexPath)
return cell
} else {
let cell = UITableViewCell(style: .default, reuseIdentifier: cellIdentifier)
configureCell(cell, forIndexPath: indexPath)
return cell
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
guard let tabBarItem = self.rdv_tabBarItem else {
return
}
tabBarItem.badgeValue = "\(indexPath.row + 1)"
}
}
| mit | e201d00a20ccb50690cfbb9a295bd5bc | 30.613333 | 109 | 0.629692 | 5.233996 | false | false | false | false |
onevcat/CotEditor | CotEditor/Sources/DocumentViewController+TouchBar.swift | 1 | 6333 | //
// DocumentViewController+TouchBar.swift
//
// CotEditor
// https://coteditor.com
//
// Created by 1024jp on 2016-11-16.
//
// ---------------------------------------------------------------------------
//
// © 2016-2021 1024jp
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Cocoa
private extension NSTouchBar.CustomizationIdentifier {
static let documentView = NSTouchBar.CustomizationIdentifier("com.coteditor.CotEditor.touchBar.documentView")
}
extension NSTouchBarItem.Identifier {
static let invisibles = NSTouchBarItem.Identifier("com.coteditor.CotEditor.TouchBarItem.invisibles")
static let indentGuides = NSTouchBarItem.Identifier("com.coteditor.CotEditor.TouchBarItem.indentGuides")
static let wrapLines = NSTouchBarItem.Identifier("com.coteditor.CotEditor.TouchBarItem.wrapLines")
static let share = NSTouchBarItem.Identifier("com.coteditor.CotEditor.TouchBarItem.share")
}
extension DocumentViewController: NSTouchBarDelegate {
// MARK: View Controller Methods
override func makeTouchBar() -> NSTouchBar? {
let touchBar = NSTouchBar()
NSTouchBar.isAutomaticValidationEnabled = true
touchBar.delegate = self
touchBar.customizationIdentifier = .documentView
touchBar.defaultItemIdentifiers = [.otherItemsProxy, .fixedSpaceSmall, .invisibles, .wrapLines, .share]
touchBar.customizationAllowedItemIdentifiers = [.share, .invisibles, .indentGuides, .wrapLines]
return touchBar
}
// MARK: Touch Bar Delegate
func touchBar(_ touchBar: NSTouchBar, makeItemForIdentifier identifier: NSTouchBarItem.Identifier) -> NSTouchBarItem? {
switch identifier {
case .invisibles:
let item = NSCustomTouchBarItem(identifier: identifier)
item.customizationLabel = "Invisibles".localized(comment: "touch bar item")
let image = NSImage(systemSymbolName: "paragraphsign", accessibilityDescription: "Invisibles".localized)!
item.view = NSButton(image: image, target: self, action: #selector(toggleInvisibleCharsViaTouchBar))
return item
case .indentGuides:
let item = NSCustomTouchBarItem(identifier: identifier)
item.customizationLabel = "Indent Guides".localized(comment: "touch bar item")
let image = NSImage(named: "text.indentguides")!
item.view = NSButton(image: image, target: self, action: #selector(toggleIndentGuidesViaTouchBar))
return item
case .wrapLines:
let item = NSCustomTouchBarItem(identifier: identifier)
item.customizationLabel = "Wrap Lines".localized(comment: "touch bar item")
let image = NSImage(named: "text.wrap")!
item.view = NSButton(image: image, target: self, action: #selector(toggleLineWrapViaTouchBar))
return item
case .share:
guard let document = self.document else { return nil }
let item = NSSharingServicePickerTouchBarItem(identifier: identifier)
item.delegate = document
return item
default:
return nil
}
}
/// toggle visibility of invisible characters in text view
@IBAction private func toggleInvisibleCharsViaTouchBar(_ sender: NSButton) {
self.toggleInvisibleChars(sender)
self.validateUserInterfaceForTouchBarEvent()
}
/// toggle visibility of invisible characters in text view
@IBAction private func toggleIndentGuidesViaTouchBar(_ sender: NSButton) {
self.toggleIndentGuides(sender)
self.validateUserInterfaceForTouchBarEvent()
}
/// toggle if lines wrap at window edge
@IBAction private func toggleLineWrapViaTouchBar(_ sender: NSButton) {
self.toggleLineWrap(sender)
self.validateUserInterfaceForTouchBarEvent()
}
// MARK: Private Methods
/// Update UI manually.
///
/// Workaround for the issue where UI doesn't update on a touch bar event. (2017-01 macOS 10.12.2 SDK)
private func validateUserInterfaceForTouchBarEvent() {
self.view.window?.toolbar?.validateVisibleItems()
self.touchBar?.validateVisibleItems()
}
}
extension DocumentViewController: TouchBarItemValidations {
func validateTouchBarItem(_ item: NSTouchBarItem) -> Bool {
guard let button = item.view as? NSButton else { return true }
guard let isEnabled: Bool = {
switch item.identifier {
case .invisibles:
return self.showsInvisibles
case .indentGuides:
return self.showsIndentGuides
case .wrapLines:
return self.wrapsLines
default: return nil
}
}() else { return true }
let color: NSColor? = isEnabled ? nil : .offStateButtonBezelColor
if button.bezelColor != color {
button.bezelColor = color
button.needsDisplay = true
}
return true
}
}
extension NSDocument: NSSharingServicePickerTouchBarItemDelegate {
public func items(for pickerTouchBarItem: NSSharingServicePickerTouchBarItem) -> [Any] {
return [self]
}
}
private extension NSColor {
/// button bezel color for off state
static let offStateButtonBezelColor = NSColor(white: 0.12, alpha: 1)
}
| apache-2.0 | 106cbf9048a761deb55d9133cc8ee7e1 | 32.326316 | 123 | 0.627606 | 5.303183 | false | false | false | false |
iOSWizards/AwesomeMedia | Example/Pods/AwesomeConstants/AwesomeConstants/Classes/Extensions/UIView.swift | 1 | 1434 | //
// UIView+Parallax.swift
// Quests
//
// Created by Evandro Harrison Hoffmann on 4/1/17.
// Copyright © 2017 Mindvalley. All rights reserved.
//
import UIKit
// MARK: - Background effect
extension UIView {
public func clearMotionEffects() {
let motionEffects = self.motionEffects
for motionEffect in motionEffects {
self.removeMotionEffect(motionEffect)
}
}
public func addBackgroundEffect(withMargin margin: Double, inverted: Bool = false) {
//remove motion effects
clearMotionEffects()
// Set vertical effect
let verticalMotionEffect = UIInterpolatingMotionEffect(keyPath: "center.y", type: .tiltAlongVerticalAxis)
verticalMotionEffect.minimumRelativeValue = inverted ? margin : -margin
verticalMotionEffect.maximumRelativeValue = inverted ? -margin : margin
// Set horizontal effect
let horizontalMotionEffect = UIInterpolatingMotionEffect(keyPath: "center.x", type: .tiltAlongHorizontalAxis)
horizontalMotionEffect.minimumRelativeValue = inverted ? margin : -margin
horizontalMotionEffect.maximumRelativeValue = inverted ? -margin : margin
// Create group to combine both
let group = UIMotionEffectGroup()
group.motionEffects = [horizontalMotionEffect, verticalMotionEffect]
// Add both effects to your view
self.addMotionEffect(group)
}
}
| mit | b21a8a1604a95b5e8719f8cb3f01d865 | 31.568182 | 117 | 0.697837 | 5.249084 | false | false | false | false |
SeriousChoice/SCSwift | SCSwift/Utils/SCCollections.swift | 1 | 1300 | //
// SCTableSection.swift
// SCSwift
//
// Created by Nicola Innocenti on 08/01/2022.
// Copyright © 2022 Nicola Innocenti. All rights reserved.
//
import Foundation
public struct SCTableSection {
public var key: String
public var title: String?
public var rows: [SCTableRow]
}
public struct SCTableRow {
public var key: String
public var title: String?
public var subtitle: String?
public var value: String?
public var image: UIImage?
public var accessoryType: UITableViewCell.AccessoryType
public init(key: String, title: String?, subtitle: String?, value: String) {
self.key = key
self.title = title
self.subtitle = subtitle
self.value = value
self.accessoryType = .none
}
public init(key: String, title: String?, value: String?, image: UIImage?, accessoryType: UITableViewCell.AccessoryType) {
self.key = key
self.title = title
self.value = value
self.image = image
self.accessoryType = accessoryType
}
public init(key: String, title: String?, value: String?, accessoryType: UITableViewCell.AccessoryType) {
self.key = key
self.title = title
self.value = value
self.accessoryType = accessoryType
}
}
| mit | f34d30399eeeadd8ca3aacd776763ce7 | 26.638298 | 125 | 0.648191 | 4.418367 | false | false | false | false |
chrisjmendez/swift-exercises | Music/Apple/iTunesQueryAdvanced/iTunesQueryAdvanced/SearchResultsViewController.swift | 1 | 3931 | //
// ViewController.swift
// iTunesQuery
//
// Created by tommy trojan on 5/17/15.
// Copyright (c) 2015 Chris Mendez. All rights reserved.
//
/** ** ** ** ** ** ** ** ** **
Inspired by:
* http://technotif.com/connect-your-apps-to-itunes-search-api/
* http://www.codingexplorer.com/getting-started-uitableview-swift/
*
* Notes:
* In iOS we always want to use dequeueReusableCellWithIdentifier
* in order to get a cell out of memory if one is available, rather
* than creating a new one every time a cell is rendered.
*
*
** ** ** ** ** ** ** ** ** ** **/
import UIKit
class SearchResultsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var tableData = []
let api = APIController()
let kCellIdentifier: String = "SearchResultCell"
@IBOutlet weak var appsTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
api.delegate = self
api.searchItunesFor("stereolab", searchCategory: "music")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableData.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(kCellIdentifier) as UITableViewCell!
if let rowData: NSDictionary = self.tableData[indexPath.row] as? NSDictionary,
// Grab the artworkUrl60 key to get an image URL for the app's thumbnail
urlString = rowData["artworkUrl60"] as? String,
imgURL = NSURL(string: urlString),
// Get the formatted price string for display in the subtitle
formattedPrice = rowData["trackPrice"] as? Double,
// Download an NSData representation of the image at the URL
imgData = NSData(contentsOfURL: imgURL),
// Get the track name
trackName = rowData["trackName"] as? String {
// Get the formatted price string for display in the subtitle
cell.detailTextLabel?.text = formattedPrice.toStringWithDecimalPlaces(2)
// Update the imageView cell to use the downloaded image data
cell.imageView?.image = UIImage(data: imgData)
// Update the textLabel text to use the trackName from the API
cell.textLabel?.text = trackName
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// Get the row data for the selected row
if let rowData = self.tableData[indexPath.row] as? NSDictionary,
// Get the name of the track for this row
name = rowData["trackName"] as? String,
// Get the price of the track on this row
formattedPrice = rowData["trackPrice"] as? Double {
print("formattedPrice:", formattedPrice)
let alert = UIAlertController(title: name, message: formattedPrice.toStringWithDecimalPlaces(2), preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
}
}
extension SearchResultsViewController: APIControllerProtocol{
func didReceiveAPIResults(results: NSArray) {
dispatch_async(dispatch_get_main_queue(), {
self.tableData = results
self.appsTableView!.reloadData()
})
}
}
extension Double {
func toStringWithDecimalPlaces(numberOfDecimalPlaces:Int) -> String {
return String(format:"$%."+numberOfDecimalPlaces.description+"f", self)
}
}
| mit | 02ffbb3fd2d5ec11b3072bae1c70bf9d | 38.707071 | 136 | 0.650725 | 4.901496 | false | false | false | false |
hayashi311/iosdcjp2016app | iOSApp/Pods/URLNavigator/Sources/URLNavigator.swift | 1 | 17961 | // The MIT License (MIT)
//
// Copyright (c) 2016 Suyeol Jeon (xoul.kr)
//
// 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
/// URLNavigator provides an elegant way to navigate through view controllers by URLs. URLs should be mapped by using
/// `URLNavigator.map(_:_:)` function.
///
/// URLNavigator can be used to map URLs with 2 kind of types: `URLNavigable` and `URLOpenHandler`. `URLNavigable` is
/// a type which defines an custom initializer and `URLOpenHandler` is a closure. Both an initializer and a closure
/// have URL and values for its parameters.
///
/// URLs can have
///
/// Here's an example of mapping URLNaviable-conforming class `UserViewController` to URL:
///
/// Navigator.map("myapp://user/<int:id>", UserViewController.self)
/// Navigator.map("http://<path:_>", MyWebViewController.self)
///
/// This URL can be used to push or present the `UserViewController` by providing URLs:
///
/// Navigator.pushURL("myapp://user/123")
/// Navigator.presentURL("http://xoul.kr")
///
/// This is another example of mapping `URLOpenHandler` to URL:
///
/// Navigator.map("myapp://say-hello") { URL, values in
/// print("Hello, world!")
/// return true
/// }
///
/// Use `URLNavigator.openURL()` to execute closures.
///
/// Navigator.openURL("myapp://say-hello") // prints "Hello, world!"
///
/// - Note: Use `UIApplication.openURL()` method to launch other applications or to open URLs in application level.
///
/// - SeeAlso: `URLNavigable`
public class URLNavigator {
/// A closure type which has URL and values for parameters.
public typealias URLOpenHandler = (URL: URLConvertible, values: [String: AnyObject]) -> Bool
/// A dictionary to store URLNaviables by URL patterns.
private(set) var URLMap = [String: URLNavigable.Type]()
/// A dictionary to store URLOpenHandlers by URL patterns.
private(set) var URLOpenHandlers = [String: URLOpenHandler]()
/// A default scheme. If this value is set, it's available to map URL paths without schemes.
///
/// Navigator.scheme = "myapp"
/// Navigator.map("/user/<int:id>", UserViewController.self)
/// Navigator.map("/post/<title>", PostViewController.self)
///
/// this is equivalent to:
///
/// Navigator.map("myapp://user/<int:id>", UserViewController.self)
/// Navigator.map("myapp://post/<title>", PostViewController.self)
public var scheme: String? {
didSet {
if let scheme = self.scheme where scheme.containsString("://") == true {
self.scheme = scheme.componentsSeparatedByString("://")[0]
}
}
}
// MARK: Initializing
public init() {
// ⛵ I'm an URLNavigator!
}
// MARK: Singleton
/// Returns a default navigator. A global constant `Navigator` is a shortcut of `URLNavigator.defaultNavigator()`.
///
/// - SeeAlso: `Navigator`
public static func defaultNavigator() -> URLNavigator {
struct Shared {
static let defaultNavigator = URLNavigator()
}
return Shared.defaultNavigator
}
// MARK: URL Mapping
/// Map an `URLNavigable` to an URL pattern.
public func map(URLPattern: URLConvertible, _ navigable: URLNavigable.Type) {
let URLString = URLNavigator.normalizedURL(URLPattern, scheme: self.scheme).URLStringValue
self.URLMap[URLString] = navigable
}
/// Map an `URLOpenHandler` to an URL pattern.
public func map(URLPattern: URLConvertible, _ handler: URLOpenHandler) {
let URLString = URLNavigator.normalizedURL(URLPattern, scheme: self.scheme).URLStringValue
self.URLOpenHandlers[URLString] = handler
}
// MARK: Matching URLs
/// Returns a matching URL pattern and placeholder values from specified URL and URL patterns. Returns `nil` if the
/// URL is not contained in URL patterns.
///
/// For example:
///
/// let (URLPattern, values) = URLNavigator.matchURL("myapp://user/123", from: ["myapp://user/<int:id>"])
///
/// The value of the `URLPattern` from an example above is `"myapp://user/<int:id>"` and the value of the `values`
/// is `["id": 123]`.
///
/// - Parameter URL: The placeholder-filled URL.
/// - Parameter from: The array of URL patterns.
///
/// - Returns: A tuple of URL pattern string and a dictionary of URL placeholder values.
static func matchURL(URL: URLConvertible, scheme: String? = nil,
from URLPatterns: [String]) -> (String, [String: AnyObject])? {
let normalizedURLString = URLNavigator.normalizedURL(URL, scheme: scheme).URLStringValue
let URLPathComponents = normalizedURLString.componentsSeparatedByString("/") // e.g. ["myapp:", "user", "123"]
outer: for URLPattern in URLPatterns {
// e.g. ["myapp:", "user", "<int:id>"]
let URLPatternPathComponents = URLPattern.componentsSeparatedByString("/")
let containsPathPlaceholder = URLPatternPathComponents.contains({ $0.hasPrefix("<path:") })
guard containsPathPlaceholder || URLPatternPathComponents.count == URLPathComponents.count else {
continue
}
var values = [String: AnyObject]()
// e.g. ["user", "<int:id>"]
for (i, component) in URLPatternPathComponents.enumerate() {
guard i < URLPathComponents.count else {
continue outer
}
let info = self.placeholderKeyValueFromURLPatternPathComponent(component,
URLPathComponents: URLPathComponents,
atIndex: i
)
if let key = info?.0, value = info?.1 {
values[key] = value // e.g. ["id": 123]
if component.hasPrefix("<path:") {
break // there's no more placeholder after <path:>
}
} else if component != URLPathComponents[i] {
continue outer
}
}
return (URLPattern, values)
}
return nil
}
/// Returns a matched view controller from a specified URL.
///
/// - Parameter URL: The URL to find view controllers.
/// - Returns: A match view controller or `nil` if not matched.
public func viewControllerForURL(URL: URLConvertible) -> UIViewController? {
if let (URLPattern, values) = URLNavigator.matchURL(URL, scheme: self.scheme, from: Array(self.URLMap.keys)) {
let navigable = self.URLMap[URLPattern]
return navigable?.init(URL: URL, values: values) as? UIViewController
}
return nil
}
// MARK: Pushing View Controllers with URL
/// Pushes a view controller using `UINavigationController.pushViewController()`.
///
/// This is an example of pushing a view controller to the top-most view contoller:
///
/// Navigator.pushURL("myapp://user/123")
///
/// Use the return value to access a view controller.
///
/// let userViewController = Navigator.pushURL("myapp://user/123")
/// userViewController?.doSomething()
///
/// - Parameter URL: The URL to find view controllers.
/// - Parameter from: The navigation controller which is used to push a view controller. Use application's top-most
/// view controller if `nil` is specified. `nil` by default.
/// - Parameter animated: Whether animates view controller transition or not. `true` by default.
///
/// - Returns: The pushed view controller. Returns `nil` if there's no matching view controller or failed to push
/// a view controller.
public func pushURL(URL: URLConvertible,
from: UINavigationController? = nil,
animated: Bool = true) -> UIViewController? {
guard let viewController = self.viewControllerForURL(URL) else {
return nil
}
return self.push(viewController, from: from, animated: animated)
}
/// Pushes a view controller using `UINavigationController.pushViewController()`.
///
/// - Parameter viewController: The `UIViewController` instance to be pushed.
/// - Parameter from: The navigation controller which is used to push a view controller. Use application's top-most
/// view controller if `nil` is specified. `nil` by default.
/// - Parameter animated: Whether animates view controller transition or not. `true` by default.
///
/// - Returns: The pushed view controller. Returns `nil` if failed to push a view controller.
public func push(viewController: UIViewController,
from: UINavigationController? = nil,
animated: Bool = true) -> UIViewController? {
guard let navigationController = from ?? UIViewController.topMostViewController()?.navigationController else {
return nil
}
navigationController.pushViewController(viewController, animated: animated)
return viewController
}
// MARK: Presenting View Controllers with URL
/// Presents a view controller using `UIViewController.presentViewController()`.
///
/// This is an example of presenting a view controller to the top-most view contoller:
///
/// Navigator.presentURL("myapp://user/123")
///
/// Use the return value to access a view controller.
///
/// let userViewController = Navigator.presentURL("myapp://user/123")
/// userViewController?.doSomething()
///
/// - Parameter URL: The URL to find view controllers.
/// - Parameter wrap: Wraps the view controller with a `UINavigationController` if `true` is specified. `false` by
/// default.
/// - Parameter from: The view controller which is used to present a view controller. Use application's top-most
/// view controller if `nil` is specified. `nil` by default.
/// - Parameter animated: Whether animates view controller transition or not. `true` by default.
/// - Parameter completion: Called after the transition has finished.
///
/// - Returns: The presented view controller. Returns `nil` if there's no matching view controller or failed to
/// present a view controller.
public func presentURL(URL: URLConvertible,
wrap: Bool = false,
from: UIViewController? = nil,
animated: Bool = true,
completion: (() -> Void)? = nil) -> UIViewController? {
guard let viewController = self.viewControllerForURL(URL) else {
return nil
}
return self.present(viewController, wrap: wrap, from: from, animated: animated, completion: completion)
}
/// Presents a view controller using `UIViewController.presentViewController()`.
///
/// - Parameter viewController: The `UIViewController` instance to be presented.
/// - Parameter wrap: Wraps the view controller with a `UINavigationController` if `true` is specified. `false` by
/// default.
/// - Parameter from: The view controller which is used to present a view controller. Use application's top-most
/// view controller if `nil` is specified. `nil` by default.
/// - Parameter animated: Whether animates view controller transition or not. `true` by default.
/// - Parameter completion: Called after the transition has finished.
///
/// - Returns: The presented view controller. Returns `nil` if failed to present a view controller.
public func present(viewController: UIViewController,
wrap: Bool = false,
from: UIViewController? = nil,
animated: Bool = true,
completion: (() -> Void)? = nil) -> UIViewController? {
guard let fromViewController = from ?? UIViewController.topMostViewController() else {
return nil
}
if wrap {
let navigationController = UINavigationController(rootViewController: viewController)
fromViewController.presentViewController(navigationController, animated: animated, completion: nil)
} else {
fromViewController.presentViewController(viewController, animated: animated, completion: nil)
}
return viewController
}
// MARK: Opening URL
/// Executes the registered `URLOpenHandler`.
///
/// - Parameter URL: The URL to find `URLOpenHandler`s.
///
/// - Returns: The return value of the matching `URLOpenHandler`. Returns `false` if there's no match.
public func openURL(URL: URLConvertible) -> Bool {
let URLOpenHandlersKeys = Array(self.URLOpenHandlers.keys)
if let (URLPattern, values) = URLNavigator.matchURL(URL, scheme: self.scheme, from: URLOpenHandlersKeys) {
let handler = self.URLOpenHandlers[URLPattern]
if handler?(URL: URL, values: values) == true {
return true
}
}
return false
}
// MARK: Utils
/// Returns an scheme-appended `URLConvertible` if given `URL` doesn't have its scheme.
static func URLWithScheme(scheme: String?, _ URL: URLConvertible) -> URLConvertible {
let URLString = URL.URLStringValue
if let scheme = scheme where !URLString.containsString("://") {
#if DEBUG
if !URLPatternString.hasPrefix("/") {
NSLog("[Warning] URL pattern doesn't have leading slash(/): '\(URL)'")
}
#endif
return scheme + ":/" + URLString
} else if scheme == nil && !URLString.containsString("://") {
assertionFailure("Either navigator or URL should have scheme: '\(URL)'") // assert only in debug build
}
return URLString
}
/// Returns the URL by
///
/// - Removing redundant trailing slash(/) on scheme
/// - Removing redundant double-slashes(//)
/// - Removing trailing slash(/)
///
/// - Parameter URL: The dirty URL to be normalized.
///
/// - Returns: The normalized URL. Returns `nil` if the pecified URL is invalid.
static func normalizedURL(dirtyURL: URLConvertible, scheme: String? = nil) -> URLConvertible {
guard dirtyURL.URLValue != nil else {
return dirtyURL
}
var URLString = URLNavigator.URLWithScheme(scheme, dirtyURL).URLStringValue
URLString = URLString.componentsSeparatedByString("?")[0].componentsSeparatedByString("#")[0]
URLString = self.replaceRegex(":/{3,}", "://", URLString)
URLString = self.replaceRegex("(?<!:)/{2,}", "/", URLString)
URLString = self.replaceRegex("/+$", "", URLString)
return URLString
}
static func placeholderKeyValueFromURLPatternPathComponent(component: String,
URLPathComponents: [String],
atIndex index: Int) -> (String, AnyObject)? {
guard component.hasPrefix("<") && component.hasSuffix(">") else {
return nil
}
let start = component.startIndex.advancedBy(1)
let end = component.endIndex.advancedBy(-1)
let placeholder = component[start..<end] // e.g. "<int:id>" -> "int:id"
let typeAndKey = placeholder.componentsSeparatedByString(":") // e.g. ["int", "id"]
if typeAndKey.count == 0 { // e.g. component is "<>"
return nil
}
if typeAndKey.count == 1 { // untyped placeholder
return (placeholder, URLPathComponents[index])
}
let (type, key) = (typeAndKey[0], typeAndKey[1]) // e.g. ("int", "id")
let value: AnyObject?
switch type {
case "int": value = Int(URLPathComponents[index]) // e.g. 123
case "float": value = Float(URLPathComponents[index]) // e.g. 123.0
case "path": value = URLPathComponents[index..<URLPathComponents.count].joinWithSeparator("/")
default: value = URLPathComponents[index]
}
if let value = value {
return (key, value)
}
return nil
}
static func replaceRegex(pattern: String, _ repl: String, _ string: String) -> String {
guard let regex = try? NSRegularExpression(pattern: pattern, options: []) else {
return string
}
let mutableString = NSMutableString(string: string)
let range = NSMakeRange(0, string.characters.count)
regex.replaceMatchesInString(mutableString, options: [], range: range, withTemplate: repl)
return mutableString as String
}
}
// MARK: - Default Navigator
public let Navigator = URLNavigator.defaultNavigator()
| mit | 1e96f3ed65f95b03499e751255f133f6 | 42.909535 | 119 | 0.627541 | 4.769987 | false | false | false | false |
Ozkr16/CryptoAnalyzer | CryptoAnalyzer/ViewController.swift | 1 | 7318 | //
// ViewController.swift
// CryptoAnalyzer
//
// Created by Oscar Gutierrez C on 6/2/17.
// Copyright © 2017 Trilobytes. All rights reserved.
//
import Cocoa
class ViewController: NSViewController, NSTextDelegate,
NSTextFieldDelegate {
@IBOutlet weak var textToAnalyzeField: NSTextField!
@IBOutlet weak var ResultsLabel: NSTextField!
@IBOutlet weak var bigramasLabel: NSTextFieldCell!
@IBOutlet weak var trigramasLabel: NSTextField!
@IBOutlet weak var keyValueTable: NSTableView!
@IBOutlet weak var keyColumn: NSTableColumn!
@IBOutlet weak var valueColumn: NSTableColumn!
@IBOutlet weak var subtextsLabel: NSTextField!
@IBOutlet weak var arbolesLabel: NSTextField!
var tableViewKeyCollection : [String] = []
var tableViewValueCollection : [String] = []
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
textToAnalyzeField.delegate = self
tableViewKeyCollection = ["Indice Coincidencia", "Kasinsky", "Babage"]
tableViewValueCollection = ["", "", ""]
keyValueTable.delegate = self
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
override func controlTextDidChange(_ notification: Notification) {
let textField = notification.object as! NSTextField
//let numeroItems = Double(textToAnalyzeField.stringValue.characters.count)
let symbols = textField.stringValue.lowercased().replacingOccurrences(of: " ", with: "").characters.map{String($0)}
let rawResults = calculateNgramFrequency(of: symbols, withNgramLength: 1)
let frequencyResults = rawResults.map{(simbolo, frecuencia) in return (simbolo, frecuencia/*/numeroItems*100*/)}
let formatedString = formatFrequency(results: frequencyResults, taking: frequencyResults.count)
self.ResultsLabel.stringValue = formatedString
let IC = calculateCoincidenceIndex(of: rawResults, with: symbols.count)
tableViewValueCollection[0] = "\(IC)"
keyValueTable.reloadData()
let bigramFrequency = calculateNgramFrequency(of: symbols, withNgramLength: 2)
let formatedBigrams = formatFrequency(results: bigramFrequency, taking: 35)
let trigramFrequency = calculateNgramFrequency(of: symbols, withNgramLength: 3)
let formatedTrigrams = formatFrequency(results: trigramFrequency, taking: 35)
self.bigramasLabel.stringValue = "20 Bigramas Más Frecuentes: \n\(formatedBigrams)"
self.trigramasLabel.stringValue = "20 Trigramas Más Frecuentes: \n\(formatedTrigrams)"
let subtextos = divideTextInSubtext(texto: textField.stringValue, numeroTextos: 5)
let formattedSubtexts = formatSubtexts(subtextos: subtextos)
self.subtextsLabel.stringValue = formattedSubtexts
let frequencyTrees = produceFrequencyTreesFor(subtexts: subtextos)
self.arbolesLabel.stringValue = frequencyTrees
}
func calculateNgramFrequency(of symbols: [String], withNgramLength: Int) -> [(String, Double)] {
var results = [(String, Double)]()
let conteo: Int = symbols.count - withNgramLength
var index = 0
while(index <= conteo){
var index2 = 0
var nGramaBuscado = ""
while(index2 < withNgramLength){
nGramaBuscado += symbols[index + index2]
index2 += 1
}
if let indiceElementoBuscado = results.index(where:{ (nGrama,valor) in nGrama == nGramaBuscado}) {
var elementoAModificar = results.remove(at: indiceElementoBuscado)
elementoAModificar.1 += 1
results.append(elementoAModificar)
}else{
results.append((nGramaBuscado, 1))
}
index += 1
}
results.sort(by: {$0.1 > $1.1})
return results
}
func formatFrequency(results: [(String, Double)], taking maxNumberOfItems: Int) -> String {
var parcialResult : String = ""
var numeroItemsProcesados = 0
for (letra, frecuencia) in results.sorted(by: {$0.1 > $1.1})
{
parcialResult += "\(letra) : \(frecuencia)\n"
numeroItemsProcesados += 1
if numeroItemsProcesados >= maxNumberOfItems {
break
}
}
return parcialResult
}
func calculateCoincidenceIndex(of frequency: [(String, Double)], with textLeght: Int ) -> Double {
var acumular: Double = 0
for (_, frecuencia) in frequency {
acumular += frecuencia*(frecuencia-1)
}
return acumular/Double(textLeght*(textLeght-1))
}
func divideTextInSubtext(texto: String, numeroTextos: Int) -> [String]{
let caracteres = texto.lowercased().replacingOccurrences(of: " ", with: "").characters.map{String($0)}
var currentT = 0;
var textos = [String](repeating: "", count: numeroTextos)
for letra in caracteres {
textos[currentT] += letra
currentT += 1
if currentT % numeroTextos == 0
{
currentT = 0
}
}
return textos
}
func formatSubtexts(subtextos : [String]) -> String {
var formateado: String = ""
var contador = 0
for sub in subtextos {
contador += 1
formateado += "T\(contador): \n\(sub) \n"
}
return formateado
}
func produceFrequencyTreesFor(subtexts: [String]) -> String {
var currentTextIndex = 0;
var longestTextIndex = 0
var normalizedSubTexts = [[String]](repeating: [""], count: subtexts.count)
for tN in subtexts {
normalizedSubTexts[currentTextIndex] = tN.lowercased().replacingOccurrences(of: " ", with: "").characters.map{String($0)};
if(tN.characters.count >= subtexts[longestTextIndex].characters.count){
longestTextIndex = currentTextIndex
}
currentTextIndex += 1
}
var arbolesTodosLosTextos = ""
currentTextIndex = 0
for tN in subtexts {
let freqSubN = calculateNgramFrequency(of: normalizedSubTexts[currentTextIndex], withNgramLength: 1).sorted(by: {$0.1 > $1.1})
var arbolSubtextoCompleto = ""
let treeWidth = Int((freqSubN[0].1 * 2) + 3)
for (letra, _) in freqSubN {
let indexesOfLetra = tN.findIndexesOfAllOccurrences(of: letra)
var ramaArbolPorLetra = "-\(letra)-"
for index in indexesOfLetra {
let letterIndexOnPreviousText : String
let letterIndexOnNextText : String
let previousText = currentTextIndex - 1 >= 0 ? currentTextIndex - 1 : normalizedSubTexts.count - 1
if previousText == normalizedSubTexts.count - 1{
//First letter, first text, previous item is last letter of whole text: meaning last letter of the longest subtext
if index == 0 {
letterIndexOnPreviousText = "*"
}else{
letterIndexOnPreviousText = normalizedSubTexts[previousText][index-1]
}
}else{
letterIndexOnPreviousText = normalizedSubTexts[previousText][index]
}
//Last letter longest text next item is first letted of whole text: first letter of the first subtext
if currentTextIndex == longestTextIndex && index == normalizedSubTexts[longestTextIndex].count - 1 {
letterIndexOnNextText = "*"
}else{
let nextText = currentTextIndex + 1 < normalizedSubTexts.count ? currentTextIndex + 1 : 0
letterIndexOnNextText = normalizedSubTexts[nextText][index]
}
ramaArbolPorLetra = letterIndexOnPreviousText + ramaArbolPorLetra + letterIndexOnNextText
}
arbolSubtextoCompleto += ramaArbolPorLetra.padLeft(totalWidth: treeWidth) + "\n"
}
currentTextIndex += 1
arbolesTodosLosTextos += "[ T\(currentTextIndex): \(arbolSubtextoCompleto) ]\n"
}
return arbolesTodosLosTextos
}
}
| apache-2.0 | b1260b06c4c3f489fef06e827c68065c | 31.95045 | 129 | 0.710458 | 3.463542 | false | false | false | false |
NoryCao/zhuishushenqi | zhuishushenqi/NewVersion/Mine/ZSSourcesViewController.swift | 1 | 2520 | //
// ZSSourcesViewController.swift
// zhuishushenqi
//
// Created by caony on 2019/11/11.
// Copyright © 2019 QS. All rights reserved.
//
import UIKit
class ZSSourcesViewController: ZSBaseTableViewController {
var sources:[ZSAikanParserModel] { return ZSSourceManager.share.sources }
override func viewDidLoad() {
super.viewDidLoad()
setupNavBar()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.tableView.reloadData()
}
private func setupNavBar() {
let addItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addAction))
self.navigationItem.rightBarButtonItem = addItem
}
@objc
private func addAction() {
let addVC = ZSAddSourceViewController()
self.navigationController?.pushViewController(addVC, animated: true)
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sources.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.qs_dequeueReusableCell(ZSSourceCell.self)
cell?.delegate = self
let source = sources[indexPath.row]
cell?.configure(source: source)
return cell!
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let source = sources[indexPath.row]
let addVC = ZSAddSourceViewController()
addVC.source = source
self.navigationController?.pushViewController(addVC, animated: true)
}
override func registerCellClasses() -> Array<AnyClass> {
return [ZSSourceCell.self]
}
}
extension ZSSourcesViewController:ZSSourceCellDelegate {
func cellDidClickCheck(cell:ZSSourceCell, checked:Bool) {
if checked {
ZSSourceManager.share.select(source: cell.source!)
} else {
ZSSourceManager.share.unselect(source: cell.source!)
}
}
func cellDidClickDelete(cell:ZSSourceCell) {
alert(with: "提醒", message: "确认删除吗,删除后不可恢复?", okTitle: "确认", cancelTitle: "取消", okAction: { [weak self] (action) in
ZSSourceManager.share.delete(source: cell.source!)
self?.tableView.reloadData()
}, cancelAction: nil)
}
}
| mit | 9c56ca0da5adab699afe4c504b842319 | 30.782051 | 122 | 0.663171 | 4.66855 | false | false | false | false |
prey/prey-ios-client | Prey/Classes/Battery.swift | 1 | 2686 | //
// Battery.swift
// Prey
//
// Created by Javier Cala Uribe on 11/7/18.
// Copyright © 2018 Prey, Inc. All rights reserved.
//
import UIKit
// Prey battery definitions
enum kBattery: String {
case STATUS = "battery_status"
case STATE = "state"
case LEVEL = "percentage_remaining"
case LOW = "low_battery"
}
class Battery: NSObject {
// MARK: Properties
static let sharedInstance = Battery()
override fileprivate init() {
// Init object
super.init()
// Enable battery monitoring
UIDevice.current.isBatteryMonitoringEnabled = true
}
// Send battery status to panel
func sendStatusToPanel() -> Bool {
// Event low_battery send one per hour
let defaults = UserDefaults.standard
let currentTime = CFAbsoluteTimeGetCurrent()
if defaults.object(forKey: kBattery.STATUS.rawValue) == nil {
defaults.set(currentTime, forKey:kBattery.STATUS.rawValue)
}
let nextTime : CFAbsoluteTime = defaults.double(forKey: kBattery.STATUS.rawValue) + 60*60*1
guard currentTime > nextTime else {
return false
}
defaults.set(currentTime, forKey:kBattery.STATUS.rawValue)
// Check level battery less than 20%
guard UIDevice.current.batteryLevel < 0.2 else {
return false
}
let params:[String: Any] = [
kGeofence.INFO.rawValue : "",
kGeofence.NAME.rawValue : kBattery.LOW.rawValue]
// Check userApiKey isn't empty
if let username = PreyConfig.sharedInstance.userApiKey, PreyConfig.sharedInstance.isRegistered {
PreyHTTPClient.sharedInstance.userRegisterToPrey(username, password:"x", params:params, messageId:nil, httpMethod:Method.POST.rawValue, endPoint:eventsDeviceEndpoint, onCompletion:PreyHTTPResponse.checkResponse(RequestType.dataSend, preyAction:nil, onCompletion:{(isSuccess: Bool) in PreyLogger("Request dataSend battery")}))
} else {
PreyLogger("Error send data battery")
}
return true
}
// Return header X-Prey-Status
func getHeaderPreyStatus() -> [String: Any] {
let info:[String: Any] = [
kBattery.STATE.rawValue : (UIDevice.current.batteryState == .unplugged ) ? "discharging" : "charging",
kBattery.LEVEL.rawValue : (UIDevice.current.batteryLevel >= 0) ? String(describing: UIDevice.current.batteryLevel*100.0) : "0.0"]
return [kBattery.STATUS.rawValue : info]
}
}
| gpl-3.0 | afba260a13315917c1723b17f639d730 | 32.5625 | 337 | 0.616015 | 4.597603 | false | false | false | false |
RxSwiftCommunity/RxGRDB | Tests/RxGRDBTests/DatabaseRegionObservationTests.swift | 2 | 4705 | import XCTest
import GRDB
import RxSwift
import RxGRDB
private struct Player: Codable, FetchableRecord, PersistableRecord {
var id: Int64
var name: String
var score: Int?
static func createTable(_ db: Database) throws {
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
t.column("score", .integer)
}
}
}
class DatabaseRegionObservationTests : XCTestCase {
func testChangesNotifications() throws {
func setUp<Writer: DatabaseWriter>(_ writer: Writer) throws -> Writer {
try writer.write(Player.createTable)
return writer
}
func test(writer: DatabaseWriter) throws {
let disposeBag = DisposeBag()
try withExtendedLifetime(disposeBag) {
let testSubject = ReplaySubject<Int>.createUnbounded()
DatabaseRegionObservation(tracking: Player.all())
.rx.changes(in: writer)
.map(Player.fetchCount)
.subscribe(testSubject)
.disposed(by: disposeBag)
try writer.writeWithoutTransaction { db in
try Player(id: 1, name: "Arthur", score: 1000).insert(db)
try db.inTransaction {
try Player(id: 2, name: "Barbara", score: 750).insert(db)
try Player(id: 3, name: "Craig", score: 500).insert(db)
return .commit
}
}
let expectedElements = [1, 3]
let elements = try testSubject
.take(expectedElements.count)
.toBlocking(timeout: 1)
.toArray()
XCTAssertEqual(elements, expectedElements)
}
}
try Test(test)
.run { try setUp(DatabaseQueue()) }
.runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) }
.runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) }
}
// This is an usage test. Do the available APIs allow to prepend a
// database connection synchronously, with the guarantee that no race can
// have the subscriber miss an impactful change?
//
// TODO: do the same, but asynchronously. If this is too hard, update the
// public API so that users can easily do it.
func testPrependInitialDatabaseSync() throws {
func setUp<Writer: DatabaseWriter>(_ writer: Writer) throws -> Writer {
try writer.write(Player.createTable)
return writer
}
func test(writer: DatabaseWriter) throws {
let disposeBag = DisposeBag()
try withExtendedLifetime(disposeBag) {
let expectation = self.expectation(description: "")
let testSubject = ReplaySubject<Database>.createUnbounded()
testSubject
.map(Player.fetchCount)
.take(3)
.toArray()
.subscribe(
onSuccess: { value in
XCTAssertEqual(value, [0, 1, 3])
expectation.fulfill()
},
onFailure: { error in XCTFail("Unexpected error \(error)") })
.disposed(by: disposeBag)
try writer
.write({ db in
DatabaseRegionObservation(tracking: Player.all())
.rx.changes(in: writer)
.startWith(db)
.subscribe(testSubject)
})
.disposed(by: disposeBag)
try writer.writeWithoutTransaction { db in
try Player(id: 1, name: "Arthur", score: 1000).insert(db)
try db.inTransaction {
try Player(id: 2, name: "Barbara", score: 750).insert(db)
try Player(id: 3, name: "Craig", score: 500).insert(db)
return .commit
}
}
waitForExpectations(timeout: 1, handler: nil)
}
}
try Test(test)
.run { try setUp(DatabaseQueue()) }
.runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) }
.runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) }
}
}
| mit | 6577f988bc70d3ca21420994716c8df3 | 38.208333 | 85 | 0.500744 | 5.5549 | false | true | false | false |
steelwheels/KiwiControls | Source/Controls/KCGraphics2DView.swift | 1 | 1714 | /**
* @file KCGraphics2DView.swift
* @brief Define KCGraphics2DView class
* @par Copyright
* Copyright (C) 2021 Steel Wheels Project
*/
import CoconutData
import CoreGraphics
#if os(OSX)
import Cocoa
#else
import UIKit
#endif
open class KCGraphics2DView: KCLayerView
{
private var mContext: CNGraphicsContext
private var mForegroundColor: CNColor
public override init(frame : CGRect){
mContext = CNGraphicsContext()
let pref = CNPreference.shared.viewPreference
mForegroundColor = pref.foregroundColor
super.init(frame: frame)
}
public convenience init(){
let frame = CGRect(x: 0.0, y: 0.0, width: 480, height: 270)
self.init(frame: frame)
}
required public init?(coder: NSCoder) {
mContext = CNGraphicsContext()
let pref = CNPreference.shared.viewPreference
mForegroundColor = pref.foregroundColor
super.init(coder: coder)
}
public var foregroundColor: CNColor { get { return mForegroundColor }}
open override func draw(context ctxt: CGContext, count cnt: Int32) {
self.mContext.begin(context: ctxt, logicalFrame: self.logicalFrame, physicalFrame: self.frame)
/* Set default parameters */
if cnt == 0 {
self.mContext.setFillColor(color: self.mForegroundColor)
self.mContext.setStrokeColor(color: self.mForegroundColor)
self.mContext.setPenSize(width: self.logicalFrame.size.width / 100.0)
}
self.draw(graphicsContext: self.mContext, count: cnt)
self.mContext.end()
}
open func draw(graphicsContext ctxt: CNGraphicsContext, count cnt: Int32) {
CNLog(logLevel: .error, message: "must be override", atFunction: #function, inFile: #file)
}
open override func accept(visitor vis: KCViewVisitor){
vis.visit(graphics2DView: self)
}
}
| lgpl-2.1 | db0a4d5c0fd252cbe15ad1f9158b5d07 | 26.206349 | 96 | 0.743874 | 3.394059 | false | false | false | false |
ccrama/Slide-iOS | Slide for Reddit/SubmissionsDataSource.swift | 1 | 10867 | //
// SubmissionsDataSource.swift
// Slide for Reddit
//
// Created by Carlos Crane on 8/23/20.
// Copyright © 2020 Haptic Apps. All rights reserved.
//
import Foundation
import RealmSwift
import reddift
protocol SubmissionDataSouceDelegate: class {
func showIndicator()
func generalError(title: String, message: String)
func loadSuccess(before: Int, count: Int)
func preLoadItems()
func doPreloadImages(values: [RSubmission])
func loadOffline()
func emptyState(_ listing: Listing)
func vcIsGallery() -> Bool
}
class SubmissionsDataSource {
func reset() {
content = []
contentIDs = []
}
var subreddit: String
var color: UIColor
var canGetMore = true
var sorting: LinkSortType
var time: TimeFilterWithin
var isReset = false
var realmListing: RListing?
var updated = NSDate()
var contentIDs = [String]()
weak var currentSession: URLSessionDataTask?
init(subreddit: String, sorting: LinkSortType, time: TimeFilterWithin) {
self.subreddit = subreddit
color = ColorUtil.getColorForSub(sub: subreddit)
paginator = Paginator()
content = []
contentIDs = []
self.sorting = sorting
self.time = time
}
var paginator: Paginator
var content: [RSubmission]
weak var delegate: SubmissionDataSouceDelegate?
var loading = false
var loaded = false
var nomore = false
var offline = false
var page = 0
var tries = 0
var numberFiltered = 0
var lastTopItem = 0
var startTime = Date()
func hasContent() -> Bool {
return !content.isEmpty
}
func hideReadPosts(callback: @escaping (_ indexPaths: [IndexPath]) -> Void) {
var indexPaths: [IndexPath] = []
var index = 0
var count = 0
self.lastTopItem = 0
for submission in content {
if History.getSeen(s: submission) {
indexPaths.append(IndexPath(row: count, section: 0))
content.remove(at: index)
} else {
index += 1
}
count += 1
}
callback(indexPaths)
}
func removeData() {
self.content = []
self.contentIDs = []
}
func hideReadPostsPermanently(callback: @escaping (_ indexPaths: [IndexPath]) -> Void) {
var indexPaths: [IndexPath] = []
var toRemove: [RSubmission] = []
var index = 0
var count = 0
for submission in content {
if History.getSeen(s: submission) {
indexPaths.append(IndexPath(row: count, section: 0))
toRemove.append(submission)
content.remove(at: index)
} else {
index += 1
}
count += 1
}
// TODO: - save realm
callback(indexPaths)
if let session = (UIApplication.shared.delegate as? AppDelegate)?.session {
if !indexPaths.isEmpty {
var hideString = ""
for item in toRemove {
hideString.append(item.getId() + ",")
}
hideString = hideString.substring(0, length: hideString.length - 1)
do {
try session.setHide(true, name: hideString) { (result) in
print(result)
}
} catch {
}
}
}
}
func handleTries(_ callback: @escaping (_ isEmpty: Bool) -> Void) {
if tries < 1 {
self.tries += 1
self.getData(reload: true)
} else {
callback(content.isEmpty)
}
}
func getData(reload: Bool, force: Bool = false) {
self.isReset = reload
if let delegate = delegate {
delegate.preLoadItems()
}
if subreddit.lowercased() == "randnsfw" && !SettingValues.nsfwEnabled {
if let delegate = delegate {
delegate.generalError(title: "r/\(self.subreddit) is NSFW", message: "You must log into Reddit and enable NSFW content at Reddit.com to view this subreddit")
}
return
} else if subreddit.lowercased() == "myrandom" && !AccountController.isGold {
if let delegate = delegate {
delegate.generalError(title: "r/\(self.subreddit) requires gold", message: "See reddit.com/gold/about for more details")
}
return
}
if !loading || force {
if !loaded {
if let delegate = delegate {
delegate.showIndicator()
}
}
currentSession?.cancel()
currentSession = nil
do {
loading = true
if isReset {
paginator = Paginator()
self.page = 0
self.lastTopItem = 0
}
if isReset || !loaded {
self.startTime = Date()
}
var subItem: SubredditURLPath = Subreddit.init(subreddit: subreddit)
if subreddit.hasPrefix("/m/") {
subItem = Multireddit.init(name: subreddit.substring(3, length: subreddit.length - 3), user: AccountController.currentName)
}
if subreddit.contains("/u/") {
subItem = Multireddit.init(name: subreddit.split("/")[3], user: subreddit.split("/")[1])
}
try currentSession = (UIApplication.shared.delegate as? AppDelegate)?.session?.getList(paginator, subreddit: subItem, sort: sorting, timeFilterWithin: time, limit: SettingValues.submissionLimit, completion: { (result) in
self.loaded = true
self.isReset = false
switch result {
case .failure:
print(result.error!)
//test if realm exists and show that
DispatchQueue.main.async {
do {
let realm = try Realm()
self.updated = NSDate()
if let listing = realm.objects(RListing.self).filter({ (item) -> Bool in
return item.subreddit == self.subreddit
}).first {
self.content = []
self.contentIDs = []
for i in listing.links {
self.content.append(i)
}
self.updated = listing.updated
}
var paths = [IndexPath]()
for i in 0..<self.content.count {
paths.append(IndexPath.init(item: i, section: 0))
}
self.loading = false
self.nomore = true
self.offline = true
if let delegate = self.delegate {
delegate.loadOffline()
}
} catch {
}
}
case .success(let listing):
self.loading = false
self.tries = 0
if self.isReset {
self.content = []
self.contentIDs = []
self.page = 0
self.numberFiltered = 0
}
self.offline = false
let before = self.content.count
let newLinks = listing.children.compactMap({ $0 as? Link })
var converted: [RSubmission] = []
var ids = [String]()
for link in newLinks {
ids.append(link.getId())
let newRS = RealmDataWrapper.linkToRSubmission(submission: link)
converted.append(newRS)
CachedTitle.addTitle(s: newRS)
}
self.delegate?.doPreloadImages(values: converted)
var values = PostFilter.filter(converted, previous: self.contentIDs, baseSubreddit: self.subreddit, gallery: self.delegate?.vcIsGallery() ?? false).map { $0 as! RSubmission }
self.numberFiltered += (converted.count - values.count)
if self.page > 0 && !values.isEmpty && SettingValues.showPages {
let pageItem = RSubmission()
pageItem.subreddit = DateFormatter().timeSince(from: self.startTime as NSDate, numericDates: true)
pageItem.author = "PAGE_SEPARATOR"
pageItem.title = "Page \(self.page + 1)\n\(self.content.count + values.count - self.page) posts"
values.insert(pageItem, at: 0)
}
self.page += 1
self.content += values
self.contentIDs += ids
self.paginator = listing.paginator
self.nomore = !listing.paginator.hasMore() || (values.isEmpty && self.content.isEmpty)
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
if self.content.isEmpty && !SettingValues.hideSeen {
self.delegate?.emptyState(listing)
} else if self.content.isEmpty && newLinks.count != 0 && self.paginator.hasMore() {
self.loadMore()
} else {
self.delegate?.loadSuccess(before: before, count: self.content.count)
}
}
}
})
} catch {
loading = false
print(error)
}
}
}
func loadMore() {
getData(reload: false)
}
}
| apache-2.0 | 13329a41dc5d1c6a83811753d2d942ab | 36.212329 | 236 | 0.455918 | 5.560901 | false | false | false | false |
tardieu/swift | stdlib/public/core/Hashable.swift | 5 | 4919 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// FIXME(ABI)#33 (Generic subscripts): This protocol exists to identify
// hashable types. It is used for defining an imitation of a generic
// subscript on `Dictionary<AnyHashable, *>`.
public protocol _Hashable {
func _toAnyHashable() -> AnyHashable
}
/// A type that provides an integer hash value.
///
/// You can use any type that conforms to the `Hashable` protocol in a set or
/// as a dictionary key. Many types in the standard library conform to
/// `Hashable`: strings, integers, floating-point and Boolean values, and even
/// sets provide a hash value by default. Your own custom types can be
/// hashable as well. When you define an enumeration without associated
/// values, it gains `Hashable` conformance automatically, and you can add
/// `Hashable` conformance to your other custom types by adding a single
/// `hashValue` property.
///
/// A hash value, provided by a type's `hashValue` property, is an integer that
/// is the same for any two instances that compare equally. That is, for two
/// instances `a` and `b` of the same type, if `a == b` then
/// `a.hashValue == b.hashValue`. The reverse is not true: Two instances with
/// equal hash values are not necessarily equal to each other.
///
/// - Important: Hash values are not guaranteed to be equal across different
/// executions of your program. Do not save hash values to use during a
/// future execution.
///
/// Conforming to the Hashable Protocol
/// ===================================
///
/// To use your own custom type in a set or as the key type of a dictionary,
/// add `Hashable` conformance to your type by providing a `hashValue`
/// property. The `Hashable` protocol inherits from the `Equatable` protocol,
/// so you must also add an equal-to operator (`==`) function for your
/// custom type.
///
/// As an example, consider a `GridPoint` type that describes a location in a
/// grid of buttons. Here's the initial declaration of the `GridPoint` type:
///
/// /// A point in an x-y coordinate system.
/// struct GridPoint {
/// var x: Int
/// var y: Int
/// }
///
/// You'd like to create a set of the grid points where a user has already
/// tapped. Because the `GridPoint` type is not hashable yet, it can't be used
/// as the `Element` type for a set. To add `Hashable` conformance, provide an
/// `==` operator function and a `hashValue` property.
///
/// extension GridPoint: Hashable {
/// var hashValue: Int {
/// return x.hashValue ^ y.hashValue
/// }
///
/// static func == (lhs: GridPoint, rhs: GridPoint) -> Bool {
/// return lhs.x == rhs.x && lhs.y == rhs.y
/// }
/// }
///
/// The `hashValue` property in this example combines the hash values of a grid
/// point's `x` and `y` values using the bitwise XOR operator (`^`). The `^`
/// operator is one way to combine two integer values into a single value.
///
/// - Note: Set and dictionary performance depends on hash values that minimize
/// collisions for their associated element and key types, respectively.
///
/// Now that `GridPoint` conforms to the `Hashable` protocol, you can create a
/// set of previously tapped grid points.
///
/// var tappedPoints: Set = [GridPoint(x: 2, y: 3), GridPoint(x: 4, y: 1)]
/// let nextTap = GridPoint(x: 0, y: 1)
/// if tappedPoints.contains(nextTap) {
/// print("Already tapped at (\(nextTap.x), \(nextTap.y)).")
/// } else {
/// tappedPoints.insert(nextTap)
/// print("New tap detected at (\(nextTap.x), \(nextTap.y)).")
/// }
/// // Prints "New tap detected at (0, 1).")
public protocol Hashable : _Hashable, Equatable {
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
var hashValue: Int { get }
}
public enum _RuntimeHelpers {}
extension _RuntimeHelpers {
@_silgen_name("swift_stdlib_Hashable_isEqual_indirect")
public static func Hashable_isEqual_indirect<T : Hashable>(
_ lhs: UnsafePointer<T>,
_ rhs: UnsafePointer<T>
) -> Bool {
return lhs.pointee == rhs.pointee
}
@_silgen_name("swift_stdlib_Hashable_hashValue_indirect")
public static func Hashable_hashValue_indirect<T : Hashable>(
_ value: UnsafePointer<T>
) -> Int {
return value.pointee.hashValue
}
}
| apache-2.0 | 0e3f34c74af5494b88973d6c612b06f9 | 40.336134 | 80 | 0.64505 | 4.099167 | false | false | false | false |
karivalkama/Agricola-Scripture-Editor | TranslationEditor/ResourceSelectionCell.swift | 1 | 1123 | //
// ResourceSelectionCell.swift
// TranslationEditor
//
// Created by Mikko Hilpinen on 2.6.2017.
// Copyright © 2017 SIL. All rights reserved.
//
import UIKit
// This cell is used for activating / deactivating a certain resource
class ResourceSelectionCell: UITableViewCell
{
// OUTLETS ------------------
@IBOutlet weak var resourceNameLabel: UILabel!
@IBOutlet weak var resourceLanguageLabel: UILabel!
@IBOutlet weak var resourceStateSwitch: UISwitch!
// ATTRIBUTES --------------
static let identifier = "ResourceCell"
private var onStateChange: ((UITableViewCell, Bool) -> ())!
// ACTIONS ------------------
@IBAction func resourceStateChanged(_ sender: Any)
{
onStateChange(self, resourceStateSwitch.isOn)
}
// OTHER METHODS ----------
func configure(resourceName: String, resourceLanguage: String, resourceState: Bool, onResourceStateChange: @escaping (UITableViewCell, Bool) -> ())
{
self.onStateChange = onResourceStateChange
resourceNameLabel.text = resourceName
resourceLanguageLabel.text = resourceLanguage
resourceStateSwitch.isOn = resourceState
}
}
| mit | 97d2691b240d9d10af98780dd96de75a | 23.391304 | 148 | 0.706774 | 4.186567 | false | false | false | false |
cao903775389/MRCBaseLibrary | Example/MRCBaseLibrary/RecommendTableViewCell.swift | 1 | 4893 | //
// RecommendTableViewCell.swift
// Beauty
// 首页最新推荐列表数据
// Created by 逢阳曹 on 2016/11/14.
// Copyright © 2016年 CBSi. All rights reserved.
//
import UIKit
class RecommendTableViewCell: UITableViewCell, NICell {
//头像
@IBOutlet weak var avatarView: UIView!
//名称
@IBOutlet weak var nameLabel: UILabel!
//封面图
@IBOutlet weak var coverImageView: UIImageView!
//标题
@IBOutlet weak var contentLabel: UILabel!
//浏览量图片
@IBOutlet weak var viewCountImageView: UIImageView!
//浏览量
@IBOutlet weak var viewcountLabel: UILabel!
//视频标识
@IBOutlet weak var videoIcon: UIImageView!
//视频时长
@IBOutlet weak var videoTimeLabel: UILabel!
//浏览量
@IBOutlet weak var viewCountHeight: NSLayoutConstraint!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
//MARK: over load
func shouldUpdate(with object: Any!) -> Bool {
if (object as AnyObject) is RecommendModel {
self.configureHomePageData(object as! RecommendModel)
}
return true
}
//MARK: - Private
//最新频道栏目
func configureHomePageData(_ object: RecommendModel) {
self.nameLabel.text = object.usr
self.coverImageView.setImageWith(URL(string: object.iu!), options: .setImageWithFadeAnimation)
self.contentLabel.text = object.tt
self.viewcountLabel.text = object.viewCount ?? "0"
self.videoIcon.isHidden = (object.type != "va" && object.type != "lv")
self.videoTimeLabel.isHidden = self.videoIcon.isHidden
self.viewCountHeight.constant = 30
self.viewcountLabel.isHidden = self.viewCountHeight.constant == 0
self.viewCountImageView.isHidden = self.viewCountHeight.constant == 0
guard object.stu != nil else { return }
if object.stu! == "1" {
self.videoTimeLabel.text = "直播"
self.viewCountHeight.constant = 0
}else if object.stu == "2" {
self.videoTimeLabel.text = "即将直播"
self.viewCountHeight.constant = 0
}else if object.stu == "3" {
self.viewCountHeight.constant = 30
self.videoTimeLabel.text = "\(object.vl != nil ? object.vl! : "")"
}else if object.stu == "4" {
self.viewCountHeight.constant = 30
}
self.viewcountLabel.isHidden = self.viewCountHeight.constant == 0
self.viewCountImageView.isHidden = self.viewCountHeight.constant == 0
}
}
class RecommendModel: MRCNibCellObject {
//文章类型 文章 视频 直播 图片视频广告
var type: String?
//文章或直播id
var id: String?
//标题
var tt: String?
//用户信息
var usr: String?
//用户头像
var up: String?
//用户身份 1专家 2达人 3编辑
var role: String?
//专家达人id
var eid: String?
//图片
var iu: String?
//链接地址
var val: String?
//视频时长
var vl: String?
//点击量
var viewCount: String?
//直播状态 1进行中 2未开始 3结束
var stu: String?
//直播观看地址
var rtmp: String?
//回放地址
var bu: String?
//是否全屏播放
var full: String?
//视频广告播放地址
var mp4: String?
//视频广告图片(扩展字段)
var videoImage: UIImage?
var iid:String? // 活动id
//广告曝光相关
//展示曝光
var trackUrl: String?
var isTrack: Bool = false
//点击曝光
var clickUrl: String?
var isClick: Bool = false
//over load
required init(anyObject: JSON) {
super.init(cellClass: UINib(nibName: "RecommendTableViewCell", bundle: nil))
type = anyObject["type"].stringValue
id = anyObject["id"].stringValue
tt = anyObject["tt"].stringValue
usr = anyObject["usr"].stringValue
up = anyObject["up"].stringValue
role = anyObject["role"].stringValue
eid = anyObject["eid"].stringValue
iu = anyObject["iu"].stringValue
val = anyObject["val"].stringValue
vl = anyObject["vl"].stringValue
viewCount = anyObject["viewCount"].stringValue
stu = anyObject["stu"].stringValue
rtmp = anyObject["rtmp"].stringValue
bu = anyObject["bu"].stringValue
full = anyObject["full"].stringValue
mp4 = anyObject["mp4"].stringValue
iid = anyObject["iid"].stringValue
trackUrl = anyObject["trackUrl"].stringValue
clickUrl = anyObject["clickUrl"].stringValue
}
}
| mit | 07fb91099a4bf5b2e164c97c7f40aca1 | 24.104972 | 102 | 0.587808 | 4.211307 | false | false | false | false |
DDSwift/SwiftDemos | Day01-LoadingADView/LoadingADView/LoadingADView/Class/Other/Global.swift | 1 | 707 | //
// Global.swift
// LoadingADView
//
// Created by SuperDanny on 16/3/7.
// Copyright © 2016年 SuperDanny. All rights reserved.
//
//import Foundation
import UIKit
// MARK: - 全局常用属性
public let NavigationH: CGFloat = 64
public let ScreenWidth: CGFloat = UIScreen.mainScreen().bounds.size.width
public let ScreenHeight: CGFloat = UIScreen.mainScreen().bounds.size.height
public let ScreenBounds: CGRect = UIScreen.mainScreen().bounds
// MARK: - 通知
// MARK: 广告页通知
public let ADImageLoadSuccess = "ADImageLoadSuccess"
public let ADImageLoadFail = "ADImageLoadFail"
// MARK: 轮播页通知
public let GuideViewControllerDidFinish = "GuideViewControllerDidFinish"
| gpl-3.0 | d3aaaed4532dc96e9142a4531e4f99c6 | 22.857143 | 75 | 0.751497 | 3.630435 | false | false | false | false |
kzaher/RxSwift | Tests/RxCocoaTests/DelegateProxyTest+UIKit.swift | 2 | 18299 | //
// DelegateProxyTest+UIKit.swift
// Tests
//
// Created by Krunoslav Zaher on 12/5/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import UIKit
@testable import RxCocoa
@testable import RxSwift
import XCTest
// MARK: Tests
extension DelegateProxyTest {
func test_UITableViewDelegateExtension() {
performDelegateTest(UITableViewSubclass1(frame: CGRect.zero)) { ExtendTableViewDelegateProxy(tableViewSubclass: $0) }
}
func test_UITableViewDataSourceExtension() {
performDelegateTest(UITableViewSubclass2(frame: CGRect.zero)) { ExtendTableViewDataSourceProxy(tableViewSubclass: $0) }
}
@available(iOS 10.0, tvOS 10.0, *)
func test_UITableViewDataSourcePrefetchingExtension() {
performDelegateTest(UITableViewSubclass3(frame: CGRect.zero)) { ExtendTableViewDataSourcePrefetchingProxy(parentObject: $0) }
}
}
extension DelegateProxyTest {
func test_UICollectionViewDelegateExtension() {
let layout = UICollectionViewFlowLayout()
performDelegateTest(UICollectionViewSubclass1(frame: CGRect.zero, collectionViewLayout: layout)) { ExtendCollectionViewDelegateProxy(parentObject: $0) }
}
func test_UICollectionViewDataSourceExtension() {
let layout = UICollectionViewFlowLayout()
performDelegateTest(UICollectionViewSubclass2(frame: CGRect.zero, collectionViewLayout: layout)) { ExtendCollectionViewDataSourceProxy(parentObject: $0) }
}
@available(iOS 10.0, tvOS 10.0, *)
func test_UICollectionViewDataSourcePrefetchingExtension() {
let layout = UICollectionViewFlowLayout()
performDelegateTest(UICollectionViewSubclass3(frame: CGRect.zero, collectionViewLayout: layout)) { ExtendCollectionViewDataSourcePrefetchingProxy(parentObject: $0) }
}
}
extension DelegateProxyTest {
func test_UINavigationControllerDelegateExtension() {
performDelegateTest(UINavigationControllerSubclass()) { ExtendNavigationControllerDelegateProxy(navigationControllerSubclass: $0) }
}
}
extension DelegateProxyTest {
func test_UIScrollViewDelegateExtension() {
performDelegateTest(UIScrollViewSubclass(frame: CGRect.zero)) { ExtendScrollViewDelegateProxy(scrollViewSubclass: $0) }
}
}
#if os(iOS)
extension DelegateProxyTest {
func test_UISearchBarDelegateExtension() {
performDelegateTest(UISearchBarSubclass(frame: CGRect.zero)) { ExtendSearchBarDelegateProxy(searchBarSubclass: $0) }
}
}
#endif
extension DelegateProxyTest {
func test_UITextViewDelegateExtension() {
performDelegateTest(UITextViewSubclass(frame: CGRect.zero)) { ExtendTextViewDelegateProxy(textViewSubclass: $0) }
}
}
#if os(iOS)
extension DelegateProxyTest {
func test_UISearchController() {
performDelegateTest(UISearchControllerSubclass()) { ExtendSearchControllerDelegateProxy(searchControllerSubclass: $0) }
}
}
extension DelegateProxyTest {
func test_UIPickerViewExtension() {
performDelegateTest(UIPickerViewSubclass(frame: CGRect.zero)) { ExtendPickerViewDelegateProxy(pickerViewSubclass: $0) }
}
func test_UIPickerViewDataSourceExtension() {
performDelegateTest(UIPickerViewSubclass2(frame: CGRect.zero)) { ExtendPickerViewDataSourceProxy(pickerViewSubclass: $0) }
}
}
#endif
extension DelegateProxyTest {
func test_UITabBarControllerDelegateExtension() {
performDelegateTest(UITabBarControllerSubclass()) { ExtendTabBarControllerDelegateProxy(tabBarControllerSubclass: $0) }
}
}
extension DelegateProxyTest {
func test_UITabBarDelegateExtension() {
performDelegateTest(UITabBarSubclass()) { ExtendTabBarDelegateProxy(tabBarSubclass: $0) }
}
}
extension DelegateProxyTest {
/* something is wrong with subclassing mechanism.
func test_NSTextStorageDelegateExtension() {
performDelegateTest(NSTextStorageSubclass(attributedString: NSAttributedString()))
}*/
}
// MARK: Mocks
final class ExtendTableViewDelegateProxy
: RxTableViewDelegateProxy
, TestDelegateProtocol {
weak private(set) var control: UITableViewSubclass1?
init(tableViewSubclass: UITableViewSubclass1) {
self.control = tableViewSubclass
super.init(tableView: tableViewSubclass)
}
}
final class UITableViewSubclass1
: UITableView
, TestDelegateControl {
func doThatTest(_ value: Int) {
(delegate as! TestDelegateProtocol).testEventHappened?(value)
}
var delegateProxy: DelegateProxy<UIScrollView, UIScrollViewDelegate> {
self.rx.delegate
}
func setMineForwardDelegate(_ testDelegate: UIScrollViewDelegate) -> Disposable {
RxScrollViewDelegateProxy.installForwardDelegate(testDelegate, retainDelegate: false, onProxyForObject: self)
}
}
final class ExtendTableViewDataSourceProxy
: RxTableViewDataSourceProxy
, TestDelegateProtocol {
weak private(set) var control: UITableViewSubclass2?
init(tableViewSubclass: UITableViewSubclass2) {
self.control = tableViewSubclass
super.init(tableView: tableViewSubclass)
}
}
final class UITableViewSubclass2
: UITableView
, TestDelegateControl {
func doThatTest(_ value: Int) {
if dataSource != nil {
(dataSource as! TestDelegateProtocol).testEventHappened?(value)
}
}
var delegateProxy: DelegateProxy<UITableView, UITableViewDataSource> {
self.rx.dataSource
}
func setMineForwardDelegate(_ testDelegate: UITableViewDataSource) -> Disposable {
RxTableViewDataSourceProxy.installForwardDelegate(testDelegate, retainDelegate: false, onProxyForObject: self)
}
}
@available(iOS 10.0, tvOS 10.0, *)
final class ExtendTableViewDataSourcePrefetchingProxy
: RxTableViewDataSourcePrefetchingProxy
, TestDelegateProtocol {
weak private(set) var control: UITableViewSubclass3?
init(parentObject: UITableViewSubclass3) {
self.control = parentObject
super.init(tableView: parentObject)
}
}
@available(iOS 10.0, tvOS 10.0, *)
final class UITableViewSubclass3
: UITableView
, TestDelegateControl {
func doThatTest(_ value: Int) {
if prefetchDataSource != nil {
(prefetchDataSource as! TestDelegateProtocol).testEventHappened?(value)
}
}
var delegateProxy: DelegateProxy<UITableView, UITableViewDataSourcePrefetching> {
self.rx.prefetchDataSource
}
func setMineForwardDelegate(_ testDelegate: UITableViewDataSourcePrefetching) -> Disposable {
RxTableViewDataSourcePrefetchingProxy.installForwardDelegate(testDelegate, retainDelegate: false, onProxyForObject: self)
}
}
final class ExtendCollectionViewDelegateProxy
: RxCollectionViewDelegateProxy
, TestDelegateProtocol {
weak private(set) var control: UICollectionViewSubclass1?
init(parentObject: UICollectionViewSubclass1) {
self.control = parentObject
super.init(collectionView: parentObject)
}
}
final class UICollectionViewSubclass1
: UICollectionView
, TestDelegateControl {
func doThatTest(_ value: Int) {
(delegate as! TestDelegateProtocol).testEventHappened?(value)
}
var delegateProxy: DelegateProxy<UIScrollView, UIScrollViewDelegate> {
self.rx.delegate
}
func setMineForwardDelegate(_ testDelegate: UIScrollViewDelegate) -> Disposable {
RxScrollViewDelegateProxy.installForwardDelegate(testDelegate, retainDelegate: false, onProxyForObject: self)
}
}
final class ExtendCollectionViewDataSourceProxy
: RxCollectionViewDataSourceProxy
, TestDelegateProtocol {
weak private(set) var control: UICollectionViewSubclass2?
init(parentObject: UICollectionViewSubclass2) {
self.control = parentObject
super.init(collectionView: parentObject)
}
}
final class UICollectionViewSubclass2
: UICollectionView
, TestDelegateControl {
func doThatTest(_ value: Int) {
if dataSource != nil {
(dataSource as! TestDelegateProtocol).testEventHappened?(value)
}
}
var delegateProxy: DelegateProxy<UICollectionView, UICollectionViewDataSource> {
self.rx.dataSource
}
func setMineForwardDelegate(_ testDelegate: UICollectionViewDataSource) -> Disposable {
RxCollectionViewDataSourceProxy.installForwardDelegate(testDelegate, retainDelegate: false, onProxyForObject: self)
}
}
@available(iOS 10.0, tvOS 10.0, *)
final class ExtendCollectionViewDataSourcePrefetchingProxy
: RxCollectionViewDataSourcePrefetchingProxy
, TestDelegateProtocol {
weak private(set) var control: UICollectionViewSubclass3?
init(parentObject: UICollectionViewSubclass3) {
self.control = parentObject
super.init(collectionView: parentObject)
}
}
@available(iOS 10.0, tvOS 10.0, *)
final class UICollectionViewSubclass3
: UICollectionView
, TestDelegateControl {
func doThatTest(_ value: Int) {
if prefetchDataSource != nil {
(prefetchDataSource as! TestDelegateProtocol).testEventHappened?(value)
}
}
var delegateProxy: DelegateProxy<UICollectionView, UICollectionViewDataSourcePrefetching> {
self.rx.prefetchDataSource
}
func setMineForwardDelegate(_ testDelegate: UICollectionViewDataSourcePrefetching) -> Disposable {
RxCollectionViewDataSourcePrefetchingProxy.installForwardDelegate(testDelegate, retainDelegate: false, onProxyForObject: self)
}
}
final class ExtendScrollViewDelegateProxy
: RxScrollViewDelegateProxy
, TestDelegateProtocol {
weak private(set) var control: UIScrollViewSubclass?
init(scrollViewSubclass: UIScrollViewSubclass) {
self.control = scrollViewSubclass
super.init(scrollView: scrollViewSubclass)
}
}
final class UIScrollViewSubclass
: UIScrollView
, TestDelegateControl {
func doThatTest(_ value: Int) {
(delegate as! TestDelegateProtocol).testEventHappened?(value)
}
var delegateProxy: DelegateProxy<UIScrollView, UIScrollViewDelegate> {
self.rx.delegate
}
func setMineForwardDelegate(_ testDelegate: UIScrollViewDelegate) -> Disposable {
RxScrollViewDelegateProxy.installForwardDelegate(testDelegate, retainDelegate: false, onProxyForObject: self)
}
}
#if os(iOS)
final class ExtendSearchBarDelegateProxy
: RxSearchBarDelegateProxy
, TestDelegateProtocol {
weak private(set) var control: UISearchBarSubclass?
init(searchBarSubclass: UISearchBarSubclass) {
self.control = searchBarSubclass
super.init(searchBar: searchBarSubclass)
}
}
final class UISearchBarSubclass
: UISearchBar
, TestDelegateControl {
func doThatTest(_ value: Int) {
(delegate as! TestDelegateProtocol).testEventHappened?(value)
}
var delegateProxy: DelegateProxy<UISearchBar, UISearchBarDelegate> {
self.rx.delegate
}
func setMineForwardDelegate(_ testDelegate: UISearchBarDelegate) -> Disposable {
RxSearchBarDelegateProxy.installForwardDelegate(testDelegate, retainDelegate: false, onProxyForObject: self)
}
}
#endif
final class ExtendTextViewDelegateProxy
: RxTextViewDelegateProxy
, TestDelegateProtocol {
weak private(set) var control: UITextViewSubclass?
init(textViewSubclass: UITextViewSubclass) {
self.control = textViewSubclass
super.init(textView: textViewSubclass)
}
}
final class UITextViewSubclass
: UITextView
, TestDelegateControl {
func doThatTest(_ value: Int) {
(delegate as! TestDelegateProtocol).testEventHappened?(value)
}
var delegateProxy: DelegateProxy<UIScrollView, UIScrollViewDelegate> {
self.rx.delegate
}
func setMineForwardDelegate(_ testDelegate: UIScrollViewDelegate) -> Disposable {
RxScrollViewDelegateProxy.installForwardDelegate(testDelegate, retainDelegate: false, onProxyForObject: self)
}
}
#if os(iOS)
final class ExtendSearchControllerDelegateProxy
: RxSearchControllerDelegateProxy
, TestDelegateProtocol {
init(searchControllerSubclass: UISearchControllerSubclass) {
super.init(searchController: searchControllerSubclass)
}
}
final class UISearchControllerSubclass
: UISearchController
, TestDelegateControl {
func doThatTest(_ value: Int) {
(delegate as! TestDelegateProtocol).testEventHappened?(value)
}
var delegateProxy: DelegateProxy<UISearchController, UISearchControllerDelegate> {
self.rx.delegate
}
func setMineForwardDelegate(_ testDelegate: UISearchControllerDelegate) -> Disposable {
RxSearchControllerDelegateProxy.installForwardDelegate(testDelegate, retainDelegate: false, onProxyForObject: self)
}
}
final class ExtendPickerViewDelegateProxy
: RxPickerViewDelegateProxy
, TestDelegateProtocol {
init(pickerViewSubclass: UIPickerViewSubclass) {
super.init(pickerView: pickerViewSubclass)
}
}
final class UIPickerViewSubclass
: UIPickerView
, TestDelegateControl {
func doThatTest(_ value: Int) {
(delegate as! TestDelegateProtocol).testEventHappened?(value)
}
var delegateProxy: DelegateProxy<UIPickerView, UIPickerViewDelegate> {
self.rx.delegate
}
func setMineForwardDelegate(_ testDelegate: UIPickerViewDelegate) -> Disposable {
return RxPickerViewDelegateProxy.installForwardDelegate(testDelegate,
retainDelegate: false,
onProxyForObject: self)
}
}
final class ExtendPickerViewDataSourceProxy
: RxPickerViewDataSourceProxy
, TestDelegateProtocol {
weak private(set) var control: UIPickerViewSubclass2?
init(pickerViewSubclass: UIPickerViewSubclass2) {
self.control = pickerViewSubclass
super.init(pickerView: pickerViewSubclass)
}
}
final class UIPickerViewSubclass2: UIPickerView, TestDelegateControl {
func doThatTest(_ value: Int) {
if dataSource != nil {
(dataSource as! TestDelegateProtocol).testEventHappened?(value)
}
}
var delegateProxy: DelegateProxy<UIPickerView, UIPickerViewDataSource> {
self.rx.dataSource
}
func setMineForwardDelegate(_ testDelegate: UIPickerViewDataSource) -> Disposable {
RxPickerViewDataSourceProxy.installForwardDelegate(testDelegate, retainDelegate: false, onProxyForObject: self)
}
}
#endif
final class ExtendTextStorageDelegateProxy
: RxTextStorageDelegateProxy
, TestDelegateProtocol {
init(textStorageSubclass: NSTextStorageSubclass) {
super.init(textStorage: textStorageSubclass)
}
}
final class NSTextStorageSubclass
: NSTextStorage
, TestDelegateControl {
func doThatTest(_ value: Int) {
(delegate as! TestDelegateProtocol).testEventHappened?(value)
}
var delegateProxy: DelegateProxy<NSTextStorage, NSTextStorageDelegate> {
self.rx.delegate
}
func setMineForwardDelegate(_ testDelegate: NSTextStorageDelegate) -> Disposable {
RxTextStorageDelegateProxy.installForwardDelegate(testDelegate, retainDelegate: false, onProxyForObject: self)
}
}
final class ExtendNavigationControllerDelegateProxy
: RxNavigationControllerDelegateProxy
, TestDelegateProtocol {
weak private(set) var control: UINavigationControllerSubclass?
init(navigationControllerSubclass: UINavigationControllerSubclass) {
self.control = navigationControllerSubclass
super.init(navigationController: navigationControllerSubclass)
}
}
final class ExtendTabBarControllerDelegateProxy
: RxTabBarControllerDelegateProxy
, TestDelegateProtocol {
weak private(set) var tabBarControllerSubclass: UITabBarControllerSubclass?
init(tabBarControllerSubclass: UITabBarControllerSubclass) {
self.tabBarControllerSubclass = tabBarControllerSubclass
super.init(tabBar: tabBarControllerSubclass)
}
}
final class ExtendTabBarDelegateProxy
: RxTabBarDelegateProxy
, TestDelegateProtocol {
weak private(set) var control: UITabBarSubclass?
init(tabBarSubclass: UITabBarSubclass) {
self.control = tabBarSubclass
super.init(tabBar: tabBarSubclass)
}
}
final class UINavigationControllerSubclass: UINavigationController, TestDelegateControl {
func doThatTest(_ value: Int) {
(delegate as! TestDelegateProtocol).testEventHappened?(value)
}
var delegateProxy: DelegateProxy<UINavigationController, UINavigationControllerDelegate> {
self.rx.delegate
}
func setMineForwardDelegate(_ testDelegate: UINavigationControllerDelegate) -> Disposable {
return RxNavigationControllerDelegateProxy.installForwardDelegate(testDelegate,
retainDelegate: false,
onProxyForObject: self)
}
}
final class UITabBarControllerSubclass
: UITabBarController
, TestDelegateControl {
func doThatTest(_ value: Int) {
(delegate as! TestDelegateProtocol).testEventHappened?(value)
}
var delegateProxy: DelegateProxy<UITabBarController, UITabBarControllerDelegate> {
self.rx.delegate
}
func setMineForwardDelegate(_ testDelegate: UITabBarControllerDelegate) -> Disposable {
RxTabBarControllerDelegateProxy.installForwardDelegate(testDelegate, retainDelegate: false, onProxyForObject: self)
}
}
final class UITabBarSubclass: UITabBar, TestDelegateControl {
func doThatTest(_ value: Int) {
(delegate as! TestDelegateProtocol).testEventHappened?(value)
}
var delegateProxy: DelegateProxy<UITabBar, UITabBarDelegate> {
self.rx.delegate
}
func setMineForwardDelegate(_ testDelegate: UITabBarDelegate) -> Disposable {
return RxTabBarDelegateProxy.installForwardDelegate(testDelegate,
retainDelegate: false,
onProxyForObject: self)
}
}
| mit | 98ccf467695ff0fc5e75a9a9cfd9e964 | 31.616756 | 173 | 0.7262 | 5.466985 | false | true | false | false |
sergdort/CleanArchitectureRxSwift | NetworkPlatform/Network/Network.swift | 1 | 2574 | //
// Network.swift
// CleanArchitectureRxSwift
//
// Created by Andrey Yastrebov on 16.03.17.
// Copyright © 2017 sergdort. All rights reserved.
//
import Foundation
import Alamofire
import Domain
import RxAlamofire
import RxSwift
final class Network<T: Decodable> {
private let endPoint: String
private let scheduler: ConcurrentDispatchQueueScheduler
init(_ endPoint: String) {
self.endPoint = endPoint
self.scheduler = ConcurrentDispatchQueueScheduler(qos: DispatchQoS(qosClass: DispatchQoS.QoSClass.background, relativePriority: 1))
}
func getItems(_ path: String) -> Observable<[T]> {
let absolutePath = "\(endPoint)/\(path)"
return RxAlamofire
.data(.get, absolutePath)
.debug()
.observe(on: scheduler)
.map({ data -> [T] in
return try JSONDecoder().decode([T].self, from: data)
})
}
func getItem(_ path: String, itemId: String) -> Observable<T> {
let absolutePath = "\(endPoint)/\(path)/\(itemId)"
return RxAlamofire
.data(.get, absolutePath)
.debug()
.observe(on: scheduler)
.map({ data -> T in
return try JSONDecoder().decode(T.self, from: data)
})
}
func postItem(_ path: String, parameters: [String: Any]) -> Observable<T> {
let absolutePath = "\(endPoint)/\(path)"
return RxAlamofire
.request(.post, absolutePath, parameters: parameters)
.debug()
.observe(on: scheduler)
.data()
.map({ data -> T in
return try JSONDecoder().decode(T.self, from: data)
})
}
func updateItem(_ path: String, itemId: String, parameters: [String: Any]) -> Observable<T> {
let absolutePath = "\(endPoint)/\(path)/\(itemId)"
return RxAlamofire
.request(.put, absolutePath, parameters: parameters)
.debug()
.observe(on: scheduler)
.data()
.map({ data -> T in
return try JSONDecoder().decode(T.self, from: data)
})
}
func deleteItem(_ path: String, itemId: String) -> Observable<T> {
let absolutePath = "\(endPoint)/\(path)/\(itemId)"
return RxAlamofire
.request(.delete, absolutePath)
.debug()
.observe(on: scheduler)
.data()
.map({ data -> T in
return try JSONDecoder().decode(T.self, from: data)
})
}
}
| mit | 17a54db477725334716e9caff27a3850 | 30.378049 | 139 | 0.556549 | 4.678182 | false | false | false | false |
googleads/googleads-mobile-ios-examples | Swift/advanced/SwiftUIDemo/SwiftUIDemo/Rewarded-Interstitial/AdDialogContentView.swift | 1 | 1361 | import SwiftUI
struct AdDialogContentView: View {
@StateObject private var countdownTimer = CountdownTimer()
@Binding var isPresenting: Bool
@Binding var showAd: Bool
var body: some View {
ZStack {
Color.gray
.opacity(0.75)
.ignoresSafeArea(.all)
dialogBody
.background(Color.white)
.padding()
}
}
var dialogBody: some View {
VStack(alignment: .leading, spacing: 10) {
Text("Watch an ad for 10 more coins.")
Text("Video starting in \(countdownTimer.timeLeft)...")
.foregroundColor(.gray)
HStack {
Spacer()
Button {
isPresenting = false
} label: {
Text("No thanks")
.bold()
.foregroundColor(.red)
}
}
}
.onAppear {
showAd = false
}
.onChange(
of: isPresenting,
perform: { newValue in
newValue ? countdownTimer.start() : countdownTimer.pause()
}
)
.onChange(
of: countdownTimer.isComplete,
perform: { newValue in
if newValue {
isPresenting = false
showAd = true
}
}
)
.padding()
}
}
struct AdDialogContentView_Previews: PreviewProvider {
static var previews: some View {
AdDialogContentView(isPresenting: .constant(true), showAd: .constant(false))
}
}
| apache-2.0 | 703687572b649b1f6674cd2d09c3fca7 | 20.265625 | 80 | 0.572373 | 4.433225 | false | false | false | false |
zkhCreator/ASImagePicker | ASImagePicker/Classes/Classes/View/ASAlbumListTableViewCell.swift | 1 | 956 | //
// ASAlbumListTableViewCell.swift
// Pods
//
// Created by zkhCreator on 11/06/2017.
//
//
import UIKit
class ASAlbumListTableViewCell: UITableViewCell {
@IBOutlet public weak var thumbnail: UIImageView!
@IBOutlet public weak var albumTitleLabel: UILabel!
@IBOutlet public weak var albumCountLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.thumbnail.layer.cornerRadius = 2
self.thumbnail.layer.masksToBounds = true;
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
override func prepareForReuse() {
super.prepareForReuse()
albumTitleLabel.text = ""
albumCountLabel.text = "0"
thumbnail.image = UIImage.getImage(imageName: "album_placeHolderImage")
}
}
| mit | 3e2f33b06e7033bec374770578f4741e | 24.837838 | 79 | 0.665272 | 4.732673 | false | false | false | false |
whiteath/ReadFoundationSource | Foundation/URLSession/URLSessionTask.swift | 1 | 25607 | // Foundation/URLSession/URLSessionTask.swift - URLSession API
//
// 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
//
// -----------------------------------------------------------------------------
///
/// URLSession API code.
/// - SeeAlso: URLSession.swift
///
// -----------------------------------------------------------------------------
import CoreFoundation
import Dispatch
/// A cancelable object that refers to the lifetime
/// of processing a given request.
open class URLSessionTask : NSObject, NSCopying {
public var countOfBytesClientExpectsToReceive: Int64 { NSUnimplemented() }
public var countOfBytesClientExpectsToSend: Int64 { NSUnimplemented() }
public var earliestBeginDate: Date? { NSUnimplemented() }
/// How many times the task has been suspended, 0 indicating a running task.
internal var suspendCount = 1
internal var session: URLSessionProtocol! //change to nil when task completes
internal let body: _Body
fileprivate var _protocol: URLProtocol! = nil
private let syncQ = DispatchQueue(label: "org.swift.URLSessionTask.SyncQ")
/// All operations must run on this queue.
internal let workQueue: DispatchQueue
public override init() {
// Darwin Foundation oddly allows calling this initializer, even though
// such a task is quite broken -- it doesn't have a session. And calling
// e.g. `taskIdentifier` will crash.
//
// We set up the bare minimum for init to work, but don't care too much
// about things crashing later.
session = _MissingURLSession()
taskIdentifier = 0
originalRequest = nil
body = .none
workQueue = DispatchQueue(label: "URLSessionTask.notused.0")
super.init()
}
/// Create a data task. If there is a httpBody in the URLRequest, use that as a parameter
internal convenience init(session: URLSession, request: URLRequest, taskIdentifier: Int) {
if let bodyData = request.httpBody {
self.init(session: session, request: request, taskIdentifier: taskIdentifier, body: _Body.data(createDispatchData(bodyData)))
} else {
self.init(session: session, request: request, taskIdentifier: taskIdentifier, body: .none)
}
}
internal init(session: URLSession, request: URLRequest, taskIdentifier: Int, body: _Body) {
self.session = session
/* make sure we're actually having a serial queue as it's used for synchronization */
self.workQueue = DispatchQueue.init(label: "org.swift.URLSessionTask.WorkQueue", target: session.workQueue)
self.taskIdentifier = taskIdentifier
self.originalRequest = request
self.body = body
super.init()
if session.configuration.protocolClasses != nil {
guard let protocolClasses = session.configuration.protocolClasses else { fatalError() }
if let urlProtocolClass = URLProtocol.getProtocolClass(protocols: protocolClasses, request: request) {
guard let urlProtocol = urlProtocolClass as? URLProtocol.Type else { fatalError() }
self._protocol = urlProtocol.init(task: self, cachedResponse: nil, client: nil)
} else {
guard let protocolClasses = URLProtocol.getProtocols() else { fatalError() }
if let urlProtocolClass = URLProtocol.getProtocolClass(protocols: protocolClasses, request: request) {
guard let urlProtocol = urlProtocolClass as? URLProtocol.Type else { fatalError() }
self._protocol = urlProtocol.init(task: self, cachedResponse: nil, client: nil)
}
}
} else {
guard let protocolClasses = URLProtocol.getProtocols() else { fatalError() }
if let urlProtocolClass = URLProtocol.getProtocolClass(protocols: protocolClasses, request: request) {
guard let urlProtocol = urlProtocolClass as? URLProtocol.Type else { fatalError() }
self._protocol = urlProtocol.init(task: self, cachedResponse: nil, client: nil)
}
}
}
deinit {
//TODO: Do we remove the EasyHandle from the session here? This might run on the wrong thread / queue.
}
open override func copy() -> Any {
return copy(with: nil)
}
open func copy(with zone: NSZone?) -> Any {
return self
}
/// An identifier for this task, assigned by and unique to the owning session
open let taskIdentifier: Int
/// May be nil if this is a stream task
/*@NSCopying*/ open let originalRequest: URLRequest?
/// May differ from originalRequest due to http server redirection
/*@NSCopying*/ open internal(set) var currentRequest: URLRequest? {
get {
return self.syncQ.sync { return self._currentRequest }
}
set {
self.syncQ.sync { self._currentRequest = newValue }
}
}
fileprivate var _currentRequest: URLRequest? = nil
/*@NSCopying*/ open internal(set) var response: URLResponse? {
get {
return self.syncQ.sync { return self._response }
}
set {
self.syncQ.sync { self._response = newValue }
}
}
fileprivate var _response: URLResponse? = nil
/* Byte count properties may be zero if no body is expected,
* or URLSessionTransferSizeUnknown if it is not possible
* to know how many bytes will be transferred.
*/
/// Number of body bytes already received
open internal(set) var countOfBytesReceived: Int64 {
get {
return self.syncQ.sync { return self._countOfBytesReceived }
}
set {
self.syncQ.sync { self._countOfBytesReceived = newValue }
}
}
fileprivate var _countOfBytesReceived: Int64 = 0
/// Number of body bytes already sent */
open internal(set) var countOfBytesSent: Int64 {
get {
return self.syncQ.sync { return self._countOfBytesSent }
}
set {
self.syncQ.sync { self._countOfBytesSent = newValue }
}
}
fileprivate var _countOfBytesSent: Int64 = 0
/// Number of body bytes we expect to send, derived from the Content-Length of the HTTP request */
open internal(set) var countOfBytesExpectedToSend: Int64 = 0
/// Number of byte bytes we expect to receive, usually derived from the Content-Length header of an HTTP response. */
open internal(set) var countOfBytesExpectedToReceive: Int64 = 0
/// The taskDescription property is available for the developer to
/// provide a descriptive label for the task.
open var taskDescription: String?
/* -cancel returns immediately, but marks a task as being canceled.
* The task will signal -URLSession:task:didCompleteWithError: with an
* error value of { NSURLErrorDomain, NSURLErrorCancelled }. In some
* cases, the task may signal other work before it acknowledges the
* cancelation. -cancel may be sent to a task that has been suspended.
*/
open func cancel() {
workQueue.sync {
guard self.state == .running || self.state == .suspended else { return }
self.state = .canceling
self.workQueue.async {
let urlError = URLError(_nsError: NSError(domain: NSURLErrorDomain, code: NSURLErrorCancelled, userInfo: nil))
self.error = urlError
self._protocol.stopLoading()
self._protocol.client?.urlProtocol(self._protocol, didFailWithError: urlError)
}
}
}
/*
* The current state of the task within the session.
*/
open var state: URLSessionTask.State {
get {
return self.syncQ.sync { self._state }
}
set {
self.syncQ.sync { self._state = newValue }
}
}
fileprivate var _state: URLSessionTask.State = .suspended
/*
* The error, if any, delivered via -URLSession:task:didCompleteWithError:
* This property will be nil in the event that no error occured.
*/
/*@NSCopying*/ open internal(set) var error: Error?
/// Suspend the task.
///
/// Suspending a task will prevent the URLSession from continuing to
/// load data. There may still be delegate calls made on behalf of
/// this task (for instance, to report data received while suspending)
/// but no further transmissions will be made on behalf of the task
/// until -resume is sent. The timeout timer associated with the task
/// will be disabled while a task is suspended. -suspend and -resume are
/// nestable.
open func suspend() {
// suspend / resume is implemented simply by adding / removing the task's
// easy handle fromt he session's multi-handle.
//
// This might result in slightly different behaviour than the Darwin Foundation
// implementation, but it'll be difficult to get complete parity anyhow.
// Too many things depend on timeout on the wire etc.
//
// TODO: It may be worth looking into starting over a task that gets
// resumed. The Darwin Foundation documentation states that that's what
// it does for anything but download tasks.
// We perform the increment and call to `updateTaskState()`
// synchronous, to make sure the `state` is updated when this method
// returns, but the actual suspend will be done asynchronous to avoid
// dead-locks.
workQueue.sync {
self.suspendCount += 1
guard self.suspendCount < Int.max else { fatalError("Task suspended too many times \(Int.max).") }
self.updateTaskState()
if self.suspendCount == 1 {
self.workQueue.async {
self._protocol.stopLoading()
}
}
}
}
/// Resume the task.
///
/// - SeeAlso: `suspend()`
open func resume() {
workQueue.sync {
self.suspendCount -= 1
guard 0 <= self.suspendCount else { fatalError("Resuming a task that's not suspended. Calls to resume() / suspend() need to be matched.") }
self.updateTaskState()
if self.suspendCount == 0 {
self.workQueue.async {
self._protocol.startLoading()
}
}
}
}
/// The priority of the task.
///
/// Sets a scaling factor for the priority of the task. The scaling factor is a
/// value between 0.0 and 1.0 (inclusive), where 0.0 is considered the lowest
/// priority and 1.0 is considered the highest.
///
/// The priority is a hint and not a hard requirement of task performance. The
/// priority of a task may be changed using this API at any time, but not all
/// protocols support this; in these cases, the last priority that took effect
/// will be used.
///
/// If no priority is specified, the task will operate with the default priority
/// as defined by the constant URLSessionTask.defaultPriority. Two additional
/// priority levels are provided: URLSessionTask.lowPriority and
/// URLSessionTask.highPriority, but use is not restricted to these.
open var priority: Float {
get {
return self.workQueue.sync { return self._priority }
}
set {
self.workQueue.sync { self._priority = newValue }
}
}
fileprivate var _priority: Float = URLSessionTask.defaultPriority
}
extension URLSessionTask {
public enum State : Int {
/// The task is currently being serviced by the session
case running
case suspended
/// The task has been told to cancel. The session will receive a URLSession:task:didCompleteWithError: message.
case canceling
/// The task has completed and the session will receive no more delegate notifications
case completed
}
}
extension URLSessionTask : ProgressReporting {
public var progress: Progress {
NSUnimplemented()
}
}
internal extension URLSessionTask {
/// Updates the (public) state based on private / internal state.
///
/// - Note: This must be called on the `workQueue`.
internal func updateTaskState() {
func calculateState() -> URLSessionTask.State {
if suspendCount == 0 {
return .running
} else {
return .suspended
}
}
state = calculateState()
}
}
internal extension URLSessionTask {
enum _Body {
case none
case data(DispatchData)
/// Body data is read from the given file URL
case file(URL)
case stream(InputStream)
}
}
internal extension URLSessionTask._Body {
enum _Error : Error {
case fileForBodyDataNotFound
}
/// - Returns: The body length, or `nil` for no body (e.g. `GET` request).
func getBodyLength() throws -> UInt64? {
switch self {
case .none:
return 0
case .data(let d):
return UInt64(d.count)
/// Body data is read from the given file URL
case .file(let fileURL):
guard let s = try FileManager.default.attributesOfItem(atPath: fileURL.path)[.size] as? NSNumber else {
throw _Error.fileForBodyDataNotFound
}
return s.uint64Value
case .stream:
return nil
}
}
}
fileprivate func errorCode(fileSystemError error: Error) -> Int {
func fromCocoaErrorCode(_ code: Int) -> Int {
switch code {
case CocoaError.fileReadNoSuchFile.rawValue:
return NSURLErrorFileDoesNotExist
case CocoaError.fileReadNoPermission.rawValue:
return NSURLErrorNoPermissionsToReadFile
default:
return NSURLErrorUnknown
}
}
switch error {
case let e as NSError where e.domain == NSCocoaErrorDomain:
return fromCocoaErrorCode(e.code)
default:
return NSURLErrorUnknown
}
}
public extension URLSessionTask {
/// The default URL session task priority, used implicitly for any task you
/// have not prioritized. The floating point value of this constant is 0.5.
public static let defaultPriority: Float = 0.5
/// A low URL session task priority, with a floating point value above the
/// minimum of 0 and below the default value.
public static let lowPriority: Float = 0.25
/// A high URL session task priority, with a floating point value above the
/// default value and below the maximum of 1.0.
public static let highPriority: Float = 0.75
}
/*
* An URLSessionDataTask does not provide any additional
* functionality over an URLSessionTask and its presence is merely
* to provide lexical differentiation from download and upload tasks.
*/
open class URLSessionDataTask : URLSessionTask {
}
/*
* An URLSessionUploadTask does not currently provide any additional
* functionality over an URLSessionDataTask. All delegate messages
* that may be sent referencing an URLSessionDataTask equally apply
* to URLSessionUploadTasks.
*/
open class URLSessionUploadTask : URLSessionDataTask {
}
/*
* URLSessionDownloadTask is a task that represents a download to
* local storage.
*/
open class URLSessionDownloadTask : URLSessionTask {
internal var fileLength = -1.0
/* Cancel the download (and calls the superclass -cancel). If
* conditions will allow for resuming the download in the future, the
* callback will be called with an opaque data blob, which may be used
* with -downloadTaskWithResumeData: to attempt to resume the download.
* If resume data cannot be created, the completion handler will be
* called with nil resumeData.
*/
open func cancel(byProducingResumeData completionHandler: @escaping (Data?) -> Void) { NSUnimplemented() }
}
/*
* An URLSessionStreamTask provides an interface to perform reads
* and writes to a TCP/IP stream created via URLSession. This task
* may be explicitly created from an URLSession, or created as a
* result of the appropriate disposition response to a
* -URLSession:dataTask:didReceiveResponse: delegate message.
*
* URLSessionStreamTask can be used to perform asynchronous reads
* and writes. Reads and writes are enquened and executed serially,
* with the completion handler being invoked on the sessions delegate
* queuee. If an error occurs, or the task is canceled, all
* outstanding read and write calls will have their completion
* handlers invoked with an appropriate error.
*
* It is also possible to create InputStream and OutputStream
* instances from an URLSessionTask by sending
* -captureStreams to the task. All outstanding read and writess are
* completed before the streams are created. Once the streams are
* delivered to the session delegate, the task is considered complete
* and will receive no more messsages. These streams are
* disassociated from the underlying session.
*/
open class URLSessionStreamTask : URLSessionTask {
/* Read minBytes, or at most maxBytes bytes and invoke the completion
* handler on the sessions delegate queue with the data or an error.
* If an error occurs, any outstanding reads will also fail, and new
* read requests will error out immediately.
*/
open func readData(ofMinLength minBytes: Int, maxLength maxBytes: Int, timeout: TimeInterval, completionHandler: @escaping (Data?, Bool, Error?) -> Void) { NSUnimplemented() }
/* Write the data completely to the underlying socket. If all the
* bytes have not been written by the timeout, a timeout error will
* occur. Note that invocation of the completion handler does not
* guarantee that the remote side has received all the bytes, only
* that they have been written to the kernel. */
open func write(_ data: Data, timeout: TimeInterval, completionHandler: @escaping (Error?) -> Void) { NSUnimplemented() }
/* -captureStreams completes any already enqueued reads
* and writes, and then invokes the
* URLSession:streamTask:didBecomeInputStream:outputStream: delegate
* message. When that message is received, the task object is
* considered completed and will not receive any more delegate
* messages. */
open func captureStreams() { NSUnimplemented() }
/* Enqueue a request to close the write end of the underlying socket.
* All outstanding IO will complete before the write side of the
* socket is closed. The server, however, may continue to write bytes
* back to the client, so best practice is to continue reading from
* the server until you receive EOF.
*/
open func closeWrite() { NSUnimplemented() }
/* Enqueue a request to close the read side of the underlying socket.
* All outstanding IO will complete before the read side is closed.
* You may continue writing to the server.
*/
open func closeRead() { NSUnimplemented() }
/*
* Begin encrypted handshake. The hanshake begins after all pending
* IO has completed. TLS authentication callbacks are sent to the
* session's -URLSession:task:didReceiveChallenge:completionHandler:
*/
open func startSecureConnection() { NSUnimplemented() }
/*
* Cleanly close a secure connection after all pending secure IO has
* completed.
*/
open func stopSecureConnection() { NSUnimplemented() }
}
/* Key in the userInfo dictionary of an NSError received during a failed download. */
public let URLSessionDownloadTaskResumeData: String = "NSURLSessionDownloadTaskResumeData"
extension _ProtocolClient : URLProtocolClient {
func urlProtocol(_ protocol: URLProtocol, didReceive response: URLResponse, cacheStoragePolicy policy: URLCache.StoragePolicy) {
guard let task = `protocol`.task else { fatalError("Received response, but there's no task.") }
task.response = response
let session = task.session as! URLSession
guard let dataTask = task as? URLSessionDataTask else { return }
switch session.behaviour(for: task) {
case .taskDelegate(let delegate as URLSessionDataDelegate):
session.delegateQueue.addOperation {
delegate.urlSession(session, dataTask: dataTask, didReceive: response, completionHandler: { _ in
URLSession.printDebug("warning: Ignoring disposition from completion handler.")
})
}
case .noDelegate, .taskDelegate, .dataCompletionHandler, .downloadCompletionHandler:
break
}
}
func urlProtocolDidFinishLoading(_ protocol: URLProtocol) {
guard let task = `protocol`.task else { fatalError() }
guard let session = task.session as? URLSession else { fatalError() }
switch session.behaviour(for: task) {
case .taskDelegate(let delegate):
if let downloadDelegate = delegate as? URLSessionDownloadDelegate, let downloadTask = task as? URLSessionDownloadTask {
session.delegateQueue.addOperation {
downloadDelegate.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: `protocol`.properties[URLProtocol._PropertyKey.temporaryFileURL] as! URL)
}
}
session.delegateQueue.addOperation {
delegate.urlSession(session, task: task, didCompleteWithError: nil)
task.state = .completed
task.workQueue.async {
session.taskRegistry.remove(task)
}
}
case .noDelegate:
task.state = .completed
session.taskRegistry.remove(task)
case .dataCompletionHandler(let completion):
session.delegateQueue.addOperation {
completion(`protocol`.properties[URLProtocol._PropertyKey.responseData] as? Data ?? Data(), task.response, nil)
task.state = .completed
session.taskRegistry.remove(task)
}
case .downloadCompletionHandler(let completion):
session.delegateQueue.addOperation {
completion(`protocol`.properties[URLProtocol._PropertyKey.temporaryFileURL] as? URL, task.response, nil)
task.state = .completed
session.taskRegistry.remove(task)
}
}
}
func urlProtocol(_ protocol: URLProtocol, didCancel challenge: URLAuthenticationChallenge) {
NSUnimplemented()
}
func urlProtocol(_ protocol: URLProtocol, didReceive challenge: URLAuthenticationChallenge) {
NSUnimplemented()
}
func urlProtocol(_ protocol: URLProtocol, didLoad data: Data) {
`protocol`.properties[.responseData] = data
guard let task = `protocol`.task else { fatalError() }
guard let session = task.session as? URLSession else { fatalError() }
switch session.behaviour(for: task) {
case .taskDelegate(let delegate):
let dataDelegate = delegate as? URLSessionDataDelegate
let dataTask = task as? URLSessionDataTask
session.delegateQueue.addOperation {
dataDelegate?.urlSession(session, dataTask: dataTask!, didReceive: data)
}
default: return
}
}
func urlProtocol(_ protocol: URLProtocol, didFailWithError error: Error) {
guard let task = `protocol`.task else { fatalError() }
guard let session = task.session as? URLSession else { fatalError() }
switch session.behaviour(for: task) {
case .taskDelegate(let delegate):
session.delegateQueue.addOperation {
delegate.urlSession(session, task: task, didCompleteWithError: error as Error)
task.state = .completed
task.workQueue.async {
session.taskRegistry.remove(task)
}
}
case .noDelegate:
task.state = .completed
session.taskRegistry.remove(task)
case .dataCompletionHandler(let completion):
session.delegateQueue.addOperation {
completion(nil, nil, error)
task.state = .completed
task.workQueue.async {
session.taskRegistry.remove(task)
}
}
case .downloadCompletionHandler(let completion):
session.delegateQueue.addOperation {
completion(nil, nil, error)
task.state = .completed
session.taskRegistry.remove(task)
}
}
}
func urlProtocol(_ protocol: URLProtocol, cachedResponseIsValid cachedResponse: CachedURLResponse) {
NSUnimplemented()
}
func urlProtocol(_ protocol: URLProtocol, wasRedirectedTo request: URLRequest, redirectResponse: URLResponse) {
NSUnimplemented()
}
}
extension URLProtocol {
enum _PropertyKey: String {
case responseData
case temporaryFileURL
}
}
| apache-2.0 | b65b99cf997e1ebc385f2d997726a22b | 40.235105 | 182 | 0.646972 | 5.201503 | false | false | false | false |
mobgeek/swift | Swift em 4 Semanas/Playgrounds/Semana 2/3-Funções.playground/Contents.swift | 2 | 3514 | // Playground - noun: a place where people can play
import UIKit
// Funções
func cancelaPropaganda(nomeServico: String) -> String {
switch nomeServico {
case "Vivo":
return "Enviando a mensagem SAIR a 457 (VIVO)"
case "Claro":
return "Enviando a mensagem SAIR a 888 (CLARO)"
case "Oi":
return "Enviando a mensagem SAIR a 55555 (OI)"
case "TIM":
return "Enviando a mensagem SAIR a 4112 (TIM)"
default:
return "Será que vc digitou corretamente a operadora?"
}
}
var cancelamento = cancelaPropaganda("Vivo")
// Múltiplos parâmetros
func media(n1: Double, n2: Double) -> Double {
return (n1 + n2) / 2
}
// Sem parâmetros
func confirma() -> String {
return "Ahan..."
}
confirma()
// Valores de Retorno
// Sem valores de retorno: tipo de retorno é VOID.
func digaOcupado(nomePessoa: String) {
println("To ocupado \(nomePessoa). Te ligo mais tarde!")
}
// Múltiplos valores de retorno.
func contar(string: String) -> (vogais: Int, consoantes: Int, outros: Int) {
var vogais = 0 , consoantes = 0, outros = 0
// classificação e incrementos das variáveis
return (vogais, consoantes, outros)
}
// Nomes locais de parâmetro
func juntar(s1: String, s2: String, comJunção junção: String) -> String {
return s1 + junção + s2
}
juntar("flamengo", "vasco", comJunção:" x ")
// Nomes externos curtos de Parâmetro:
// #
func possuiLetra(#string: String, #letraEncontrar: Character) -> Bool {
for letra in string {
if letra == letraEncontrar {
return true
}
}
return false
}
var temA = possuiLetra(string: "Oi Ana!", letraEncontrar: "A")
// Valores Padrão de Parâmetros
func novaJuntar(s1: String, s2: String, junção: String = " x ") -> String {
return s1 + junção + s2
}
novaJuntar("Flamengo", "Vasco", junção: " e ")
// Parâmetros "Variadic"
func chamarIntensidade(var nome: String, intensidade: Int) -> String {
for _ in 1...intensidade {
nome += "!"
}
return nome
}
chamarIntensidade("Maria", 7)
// Parâmetros In-Out
func trocaAssento(inout a1: String, inout a2: String) {
let assentoTemporario = a1
a1 = a2
a2 = assentoTemporario
}
var poltronaJoao = "17A"
var poltronaMarcos = "18B"
trocaAssento(&poltronaJoao, &poltronaMarcos)
poltronaJoao
poltronaMarcos
// Tipo Função
func adicionaInteiros(a: Int, b: Int) -> Int // (Int, Int) -> Int
{
return a + b
}
adicionaInteiros(3, 3)
func digaOi() { println("Oi")} // ()->() Void
digaOi()
var funcaoMatematica: (Int, Int) -> Int = adicionaInteiros
funcaoMatematica(2,5)
func resultado(funcaoMatematica: (Int, Int) -> Int, a: Int, b: Int) -> String
{
return "Resultado: \(funcaoMatematica(a,b))"
}
resultado(adicionaInteiros, 4, 6)
// Funções Aninhadas
func selecionaOperação(comDesconto: Bool) -> (Double) -> Double
{
func totalComDesconto(valor: Double) -> Double
{
return valor * 0.8 * 1.2
}
func totalSemDesconto(valor: Double) -> Double
{
return valor * 1.2
}
return comDesconto ? totalComDesconto : totalSemDesconto
}
var total = selecionaOperação(false)
total(10)
| mit | be6c23c9c3c2ab0dd9f43450c897a4b6 | 11.918216 | 77 | 0.595108 | 2.944915 | false | false | false | false |
imex94/KCLTech-iOS-Sessions-2014-2015 | session202/session202/SignupViewController.swift | 1 | 1571 | //
// SignupViewController.swift
// session202
//
// Created by Alex Telek on 10/11/2014.
// Copyright (c) 2014 KCLTech. All rights reserved.
//
import UIKit
class SignupViewController: UIViewController {
@IBOutlet var txtUsername: UITextField!
@IBOutlet var txtPassword: UITextField!
@IBOutlet var txtEmail: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func signup(sender: AnyObject) {
if let user = Store.loadData(txtUsername.text) {
println("User already exist")
} else {
performSegueWithIdentifier("signup", sender: self)
}
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
let nav = segue.destinationViewController as! UINavigationController
let nextView = nav.topViewController as! NotesTableViewController
let newUser = User(username: txtUsername.text, password: txtPassword.text, email: txtEmail.text)
nextView.currentUser = newUser
Store.saveData(newUser)
}
}
| mit | 0ec99443c06e0e954cb8f9a7baa01546 | 31.729167 | 106 | 0.681095 | 5.019169 | false | false | false | false |
bm842/Threads | Sources/Timespec.swift | 1 | 3699 | /*
The MIT License (MIT)
Copyright (c) 2016 Bertrand Marlier
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE
*/
import Foundation
public typealias Duration = UInt64
public let NanoSeconds : Duration = 1
public let MicroSeconds : Duration = 1_000 * NanoSeconds
public let MilliSeconds : Duration = 1_000 * MicroSeconds
public let Seconds : Duration = 1_000 * MilliSeconds
public let Infinite : Duration = 100*365*24*3600 * Seconds
extension Duration
{
var fullSeconds: Int { return Int(self / 1_000_000_000) }
var remainingNanoSeconds: Int { return Int(self % 1_000_000_000) }
}
/*public struct Duration
{
static let Infinite = Duration(seconds: 100*365*24*3600)
let nanoSeconds: UInt64
public init(nanoSeconds value: UInt64)
{
nanoSeconds = value
}
public init(milliSeconds value: UInt64)
{
nanoSeconds = value * 1_000_000
}
public init(seconds value: UInt64)
{
nanoSeconds = value * 1_000_000_000
}
}*/
public struct Timespec
{
/*public static func never() -> Timespec
{
return Timespec(relative: Infinite)
}
public static func now() -> Timespec
{
var timeVal = timeval()
gettimeofday(&timeVal, nil)
return Timespec(seconds: timeVal.tv_sec, nanoSeconds: (Int(timeVal.tv_usec) * 1000))
}*/
public static func zero() -> Timespec
{
return Timespec(seconds: 0, nanoSeconds: 0)
}
var posixTimespec = timespec()
init()
{
}
public init(seconds: Int, nanoSeconds: Int)
{
posixTimespec.tv_sec = seconds
posixTimespec.tv_nsec = nanoSeconds
}
public init(absolute duration: Duration)
{
posixTimespec.tv_sec = duration.fullSeconds
posixTimespec.tv_nsec = duration.remainingNanoSeconds
}
public init(relative duration: Duration)
{
var timeVal = timeval()
gettimeofday(&timeVal, nil)
let nanoSeconds: Int = Int(timeVal.tv_usec) * 1000 + Int(duration.remainingNanoSeconds)
let seconds: Int = timeVal.tv_sec + Int(duration.fullSeconds) + nanoSeconds / 1_000_000_000
posixTimespec.tv_sec = seconds
posixTimespec.tv_nsec = nanoSeconds % 1_000_000_000
}
/*public func delay(value: Duration) -> Timespec
{
var tv_sec = posixTimespec.tv_sec + Int(value.fullSeconds)
let tv_nsec = posixTimespec.tv_nsec + Int(value.remainingNanoSeconds)
tv_sec += tv_nsec / 1_000_000_000
return Timespec(seconds: tv_sec, nanoSeconds: tv_nsec % 1_000_000_000)
}*/
}
| mit | 04ceeba9a4d14a2522ba2bfe18e3186b | 28.592 | 99 | 0.664234 | 4.15618 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.