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
wangyaqing/LeetCode-swift
Solutions/19. Remove Nth Node From End of List.playground/Contents.swift
1
937
import UIKit public class ListNode { public var val: Int public var next: ListNode? public init(_ val: Int) { self.val = val self.next = nil } } class Solution { func removeNthFromEnd(_ head: ListNode?, _ n: Int) -> ListNode? { let pre:ListNode? = ListNode(0) pre?.next = head var lastNode = pre var nNode = pre var count = -1 while lastNode != nil { if count < n { count += 1 } else { nNode = nNode?.next } lastNode = lastNode?.next } nNode?.next = nNode?.next?.next return pre?.next } } var lastNode: ListNode? for i in 0...0 { let node = ListNode(i) node.next = lastNode lastNode = node } var node = Solution().removeNthFromEnd(lastNode, 1) while node != nil { print(node!.val) node = node?.next }
mit
765873f9aa1dcff75ccdafc90d89077c
18.93617
69
0.510139
3.808943
false
false
false
false
malcommac/Hydra
Sources/Hydra/Promise+Timeout.swift
1
2776
/* * Hydra * Fullfeatured lightweight Promise & Await Library for Swift * * Created by: Daniele Margutti * Email: hello@danielemargutti.com * Web: http://www.danielemargutti.com * Twitter: @danielemargutti * * Copyright © 2017 Daniele Margutti * * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ import Foundation public extension Promise { /// Reject the receiving Promise if it does not resolve or reject after a given number of seconds /// /// - Parameters: /// - context: context in which the nextPromise will be executed (if not specified `background` is used) /// - timeout: timeout expressed in seconds /// - error: error to report, if nil `PromiseError.timeout` is used instead /// - Returns: promise func timeout(in context: Context? = nil, timeout: TimeInterval, error: Error? = nil) -> Promise<Value> { let ctx = context ?? .background let nextPromise = Promise<Value>(in: ctx, token: self.invalidationToken) { resolve, reject, operation in // Dispatch the result of self promise to the nextPromise // If self promise does not resolve or reject in given amount of time // nextPromise is rejected with passed error or generic timeout error // and any other result of the self promise is ignored let timer = DispatchTimerWrapper(queue: ctx.queue) timer.setEventHandler { let errorToPass = (error ?? PromiseError.timeout) reject(errorToPass) } timer.scheduleOneShot(deadline: .now() + timeout) timer.resume() // Observe resolve self.add(onResolve: { v in resolve(v) // resolve with value timer.cancel() // cancel timeout timer and release promise }, onReject: reject, onCancel: operation.cancel) } nextPromise.runBody() self.runBody() return nextPromise } }
mit
8970be790dd6a734dbcbbb430deff56e
38.084507
107
0.736577
4.051095
false
false
false
false
rajmuhar/iosbridge-rottentomatoes
RottenTomatoesSwift/RottenTomatoesSwift/Downloader.swift
7
1604
// // Downloader.swift // RottenTomatoesSwift // // Created by Jeffrey Bergier on 9/12/15. // Copyright © 2015 MobileBridge. All rights reserved. // import Foundation protocol DownloaderDelegate: class { func downloadFinishedForURL(finishedURL: NSURL) } class Downloader { weak var delegate: DownloaderDelegate? private let session: NSURLSession = { let config = NSURLSessionConfiguration.defaultSessionConfiguration() return NSURLSession(configuration: config) }() private var downloaded = [NSURL : NSData]() func beginDownloadingURL(downloadURL: NSURL) { self.session.dataTaskWithRequest(NSURLRequest(URL: downloadURL)) { (downloadedData, response, error) in guard let downloadedData = downloadedData else { NSLog("Downloader: Downloaded Data was NIL for URL: \(downloadURL)") return } guard let response = response as? NSHTTPURLResponse else { NSLog("Downloader: Response was not an HTTP Response for URL: \(downloadURL)") return } switch response.statusCode { case 200: self.downloaded[downloadURL] = downloadedData self.delegate?.downloadFinishedForURL(downloadURL) default: NSLog("Downloader: Received Response Code: \(response.statusCode) for URL: \(downloadURL)") } }.resume() } func dataForURL(requestURL: NSURL) -> NSData? { return self.downloaded[requestURL] } }
mit
00add93a3b347e4a0b27f0d6c32831b7
31.06
111
0.623206
5.307947
false
true
false
false
barteljan/VISPER
Example/VISPER-Wireframe-Tests/Mocks/MockRoutingHandlerContainer.swift
1
2505
// // MockRoutingHandlerContainer.swift // VISPER-Wireframe_Example // // Created by bartel on 02.12.17. // Copyright © 2017 CocoaPods. All rights reserved. // import Foundation import VISPER_Wireframe import VISPER_Core class MockRoutingHandlerContainer: NSObject, RoutingHandlerContainer { var invokedAdd = false var invokedAddCount = 0 var invokedAddParameters: (priority: Int, Void)? var invokedAddResponsibleForParam: ((_ routeResult: RouteResult) -> Bool)? var invokedAddHandlerParam: ((_ routeResult: RouteResult) -> Void)? var invokedAddParametersList = [(priority: Int, Void)]() var stubbedAddResponsibleForResult: (RouteResult, Void)? var stubbedAddHandlerResult: (RouteResult, Void)? func add(priority: Int, responsibleFor: @escaping (_ routeResult: RouteResult) -> Bool, handler: @escaping RoutingHandler) { invokedAdd = true invokedAddCount += 1 invokedAddResponsibleForParam = responsibleFor invokedAddHandlerParam = handler invokedAddParameters = (priority, ()) invokedAddParametersList.append((priority, ())) } var invokedPriorityOfHighestResponsibleProvider = false var invokedPriorityOfHighestResponsibleProviderCount = 0 var invokedPriorityOfHighestResponsibleProviderParameters: (routeResult: RouteResult, Void)? var invokedPriorityOfHighestResponsibleProviderParametersList = [(routeResult: RouteResult, Void)]() var stubbedPriorityOfHighestResponsibleProviderResult: Int! func priorityOfHighestResponsibleProvider(routeResult: RouteResult) -> Int? { invokedPriorityOfHighestResponsibleProvider = true invokedPriorityOfHighestResponsibleProviderCount += 1 invokedPriorityOfHighestResponsibleProviderParameters = (routeResult, ()) invokedPriorityOfHighestResponsibleProviderParametersList.append((routeResult, ())) return stubbedPriorityOfHighestResponsibleProviderResult } var invokedHandler = false var invokedHandlerCount = 0 var invokedHandlerParameters: (routeResult: RouteResult, Void)? var invokedHandlerParametersList = [(routeResult: RouteResult, Void)]() var stubbedHandlerResult: (RoutingHandler)! func handler(routeResult: RouteResult) -> RoutingHandler? { invokedHandler = true invokedHandlerCount += 1 invokedHandlerParameters = (routeResult, ()) invokedHandlerParametersList.append((routeResult, ())) return stubbedHandlerResult } }
mit
92d301d4820c6a69c5a80541b6780821
40.733333
128
0.748003
5.260504
false
false
false
false
dflax/Anagrams
Anagrams/TileView.swift
1
2895
// // TileView.swift // Anagrams // // Created by Daniel Flax on 4/29/15. // Copyright (c) 2015 Caroline. All rights reserved. // import UIKit // Delegate protocol to inform Game Controller that tile has dropped. protocol TileDragDelegateProtocol { func tileView(tileView: TileView, didDragToPoint: CGPoint) } //1 class TileView:UIImageView { // Touch Offsets private var xOffset: CGFloat = 0.0 private var yOffset: CGFloat = 0.0 //2 var letter: Character //3 var isMatched: Bool = false // Delegate protocol property var dragDelegate: TileDragDelegateProtocol? // 4 this should never be called required init(coder aDecoder:NSCoder) { fatalError("use init(letter:, sideLength:") } //5 create a new tile for a given letter init(letter:Character, sideLength:CGFloat) { self.letter = letter // the tile background let image = UIImage(named: "tile")! // superclass initializer // references to superview's "self" must take place after super.init super.init(image:image) // Enable touch movement self.userInteractionEnabled = true // 6 resize the tile let scale = sideLength / image.size.width self.frame = CGRect(x: 0, y: 0, width: image.size.width * scale, height: image.size.height * scale) //add a letter on top let letterLabel = UILabel(frame: self.bounds) letterLabel.textAlignment = NSTextAlignment.Center letterLabel.textColor = UIColor.whiteColor() letterLabel.backgroundColor = UIColor.clearColor() letterLabel.text = String(letter).uppercaseString letterLabel.font = UIFont(name: "Verdana-Bold", size: 78.0*scale) self.addSubview(letterLabel) } // Generate randomness in the tiles func randomize() { // 1 // set random rotation of the tile // anywhere between -0.2 and 0.3 radians let rotation = CGFloat(randomNumber(minX:0, maxX:50)) / 100.0 - 0.2 self.transform = CGAffineTransformMakeRotation(rotation) // 2 // move randomly up or down -10 to 0 points let yOffset = CGFloat(randomNumber(minX: 0, maxX: TileYOffset) - Int(TileYOffset)) self.center = CGPointMake(self.center.x, self.center.y + yOffset) } //1 override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { if let touch = touches.first as? UITouch { let point = touch.locationInView(self.superview) xOffset = point.x - self.center.x yOffset = point.y - self.center.y } } //2 override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) { if let touch = touches.first as? UITouch { let point = touch.locationInView(self.superview) self.center = CGPointMake(point.x - xOffset, point.y - yOffset) } } //3 override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) { self.touchesMoved(touches, withEvent: event) // Inform the delegate that the drag and drop has completed dragDelegate?.tileView(self, didDragToPoint: self.center) } }
mit
e6739246768cc4a621701902e615a743
26.056075
101
0.720898
3.560886
false
false
false
false
xu6148152/binea_project_for_ios
ListerforAppleWatchiOSandOSX/Swift/ListerOSX/AppDelegate.swift
1
2899
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: The application delegate. */ import Cocoa import ListerKit @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { // MARK: Properties @IBOutlet weak var todayListMenuItem: NSMenuItem! var ubiquityIdentityDidChangeNotificationToken: NSObjectProtocol? // MARK: NSApplicationDelegate func applicationDidFinishLaunching(notification: NSNotification) { AppConfiguration.sharedConfiguration.runHandlerOnFirstLaunch { // If iCloud is enabled and it's the first launch, we'll show the Today document initially. if AppConfiguration.sharedConfiguration.isCloudAvailable { // Make sure that no other documents are visible except for the Today document. NSDocumentController.sharedDocumentController().closeAllDocumentsWithDelegate(nil, didCloseAllSelector: nil, contextInfo: nil) self.openTodayDocument() } } // Update the menu item at app launch. updateTodayListMenuItemForCloudAvailability() ubiquityIdentityDidChangeNotificationToken = NSNotificationCenter.defaultCenter().addObserverForName(NSUbiquityIdentityDidChangeNotification, object: nil, queue: nil) { [weak self] _ in // Update the menu item once the iCloud account changes. self?.updateTodayListMenuItemForCloudAvailability() return } } // MARK: IBActions /** Note that there are two possibile callers for this method. The first is the application delegate if it's the first launch. The other possibility is if you use the keyboard shortcut (Command-T) to open your Today document. */ @IBAction func openTodayDocument(_: AnyObject? = nil) { TodayListManager.fetchTodayDocumentURLWithCompletionHandler { url in if let url = url { dispatch_async(dispatch_get_main_queue()) { let documentController = NSDocumentController.sharedDocumentController() as NSDocumentController documentController.openDocumentWithContentsOfURL(url, display: true) { _ in // Configuration of the document can go here... } } } } } // MARK: Convenience func updateTodayListMenuItemForCloudAvailability() { if AppConfiguration.sharedConfiguration.isCloudAvailable { todayListMenuItem.action = "openTodayDocument:" todayListMenuItem.target = self } else { todayListMenuItem.action = nil todayListMenuItem.target = nil } } }
mit
bbfb45544f2c692de87a86f4619f5d03
35.670886
193
0.645841
5.852525
false
true
false
false
SuPair/firefox-ios
Client/Frontend/Browser/PrintHelper.swift
16
968
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import WebKit class PrintHelper: TabContentScript { fileprivate weak var tab: Tab? class func name() -> String { return "PrintHelper" } required init(tab: Tab) { self.tab = tab } func scriptMessageHandlerName() -> String? { return "printHandler" } func userContentController(_ userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) { if let tab = tab, let webView = tab.webView { let printController = UIPrintInteractionController.shared printController.printFormatter = webView.viewPrintFormatter() printController.present(animated: true, completionHandler: nil) } } }
mpl-2.0
80699f12c188962494ada6ec2205d4f5
30.225806
132
0.683884
4.792079
false
false
false
false
codergaolf/DouYuTV
DouYuTV/DouYuTV/Classes/Tools/Extension/UIBarButtonItem-Extension.swift
1
1357
// // UIBarButtonItem-Extension.swift // DouYuTV // // Created by 高立发 on 2016/11/12. // Copyright © 2016年 GG. All rights reserved. // import UIKit extension UIBarButtonItem { /* class func creatItem(imgName : String, highLighted : String, size : CGSize) -> UIBarButtonItem { let btn = UIButton() btn.setImage(UIImage(named:imgName), for: .normal) btn.setImage(UIImage(named:highLighted), for: .selected) btn.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: size) return UIBarButtonItem(customView: btn) } */ //便利构造函数 : 1>必须以convenience开头 2>在构造函数中必须明确调用一个设计的构造函数(self) convenience init(imgName : String, highLighted : String = "", size : CGSize = CGSize.zero) { //1,创建UIButton let btn = UIButton() //2,设置button图片 btn.setImage(UIImage(named:imgName), for: .normal) if highLighted != "" { btn.setImage(UIImage(named:highLighted), for: .selected) } //3,设置button尺寸 if size != CGSize.zero { btn.frame = CGRect(origin: CGPoint.zero, size: size) } else { btn.sizeToFit() } self.init(customView : btn) } }
mit
f71783229e1b1930a55944b99bb123e3
26.478261
100
0.56962
3.95
false
false
false
false
Vadim-Yelagin/ImageLoading
ImageLoading/FadeInImageLoadingView.swift
1
868
// // FadeInImageLoadingView.swift // // Created by Vadim Yelagin on 20/06/15. // Copyright (c) 2015 Fueled. All rights reserved. // import Foundation import UIKit open class FadeInImageLoadingView: ImageLoadingView { open override func transition( from oldState: Task.State, ofTask oldTask: Task?, to newState: Task.State, ofTask newTask: Task?) { var fade = false if let oldTask = oldTask, let newTask = newTask , oldTask === newTask { switch (oldState, newState) { case (.loading, .success): fade = true default: break } } func callSuper() { super.transition(from: oldState, ofTask: oldTask, to: newState, ofTask: newTask) } if fade { UIView.transition( with: self, duration: 0.25, options: .transitionCrossDissolve, animations: callSuper, completion: nil) } else { callSuper() } } }
mit
4e2b93f5c0469775b47eb6d88e2e8507
20.170732
83
0.669355
3.214815
false
false
false
false
jm-schaeffer/JMWebImageView
JMWebImageView/JMWebImageView.swift
1
5598
// // JMWebImageView.swift // JMWebImageView // // Copyright (c) 2016 J.M. Schaeffer // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit class JMWebImageView: UIImageView { private weak var loadingView: UIView? weak var delegate: JMWebImageViewDelegate? var url: NSURL? { didSet { if let oldValue = oldValue where oldValue != url { WebImageDownloaderManager.sharedManager.cancel(oldValue, key: hashString) } if url == nil { setState(.Initial) } else if superview != nil { load() } } } var useCache: Bool = true var cacheDuration: NSTimeInterval = 86400 // 1 day var placeholderImage: UIImage? // Displayed when the image cannot be loaded or if the url is set to nil var hashString: String { return String(ObjectIdentifier(self).uintValue) } private func load() { guard let url = url else { return } let size = max(bounds.width, bounds.height) * UIScreen.mainScreen().scale let download = { self.setState(.Loading) WebImageDownloaderManager.sharedManager.request(url, key: self.hashString, size: size, useCache: self.useCache, cacheDuration: self.cacheDuration, completion: { error, image, progress in self.setImage(image, animated: true) }) } if useCache { WebImageCacheManager.imageForURL(url, size: size, cacheDuration: self.cacheDuration) { error, image in if let image = image where error == nil { self.setImage(image, animated: false) } else { download() } } } else { download() } } private let dissolveAnimationDuration = 0.5 private func setImage(image: UIImage?, animated: Bool) { delegate?.webImageView(self, willUpdateImage: animated, duration: dissolveAnimationDuration) UIView.transitionWithView( self, duration: animated ? dissolveAnimationDuration : 0.0, options: [.TransitionCrossDissolve], animations: { self.setState(.Complete, image: image) }, completion: { finished in self.delegate?.webImageView(self, didUpdateImage: animated) }) } // MARK: - State private enum State { case Initial case Loading case Complete } private func setState(state: State, image: UIImage? = nil) { switch state { case .Initial: self.image = placeholderImage layer.removeAllAnimations() removeLoadingView() case .Loading: self.image = nil layer.removeAllAnimations() showLoadingView() case .Complete: removeLoadingView() self.image = image ?? placeholderImage if image == nil { // When the image couldn't be loaded we need to reset the url url = nil } } } // MARK: - Loading View private func showLoadingView() { if loadingView == nil { if let loadingView = loadLoadingView() { loadingView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] loadingView.frame = CGRect(x: 0.0, y: 0.0, width: bounds.width, height: bounds.height) addSubview(loadingView) self.loadingView = loadingView } } } private func removeLoadingView() { loadingView?.removeFromSuperview() } // MARK: - Methods that can be overriden // Don't call the super implementation func loadLoadingView() -> UIView? { if bounds.width >= 30.0 && bounds.height >= 30.0 { let activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .Gray) activityIndicatorView.startAnimating() return activityIndicatorView } else { return nil } } func setProgress(progress: Float) { } } protocol JMWebImageViewDelegate: NSObjectProtocol { func webImageView(webImageView: JMWebImageView, willUpdateImage animated: Bool, duration: NSTimeInterval) func webImageView(webImageView: JMWebImageView, didUpdateImage animated: Bool) }
mit
e9473c2dc3a28834d7c2b6589b386f80
33.343558
198
0.605395
5.084469
false
false
false
false
RobotPajamas/ble113-ota-ios
ble113-ota/BaseBluetoothPeripheral.swift
1
6238
// // BaseBluetoothPeripheral.swift // ble113-ota // // Created by Suresh Joshi on 2016-06-13. // Copyright © 2016 Robot Pajamas. All rights reserved. // import LGBluetooth class BaseBluetoothPeripheral { enum StandardServices { static let deviceInformation: String = "180A"; } enum StandardCharacteristics { static let manufacturerModel: String = "2A24"; static let serialNumber: String = "2A25"; static let firmwareVersion: String = "2A26"; static let hardwareVersion: String = "2A27"; static let softwareVersion: String = "2A28"; static let manufacturerName: String = "2A29"; } var peripheral: LGPeripheral! var name: String? var rssi: Int? // Properties for the standard services var manufacturerModel: String? var serialNumber: String? var firmwareRevision: String? var hardwareRevision: String? var softwareRevision: String? var manufacturerName: String? /** * Constructor * @param peripheral LGPeripheral instance representing this device */ init(fromPeripheral peripheral: LGPeripheral) { self.peripheral = peripheral self.name = self.peripheral.name self.rssi = self.peripheral.RSSI } /** * Determines if this peripheral is currently connected or not */ func isConnected() -> Bool { return peripheral.cbPeripheral.state == .Connected } /** * Opens connection with a timeout to this device * @param timeout Timeout after which, connection will be closed (if it was in stage isConnecting) * @param callback Will be called after connection success/failure */ func connect(withTimeout timeout: UInt, callback: (NSError!) -> Void) { peripheral.connectWithTimeout(timeout, completion: callback) } /** * Disconnects from device * @param callback Will be called after disconnection success/failure */ func disconnect(callback: (NSError?) -> Void) { peripheral.disconnectWithCompletion(callback) } /** * Reads all standard BLE information from device (manufacturer, firmware, hardware, serial number, etc...) * @param callback Will be called when all information is ready (or failed to gather data) */ func readDeviceInformation(callback: () -> Void) { // Using RxSwift would be great to clean up this super messy nested block business... // self.readSoftwareRevision({ <-- not implemented in firmawre self.readManufacturerModel({ // self.readSerialNumber({ self.readFirmwareRevision({ self.readHardwareRevision({ self.readManufacturerName(callback) }) }) // }) }) } /** * Read in the manufacturer name * @param callback Will be called when the call returns with success or error */ private func readManufacturerName(callback: (() -> ())?) { let cb: LGCharacteristicReadCallback = { data, error in self.manufacturerName = String(data: data, encoding: NSUTF8StringEncoding) callback?() } LGUtils.readDataFromCharactUUID(StandardCharacteristics.manufacturerName, serviceUUID: StandardServices.deviceInformation, peripheral: peripheral, completion: cb) } /** * Read in the manufacturer model * @param callback Will be called when the call returns with success or error */ private func readManufacturerModel(callback: (() -> ())?) { let cb: LGCharacteristicReadCallback = { data, error in self.manufacturerModel = String(data: data, encoding: NSUTF8StringEncoding) callback?() } LGUtils.readDataFromCharactUUID(StandardCharacteristics.manufacturerModel, serviceUUID: StandardServices.deviceInformation, peripheral: peripheral, completion: cb) } /** * Read in the hardware revision * @param callback Will be called when the call returns with success or error */ private func readHardwareRevision(callback: (() -> ())?) { let cb: LGCharacteristicReadCallback = { data, error in self.hardwareRevision = String(data: data, encoding: NSUTF8StringEncoding) callback?() } LGUtils.readDataFromCharactUUID(StandardCharacteristics.hardwareVersion, serviceUUID: StandardServices.deviceInformation, peripheral: peripheral, completion: cb) } /** * Read in the firmware version * @param callback Will be called when the call returns with success or error */ private func readFirmwareRevision(callback: (() -> ())?) { let cb: LGCharacteristicReadCallback = { data, error in self.firmwareRevision = String(data: data, encoding: NSUTF8StringEncoding) callback?() } LGUtils.readDataFromCharactUUID(StandardCharacteristics.firmwareVersion, serviceUUID: StandardServices.deviceInformation, peripheral: peripheral, completion: cb) } /** * Read in the software version * @param callback Will be called when the call returns with success or error */ private func readSoftwareRevision(callback: (() -> ())?) { let cb: LGCharacteristicReadCallback = { data, error in self.softwareRevision = String(data: data, encoding: NSUTF8StringEncoding) callback?() } LGUtils.readDataFromCharactUUID(StandardCharacteristics.softwareVersion, serviceUUID: StandardServices.deviceInformation, peripheral: peripheral, completion: cb) } /** * Read in the serial number * @param callback Will be called when the call returns with success or error */ private func readSerialNumber(callback: (() -> ())?) { let cb: LGCharacteristicReadCallback = { data, error in self.serialNumber = String(data: data, encoding: NSUTF8StringEncoding) callback?() } LGUtils.readDataFromCharactUUID(StandardCharacteristics.serialNumber, serviceUUID: StandardServices.deviceInformation, peripheral: peripheral, completion: cb) } }
mit
4f1886b57a347e726bc27720b4464f6f
34.844828
171
0.65865
4.946075
false
false
false
false
justindaigle/grogapp-ios
GroGApp/GroGApp/DetailViewController.swift
1
4637
// // DetailViewController.swift // GroGApp // // Created by Justin Daigle on 3/26/15. // Copyright (c) 2015 Justin Daigle (.com). All rights reserved. // import UIKit class DetailViewController: UIViewController { @IBOutlet var displayNameLabel:UILabel! @IBOutlet var userNameLabel:UILabel! @IBOutlet var avaView:UIImageView! @IBOutlet var statusesLabel:UILabel! @IBOutlet var bioLabel:UILabel! @IBOutlet var locLabel:UILabel! @IBOutlet var blockButton:UIButton! @IBOutlet var contentLabel:UITextView! @IBOutlet var groupLabel:UILabel! @IBOutlet var dateLabel:UILabel! @IBOutlet var imgDetailIndicator:UIButton! var statusId = -1 var username = "" var blocked:Bool = false var status:JSON! var profile:JSON! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func blockUnblock() { if (blocked) { blockButton.setTitle("Block", forState: UIControlState.Normal) blockButton.setTitle("Block", forState: UIControlState.Selected) var defaults = NSUserDefaults.standardUserDefaults() var lUsername = defaults.valueForKey("username") as! String var password = defaults.valueForKey("password") as! String DataMethods.Unblock(lUsername, password, username) } else { blockButton.setTitle("Unblock", forState: UIControlState.Normal) blockButton.setTitle("Unblock", forState: UIControlState.Selected) var defaults = NSUserDefaults.standardUserDefaults() var lUsername = defaults.valueForKey("username") as! String var password = defaults.valueForKey("password") as! String DataMethods.Block(lUsername, password, username) } } override func viewDidAppear(animated: Bool) { var defaults = NSUserDefaults.standardUserDefaults() var lUsername = defaults.valueForKey("username") as! String var password = defaults.valueForKey("password") as! String status = DataMethods.GetStatus(lUsername, password, statusId) profile = DataMethods.GetProfile(username) blocked = DataMethods.GetBlocked(lUsername, password, username) if (blocked) { blockButton.setTitle("Unblock", forState: UIControlState.Normal) blockButton.setTitle("Unblock", forState: UIControlState.Selected) } else { blockButton.setTitle("Block", forState: UIControlState.Normal) blockButton.setTitle("Block", forState: UIControlState.Selected) } displayNameLabel.text = profile["displayname"].stringValue userNameLabel.text = "@" + profile["username"].stringValue if (profile["avaurl"].stringValue != "") { var avaUrl = NSURL(string:profile["avaurl"].stringValue) if let avUrl = avaUrl { var avaData = NSData(contentsOfURL: avUrl) var img = UIImage(data: avaData!)! avaView.image = UIImage(data: avaData!) avaView.layer.cornerRadius = avaView.frame.size.width / 2 avaView.clipsToBounds = true } } bioLabel.text = profile["bio"].stringValue locLabel.text = profile["location"].stringValue statusesLabel.text = profile["statusid"].stringValue contentLabel.text = status["content"].stringValue groupLabel.text = "posted to: " + status["group"].stringValue dateLabel.text = status["time"].stringValue // debug println(status) println(profile) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if (segue.identifier == "iDetail") { var dest = segue.destinationViewController as! ImageDetailTableViewController dest.status = contentLabel.text! } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
ac2ef46ad82f28a6d4fc01ced50f1074
34.669231
106
0.634246
5.135105
false
false
false
false
BlurredSoftware/BSWInterfaceKit
Sources/BSWInterfaceKit/ViewControllers/Presentations/CardPresentation.swift
1
11509
// // Copyright © 2018 TheLeftBit SL. All rights reserved. // Created by Pierluigi Cifani. // #if canImport(UIKit) import UIKit /** This abstraction will create the appropiate `UIViewControllerAnimatedTransitioning` instance for a card-like modal animation. - Attention: To use it: ``` extension FooVC: UIViewControllerTransitioningDelegate { public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { let properties = CardPresentation.AnimationProperties(kind: .presentation(cardHeight: .intrinsicHeight), animationDuration: 2) return CardPresentation.transitioningFor(properties: properties) } public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { let properties = CardPresentation.AnimationProperties(kind: .dismissal, animationDuration: 2) return CardPresentation.transitioningFor(properties: properties) } } ``` - note: For an example on how it [looks](http://i.giphy.com/l0EwZqcEkc15D6XOo.gif) */ public enum CardPresentation { /** These are the properties you can edit of the card-like modal presentation. */ public struct AnimationProperties: Equatable { /// The Kind of this animation public let kind: Kind /// The duration of this animation public let animationDuration: TimeInterval /// If true, the presented VC will be layout inside the safeArea of the presenting VC public let presentationInsideSafeArea: Bool /// The background color for the view below the presented VC public let backgroundColor: UIColor /// If true, the alpha of the VC will be animated from 0 to 1 public let shouldAnimateNewVCAlpha: Bool /// Any traits to set to the presented VC public let overridenTraits: UITraitCollection? /// The corner radius for the presented VC public let roundCornerRadius: CGFloat? /// Any additional offset to add to the presentation public let initialYOffset: CGFloat? public enum CardHeight: Equatable { // swiftlint:disable:this nesting case fixed(CGFloat) case intrinsicHeight } public enum Position: Equatable { // swiftlint:disable:this nesting case top case bottom } public enum Kind: Equatable { // swiftlint:disable:this nesting case dismissal case presentation(cardHeight: CardHeight = .intrinsicHeight, position: Position = .bottom) } public init(kind: Kind, animationDuration: TimeInterval = 0.6, presentationInsideSafeArea: Bool = false, backgroundColor: UIColor = UIColor.black.withAlphaComponent(0.7), shouldAnimateNewVCAlpha: Bool = true, overridenTraits: UITraitCollection? = nil, roundCornerRadius: CGFloat? = nil, initialYOffset: CGFloat? = nil) { self.kind = kind self.animationDuration = animationDuration self.presentationInsideSafeArea = presentationInsideSafeArea self.backgroundColor = backgroundColor self.shouldAnimateNewVCAlpha = shouldAnimateNewVCAlpha self.overridenTraits = overridenTraits self.roundCornerRadius = roundCornerRadius self.initialYOffset = initialYOffset } } /** This method will return a `UIViewControllerAnimatedTransitioning` with default `AnimationProperties` for the given `Kind` - Parameter kind: A value that represents the kind of transition you need. */ static public func transitioningFor(kind: AnimationProperties.Kind) -> UIViewControllerAnimatedTransitioning { return transitioningFor(properties: CardPresentation.AnimationProperties(kind: kind)) } /** This method will return a `UIViewControllerAnimatedTransitioning` with the given `AnimationProperties` - Parameter properties: The properties for the desired animation. */ static public func transitioningFor(properties: AnimationProperties) -> UIViewControllerAnimatedTransitioning { switch properties.kind { case .dismissal: return CardDismissAnimationController(properties: properties) case .presentation: return CardPresentAnimationController(properties: properties) } } } private class CardPresentAnimationController: NSObject, UIViewControllerAnimatedTransitioning { let properties: CardPresentation.AnimationProperties init(properties: CardPresentation.AnimationProperties) { self.properties = properties super.init() } // MARK: - UIViewControllerAnimatedTransitioning func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return properties.animationDuration } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { guard let toViewController = transitionContext.viewController(forKey: .to) else { return } guard var fromViewController = transitionContext.viewController(forKey: .from) else { return } if let containerVC = fromViewController as? ContainerViewController { fromViewController = containerVC.containedViewController } if let tabBarController = fromViewController as? UITabBarController { fromViewController = tabBarController.selectedViewController ?? fromViewController } if let navController = fromViewController as? UINavigationController { fromViewController = navController.topViewController ?? fromViewController } guard case .presentation(let cardHeight, let position) = properties.kind else { fatalError() } let containerView = transitionContext.containerView let duration = self.transitionDuration(using: transitionContext) let safeAreaOffset: CGFloat = { guard properties.presentationInsideSafeArea else { return 0 } switch position { case .top: return fromViewController.view.safeAreaInsets.top case .bottom: return fromViewController.view.safeAreaInsets.bottom } }() /// Add background view let bgView = PresentationBackgroundView(frame: containerView.bounds) bgView.backgroundColor = properties.backgroundColor bgView.tag = Constants.BackgroundViewTag containerView.addSubview(bgView) bgView.context = .init(parentViewController: toViewController, position: position, offset: safeAreaOffset) if let radius = properties.roundCornerRadius { toViewController.view.roundCorners(radius: radius) } /// Add VC's view containerView.addAutolayoutSubview(toViewController.view) /// Override size classes if required toViewController.presentationController?.overrideTraitCollection = properties.overridenTraits /// Pin to the bottom or top let anchorConstraint: NSLayoutConstraint = { switch (position) { case .bottom: return toViewController.view.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: safeAreaOffset) case .top: return toViewController.view.topAnchor.constraint(equalTo: containerView.topAnchor, constant: safeAreaOffset) } }() NSLayoutConstraint.activate([ toViewController.view.leadingAnchor.constraint(equalTo: containerView.leadingAnchor), toViewController.view.trailingAnchor.constraint(equalTo: containerView.trailingAnchor), anchorConstraint, ]) /// If it's a fixed height, add that constraint switch cardHeight { case .fixed(let height): toViewController.view.heightAnchor.constraint(equalToConstant: height).isActive = true case .intrinsicHeight: break } /// Perform the first layout pass containerView.layoutIfNeeded() /// Now move this view offscreen let distanceToMove = toViewController.view.frame.height + safeAreaOffset let distanceToMoveWithPosition = (position == .bottom) ? distanceToMove : -distanceToMove let offScreenTransform = CGAffineTransform(translationX: 0, y: distanceToMoveWithPosition) toViewController.view.transform = offScreenTransform /// Prepare the alpha animation toViewController.view.alpha = properties.shouldAnimateNewVCAlpha ? 0.0 : 1.0 bgView.alpha = 0.0 /// And bring it back on screen let animator = UIViewPropertyAnimator(duration: duration, dampingRatio: 1.0) { toViewController.view.transform = { if let offset = self.properties.initialYOffset { return CGAffineTransform(translationX: 0, y: offset) } else { return .identity } }() toViewController.view.alpha = 1 bgView.alpha = 1.0 } animator.addCompletion { (position) in guard position == .end else { return } transitionContext.completeTransition(true) } animator.startAnimation() } } private class CardDismissAnimationController: NSObject, UIViewControllerAnimatedTransitioning { let properties: CardPresentation.AnimationProperties init(properties: CardPresentation.AnimationProperties) { self.properties = properties super.init() } // MARK: UIViewControllerAnimatedTransitioning func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return properties.animationDuration } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let containerView = transitionContext.containerView guard let fromViewController = transitionContext.viewController(forKey: .from) else { return } guard let bgView = containerView.subviews.first(where: { $0.tag == Constants.BackgroundViewTag}) as? PresentationBackgroundView, let context = bgView.context else { fatalError() } let distanceToMove = fromViewController.view.frame.height + (context.offset ?? 0) let distanceToMoveWithPosition = (context.position == .bottom) ? distanceToMove : -distanceToMove let offScreenTransform = CGAffineTransform(translationX: 0, y: distanceToMoveWithPosition) /// And bring it off screen let animator = UIViewPropertyAnimator(duration: properties.animationDuration, dampingRatio: 1.0) { fromViewController.view.transform = offScreenTransform fromViewController.view.alpha = self.properties.shouldAnimateNewVCAlpha ? 0 : 1 bgView.alpha = 0 } animator.addCompletion { (position) in guard position == .end else { return } fromViewController.view.removeFromSuperview() transitionContext.completeTransition(true) } animator.startAnimation() } } private enum Constants { static let BackgroundViewTag = 78 } #endif
mit
443b6acef827e0e7cc57d4fbfaed0eb2
41.780669
328
0.686044
5.944215
false
false
false
false
KailinLi/LeetCode-Solutions
328. Odd Even Linked List/solution.swift
1
1033
/** * Definition for singly-linked list. * public class ListNode { * public var val: Int * public var next: ListNode? * public init(_ val: Int) { * self.val = val * self.next = nil * } * } */ class Solution { func oddEvenList(_ head: ListNode?) -> ListNode? { if head == nil || head!.next == nil { return head; } var ping = true let save: ListNode = head!.next! var odd: ListNode = head!.next! var even: ListNode = head!; while odd.next != nil && even.next != nil { if ping { even.next = odd.next even = odd.next! ping = false } else { odd.next = even.next odd = even.next! ping = true } } if ping { even.next = nil } else { odd.next = nil } even.next = save return head } }
mit
79cf38957e57960f548b51189e096efe
23.046512
54
0.418199
4.322176
false
false
false
false
mdmsua/Ausgaben.iOS
Ausgaben/Ausgaben/AppDelegate.swift
1
4847
// // AppDelegate.swift // Ausgaben // // Created by Dmytro Morozov on 11.01.16. // Copyright © 2016 Dmytro Morozov. All rights reserved. // import UIKit import CoreData import Fabric import Crashlytics @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var client: MSClient? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { Fabric.with([Crashlytics.self]) let appServiceUrl = NSBundle.mainBundle().objectForInfoDictionaryKey("APP_SERVICE_URL") as! String client = MSClient(applicationURLString: appServiceUrl) return true } 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.mdmsua.Ausgaben" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("Ausgaben", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
mit
ea78e0e6867dfbc0d54d3da1d06d3e2b
48.958763
291
0.705324
5.748517
false
false
false
false
francisykl/PagingMenuController
Example/PagingMenuControllerDemo/GistsViewController.swift
4
2018
// // GistsViewController.swift // PagingMenuControllerDemo // // Created by Yusuke Kita on 5/10/15. // Copyright (c) 2015 kitasuke. All rights reserved. // import UIKit class GistsViewController: UITableViewController { var gists = [[String: AnyObject]]() class func instantiateFromStoryboard() -> GistsViewController { let storyboard = UIStoryboard(name: "MenuViewController", bundle: nil) return storyboard.instantiateViewController(withIdentifier: String(describing: self)) as! GistsViewController } // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() let url = URL(string: "https://api.github.com/gists/public") let request = URLRequest(url: url!) let session = URLSession(configuration: URLSessionConfiguration.default) let task = session.dataTask(with: request) { [weak self] data, response, error in let result = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [[String: AnyObject]] self?.gists = result ?? [] DispatchQueue.main.async(execute: { () -> Void in self?.tableView.reloadData() }) } task.resume() } } extension GistsViewController { // MARK: - UITableViewDataSource override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return gists.count } // MARK: - UITableViewDelegate override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) let gist = gists[(indexPath as NSIndexPath).row] cell.textLabel?.text = gist["description"] as? String return cell } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } }
mit
75cef7213f8331c5c3f5b2b1904de5c1
32.633333
123
0.643707
5.09596
false
false
false
false
verloop/verloop_ios
VerloopSDK/Verloop/VerloopChatViewController.swift
1
2175
// // VerloopChatViewController.swift // VerloopSDK // // Created by Prashanta Kumar Nayak on 24/05/17. // Copyright © 2017 Verloop. All rights reserved. // import Foundation import UIKit class VerloopChatViewController: UIViewController { var urlString:String? var webView:UIWebView? var cancelButton:UIButton? var chatTile:String? public var viewIsOutOfFocusBlock:((Void) -> Void)? init(chatUrl url:String, title:String, viewOutOfFocusBlock:((Void) -> Void)?) { super.init(nibName: nil, bundle: nil) self.urlString = url self.chatTile = title; self.viewIsOutOfFocusBlock = viewOutOfFocusBlock; } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.setupLayout(); let url:URL = URL.init(string: self.urlString!)! let urlRequest:URLRequest = URLRequest.init(url:url) self.webView!.loadRequest(urlRequest); self.title = self.chatTile } func setupLayout() { self.webView = UIWebView.init() self.webView?.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(self.webView!) self.webView?.scrollView.isScrollEnabled = false; self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[webView]|", options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: ["webView" : self.webView!])) self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[webView]|", options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: ["webView" : self.webView!])) let closeButton = UIBarButtonItem.init(title: "Close", style: UIBarButtonItemStyle.done, target: self, action: #selector(VerloopChatViewController.cancelButtonTapped(button:))) self.navigationItem.leftBarButtonItem = closeButton; } func cancelButtonTapped(button:UIBarButtonItem) { self.dismiss(animated: true) { self.viewIsOutOfFocusBlock!() } } }
mit
a0215da87be7f47cf11a7032edf71bac
34.639344
199
0.674793
4.596195
false
false
false
false
P0ed/SWLABR
SWLABR/Model/Components/InputComponent.swift
1
731
import Foundation final class InputComponent: ControlComponent { let inputController: InputController var thrusters = 0.0 init(_ inputController: InputController) { self.inputController = inputController } func update(node: EntityNode, inEngine engine: GameEngine) { let input = inputController.currentInput() let shipBehavior = node.behaviorComponent as! ShipBehavior if thrusters > 0.7 { thrusters -= 0.01 } thrusters = min(max(thrusters + 0.02 * input.throttle, 0), 1) shipBehavior.control(node: node, fwd: thrusters * 0.02, roll: input.stick.dx * 0.01, pitch: input.stick.dy * 0.01, yaw: input.rudder * 0.01 ) if input.fireBlaster { shipBehavior.fireBlaster(node: node) } } }
mit
53737b2a8c28ff43847408a9f84a4fcb
21.84375
63
0.708618
3.020661
false
false
false
false
sufangliang/LiangDYZB
LiangDYZB/Classes/Main/View/PageContentView.swift
1
5811
// // PageContentView.swift // LiangDYZB // // Created by qu on 2017/1/12. // Copyright © 2017年 qu. All rights reserved. // import UIKit protocol PageContentViewDelegate : class { func pageContentView(_ contentView : PageContentView, progress : CGFloat, sourceIndex : Int, targetIndex : Int) } private let identycollectCell = "collectCell" class PageContentView: UIView { //MARK:- 定义属性 fileprivate var childVcs:[UIViewController] fileprivate var parentVc:UIViewController fileprivate var startOffsetX:CGFloat = 0 fileprivate var isForbidScrollDelegate : Bool = false weak var delegate:PageContentViewDelegate? fileprivate lazy var colletctView:UICollectionView = { //创建布局对象 let layout = UICollectionViewFlowLayout() layout.itemSize = self.frame.size layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.scrollDirection = .horizontal //创建collectView let collectView = UICollectionView(frame:CGRect.zero, collectionViewLayout: layout) collectView.backgroundColor = UIColor.lightGray collectView.isPagingEnabled = true collectView.bounces = false collectView.dataSource = self collectView.delegate = self collectView.scrollsToTop = false collectView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: identycollectCell) return collectView }() //初始化创建View init(frame: CGRect,childVcs:[UIViewController],parentVc:UIViewController) { self.childVcs = childVcs // 属性初始化 必须在super.init 之前 self.parentVc = parentVc super.init(frame: frame) setUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } //设置UI extension PageContentView{ func setUI(){ for childVc in childVcs { self.parentVc.addChildViewController(childVc) } addSubview(colletctView) colletctView.frame = bounds } } //MARK: - collectView 代理 extension PageContentView:UICollectionViewDataSource{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return childVcs.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView .dequeueReusableCell(withReuseIdentifier: identycollectCell, for: indexPath) for view in cell.contentView.subviews { view .removeFromSuperview() } let childVc = childVcs[indexPath.item] childVc.view.frame = cell.contentView.bounds cell.contentView .addSubview(childVc.view) //随机色 // let red = CGFloat(arc4random_uniform(255))/CGFloat(255.0) // let green = CGFloat( arc4random_uniform(255))/CGFloat(255.0) // let blue = CGFloat(arc4random_uniform(255))/CGFloat(255.0) // let colorRun = UIColor.init(red:red, green:green, blue:blue , alpha: 1) // cell.contentView.backgroundColor = colorRun return cell } } //MARK: - contentView - 滑动代理 extension PageContentView:UICollectionViewDelegate{ func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { isForbidScrollDelegate = false startOffsetX = scrollView.contentOffset.x print("startOffsetX:%f",startOffsetX) } func scrollViewDidScroll(_ scrollView: UIScrollView) { // 0.判断是否是点击事件 if isForbidScrollDelegate { return } // 1.定义获取需要的数据 var progress : CGFloat = 0 var sourceIndex : Int = 0 var targetIndex : Int = 0 // 2.判断是左滑还是右滑 let currentOffsetX = scrollView.contentOffset.x let scrollViewW = scrollView.bounds.width if currentOffsetX > startOffsetX { // 左滑 // 1.计算progress floor 最大整数 progress = currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW) // 2.计算sourceIndex sourceIndex = Int(currentOffsetX / scrollViewW) // 3.计算targetIndex targetIndex = sourceIndex + 1 if targetIndex >= childVcs.count { targetIndex = childVcs.count - 1 } print("\(currentOffsetX)") // 4.如果完全划过去 if currentOffsetX - startOffsetX == scrollViewW { progress = 1 targetIndex = sourceIndex } } else { // 右滑 // 1.计算progress progress = 1 - (currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW)) // 2.计算targetIndex targetIndex = Int(currentOffsetX / scrollViewW) // 3.计算sourceIndex sourceIndex = targetIndex + 1 if sourceIndex >= childVcs.count { sourceIndex = childVcs.count - 1 } } // 3.将progress/sourceIndex/targetIndex传递给titleView delegate?.pageContentView(self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex) } } //设置page的当前页 extension PageContentView { func setcurrentIndex (currentIndex:NSInteger){ // 1.记录需要进制执行代理方法 isForbidScrollDelegate = true // 2.滚动正确的位置 let offsetX = CGFloat (currentIndex)*colletctView.frame.width colletctView.setContentOffset(CGPoint(x:offsetX,y:0), animated: true) } }
mit
aa8bc3d2e8dc53fb3a25f452b3cb2636
31.17341
121
0.636903
5.182495
false
false
false
false
alisidd/iOS-WeJ
WeJ/Play Tracks/HubViewController.swift
1
7424
// // LyricsViewController.swift // WeJ // // Created by Mohammad Ali Siddiqui on 3/15/17. // Copyright © 2017 Mohammad Ali Siddiqui. All rights reserved. // import UIKit class HubViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { weak var delegate: PartyViewControllerInfoDelegate? weak var tracksTableModifierDelegate: TracksTableModifierDelegate? fileprivate var minHeight: CGFloat { return HubAndQueuePageViewController.minHeight } fileprivate var maxHeight: CGFloat { return HubAndQueuePageViewController.maxHeight } fileprivate var previousScrollOffset: CGFloat = 0 @IBOutlet weak var hubTitle: UILabel? private let hubOptions = [NSLocalizedString("View Lyrics", comment: ""), NSLocalizedString("Leave Party", comment: "")] private let hubIcons = [#imageLiteral(resourceName: "lyricsIcon"), #imageLiteral(resourceName: "leavePartyIcon")] @IBOutlet weak var hubTableView: UITableView! @IBOutlet weak var hubLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() setDelegates() adjustViews() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) changeFontSizeForHub() } private func setDelegates() { hubTableView.delegate = self hubTableView.dataSource = self } func adjustViews() { updateHubTitle() hubTableView.tableFooterView = UIView() } // MARK: - Table func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return hubOptions.count } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { cell.preservesSuperviewLayoutMargins = false cell.separatorInset = .zero cell.layoutMargins = .zero cell.backgroundColor = .clear } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Hub Cell") as! HubTableViewCell cell.hubLabel.text = hubOptions[indexPath.row] cell.iconView?.image = hubIcons[indexPath.row] return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if hubOptions[indexPath.row] == NSLocalizedString("Leave Party", comment: "") { leaveParty() } else if let position = delegate?.currentTrackPosition, !Party.tracksQueue.isEmpty { MXMLyricsAction.sharedExtension().findLyricsForSong( withTitle: Party.tracksQueue[0].name, artist: Party.tracksQueue[0].artist, album: "", artWork: Party.tracksQueue[0].highResArtwork, currentProgress: position, trackDuration: Party.tracksQueue[0].length!, for: self, sender: tableView.dequeueReusableCell(withIdentifier: "Hub Cell")!, competionHandler: nil) } else { postAlertForNoTracks() } } private func postAlertForNoTracks() { let alert = UIAlertController(title: NSLocalizedString("No Track Playing", comment: ""), message: nil, preferredStyle: .alert) alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: .default, handler: nil)) present(alert, animated: true) } // MARK: = Navigation private func leaveParty() { let _ = navigationController?.popToRootViewController(animated: true) } } extension HubViewController { private var headerHeightConstraint: CGFloat { get { return delegate!.tableHeight } set { delegate?.tableHeight = newValue } } // Code taken from https://michiganlabs.com/ios/development/2016/05/31/ios-animating-uitableview-header/ func scrollViewDidScroll(_ scrollView: UIScrollView) { let scrollDiff = scrollView.contentOffset.y - previousScrollOffset let absoluteTop: CGFloat = 0 let isScrollingDown = scrollDiff > 0 && scrollView.contentOffset.y > absoluteTop let isScrollingUp = scrollDiff < 0 && scrollView.contentOffset.y < absoluteTop && !Party.tracksQueue.isEmpty var newHeight = headerHeightConstraint if isScrollingDown { newHeight = max(maxHeight, headerHeightConstraint - abs(scrollDiff)) if newHeight != headerHeightConstraint { headerHeightConstraint = newHeight changeFontSizeForHub() setScrollPosition(forOffset: previousScrollOffset) } } else if isScrollingUp { newHeight = min(minHeight, headerHeightConstraint + abs(scrollDiff)) if newHeight != headerHeightConstraint && hubTableView.contentOffset.y < 2 { headerHeightConstraint = newHeight changeFontSizeForHub() setScrollPosition(forOffset: previousScrollOffset) } } previousScrollOffset = scrollView.contentOffset.y } fileprivate func changeFontSizeForHub() { UIView.animate(withDuration: 0.3) { self.hubLabel.font = self.hubLabel.font.withSize(20 - UILabel.smallerTitleFontSize * (self.headerHeightConstraint / self.minHeight)) } } private func setScrollPosition(forOffset offset: CGFloat) { hubTableView.contentOffset = CGPoint(x: hubTableView.contentOffset.x, y: offset) } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { scrollViewDidStopScrolling() } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { if !decelerate { scrollViewDidStopScrolling() } } private func scrollViewDidStopScrolling() { let range = maxHeight - minHeight let midPoint = minHeight + (range / 2) delegate?.layout() if headerHeightConstraint > midPoint { tracksTableModifierDelegate?.showAddButton() makeTracksTableShorter() } else { makeTracksTableTaller() } } func makeTracksTableShorter() { DispatchQueue.main.async { self.delegate?.layout() UIView.animate(withDuration: 0.2, animations: { self.headerHeightConstraint = self.minHeight self.changeFontSizeForHub() self.delegate?.layout() }) } } func makeTracksTableTaller() { DispatchQueue.main.async { self.delegate?.layout() UIView.animate(withDuration: 0.2, animations: { self.headerHeightConstraint = self.maxHeight self.changeFontSizeForHub() self.delegate?.layout() }) } } func updateHubTitle() { DispatchQueue.main.async { self.hubTitle?.text = Party.name ?? NSLocalizedString("Party", comment: "") } } }
gpl-3.0
63816e9c1f1d3dba41eed7cbd114351a
33.207373
144
0.624411
5.351839
false
false
false
false
vmanot/swift-package-manager
Sources/Utility/BuildFlags.swift
1
1156
/* 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 http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ /// Build-tool independent flags. // // FIXME: This belongs somewhere else, but we don't have a layer specifically // for BuildSupport style logic yet. public struct BuildFlags { /// Flags to pass to the C compiler. public var cCompilerFlags: [String] /// Flags to pass to the C++ compiler. public var cxxCompilerFlags: [String] /// Flags to pass to the linker. public var linkerFlags: [String] /// Flags to pass to the Swift compiler. public var swiftCompilerFlags: [String] public init( xcc: [String]? = nil, xcxx: [String]? = nil, xswiftc: [String]? = nil, xlinker: [String]? = nil ) { cCompilerFlags = xcc ?? [] cxxCompilerFlags = xcxx ?? [] linkerFlags = xlinker ?? [] swiftCompilerFlags = xswiftc ?? [] } }
apache-2.0
1f50eab5bcc2452596a397bb1cff7530
27.9
77
0.654844
4.173285
false
false
false
false
nodekit-io/nodekit-darwin
src/samples/sample-nodekit/platform-darwin/SamplePlugin.swift
1
2602
/* * nodekit.io * * Copyright (c) 2016 OffGrid Networks. 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 Foundation import Cocoa import WebKit import NodeKit protocol SamplePluginProtocol: NKScriptExport { func logconsole(text: AnyObject?) -> Void func alertSync(text: AnyObject?) -> String } class SamplePlugin: NSObject, SamplePluginProtocol { class func attachTo(context: NKScriptContext) { context.loadPlugin(SamplePlugin(), namespace: "io.nodekit.test", options: ["PluginBridge": NKScriptExportType.NKScriptExport.rawValue]) } func logconsole(text: AnyObject?) -> Void { NKLogging.log(text as? String! ?? "") } func alertSync(text: AnyObject?) -> String { dispatch_async(dispatch_get_main_queue()) { self._alert(title: text as? String, message: nil) } return "OK" } private func _alert(title title: String?, message: String?) { let myPopup: NSAlert = NSAlert() myPopup.messageText = message ?? "NodeKit" myPopup.informativeText = title ?? "" myPopup.alertStyle = NSAlertStyle.Warning myPopup.addButtonWithTitle("OK") myPopup.runModal() } } /* extension WKWebView: WKUIDelegate { private func _alert(title title: String?, message: String?) { let myPopup: NSAlert = NSAlert() myPopup.messageText = message ?? "NodeKit" myPopup.informativeText = title! myPopup.alertStyle = NSAlertStyle.WarningAlertStyle myPopup.addButtonWithTitle("OK") myPopup.runModal() } public func webView(webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: () -> Void) { _alert(title: self.title, message: message) } public func webView(webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: (String?) -> Void) { completionHandler("hello from native; you sent: " + prompt) } } */
apache-2.0
c4cad24f2800a92a0f43038052d28a84
32.358974
196
0.694466
4.525217
false
false
false
false
sarvex/SwiftRecepies
Concurrency/Playing Audio in the Background/Playing Audio in the Background/AppDelegate.swift
1
3763
// // AppDelegate.swift // Playing Audio in the Background // // Created by Vandad Nahavandipoor on 7/7/14. // Copyright (c) 2014 Pixolity Ltd. All rights reserved. // // These example codes are written for O'Reilly's iOS 8 Swift Programming Cookbook // If you use these solutions in your apps, you can give attribution to // Vandad Nahavandipoor for his work. Feel free to visit my blog // at http://vandadnp.wordpress.com for daily tips and tricks in Swift // and Objective-C and various other programming languages. // // You can purchase "iOS 8 Swift Programming Cookbook" from // the following URL: // http://shop.oreilly.com/product/0636920034254.do // // If you have any questions, you can contact me directly // at vandad.np@gmail.com // Similarly, if you find an error in these sample codes, simply // report them to O'Reilly at the following URL: // http://www.oreilly.com/catalog/errata.csp?isbn=0636920034254 import UIKit import AVFoundation @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, AVAudioPlayerDelegate { var window: UIWindow? var audioPlayer: AVAudioPlayer? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool { let dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) dispatch_async(dispatchQueue, {[weak self] in var audioSessionError: NSError? let audioSession = AVAudioSession.sharedInstance() NSNotificationCenter.defaultCenter().addObserver(self!, selector: "handleInterruption:", name: AVAudioSessionInterruptionNotification, object: nil) audioSession.setActive(true, error: nil) if audioSession.setCategory(AVAudioSessionCategoryPlayback, error: &audioSessionError){ println("Successfully set the audio session") } else { println("Could not set the audio session") } let filePath = NSBundle.mainBundle().pathForResource("MySong", ofType:"mp3") let fileData = NSData(contentsOfFile: filePath!, options: .DataReadingMappedIfSafe, error: nil) var error:NSError? /* Start the audio player */ self!.audioPlayer = AVAudioPlayer(data: fileData, error: &error) /* Did we get an instance of AVAudioPlayer? */ if let theAudioPlayer = self!.audioPlayer{ theAudioPlayer.delegate = self; if theAudioPlayer.prepareToPlay() && theAudioPlayer.play(){ println("Successfully started playing") } else { println("Failed to play") } } else { /* Handle the failure of instantiating the audio player */ } }) return true } func handleInterruption(notification: NSNotification){ /* Audio Session is interrupted. The player will be paused here */ let interruptionTypeAsObject = notification.userInfo![AVAudioSessionInterruptionTypeKey] as! NSNumber let interruptionType = AVAudioSessionInterruptionType(rawValue: interruptionTypeAsObject.unsignedLongValue) if let type = interruptionType{ if type == .Ended{ /* resume the audio if needed */ } } } func audioPlayerDidFinishPlaying(player: AVAudioPlayer!, successfully flag: Bool){ println("Finished playing the song") /* The flag parameter tells us if the playback was successfully finished or not */ if player == audioPlayer{ audioPlayer = nil } } }
isc
21eac957465dd70bbd597e33ce915938
30.621849
83
0.650545
5.255587
false
false
false
false
peferron/algo
EPI/Hash Tables/Implement an ISBN cache/swift/main.swift
1
1976
private struct CachedValue { let price: Int var olderISBN: String? var newerISBN: String? } public struct ISBNCache { public let capacity: Int private var cache: [String: CachedValue] private var oldestISBN: String? private var newestISBN: String? public init(capacity: Int) { self.capacity = capacity self.cache = [String: CachedValue](minimumCapacity: capacity) } public mutating func lookup(_ ISBN: String) -> Int? { if let price = cache[ISBN]?.price { // Removing then inserting is the easiest way to bump the ISBN to newest, but it also // performs unnecessary work and could be optimized. self.remove(ISBN) self.insert(ISBN, price: price) return price } return nil } public mutating func insert(_ ISBN: String, price: Int) { self.remove(ISBN) // Remove oldest ISBN if necessary. if cache.count >= capacity { self.remove(self.oldestISBN!) } // Insert as newest ISBN. cache[ISBN] = CachedValue(price: price, olderISBN: self.newestISBN, newerISBN: nil) if let newestISBN = self.newestISBN { cache[newestISBN]!.newerISBN = ISBN } self.newestISBN = ISBN self.oldestISBN = self.oldestISBN ?? ISBN } public mutating func remove(_ ISBN: String) { if let value = cache[ISBN] { cache.removeValue(forKey: ISBN) if let olderISBN = value.olderISBN { cache[olderISBN]!.newerISBN = value.newerISBN } if let newerISBN = value.newerISBN { cache[newerISBN]!.olderISBN = value.olderISBN } if ISBN == self.oldestISBN { self.oldestISBN = value.newerISBN } if ISBN == self.newestISBN { self.newestISBN = value.olderISBN } } } }
mit
a44b96747ae9bd9ad26e546ca1451d50
28.058824
97
0.574393
4.420582
false
false
false
false
peferron/algo
EPI/Sorting/Count the frequencies of characters in a sentence/swift/test.swift
1
1116
import Darwin func == <T: Equatable, U: Equatable>(lhs: [(T, U)], rhs: [(T, U)]) -> Bool { guard lhs.count == rhs.count else { return false } for (i, lt) in lhs.enumerated() { let rt = rhs[i] guard lt.0 == rt.0 && lt.1 == rt.1 else { return false } } return true } let tests: [(string: String, occurrences: [Occurrences])] = [ ( string: "", occurrences: [] ), ( string: "a", occurrences: [("a", 1)] ), ( string: "aa", occurrences: [("a", 2)] ), ( string: "ab", occurrences: [("a", 1), ("b", 1)] ), ( string: "ba", occurrences: [("a", 1), ("b", 1)] ), ( string: "bcdacebe", occurrences: [("a", 1), ("b", 2), ("c", 2), ("d", 1), ("e", 2)] ), ] for test in tests { let actual = occurrences(test.string) guard actual == test.occurrences else { print("For test string \(test.string), expected occurrences to be \(test.occurrences), " + "but were \(actual)") exit(1) } }
mit
a5830712171c0a41a9e020b037a685ff
21.32
98
0.445341
3.4875
false
true
false
false
sshams/puremvc-swift-standard-framework
PureMVC/org/puremvc/swift/patterns/observer/Notification.swift
1
2831
// // Notification.swift // PureMVC SWIFT Standard // // Copyright(c) 2015-2025 Saad Shams <saad.shams@puremvc.org> // Your reuse is governed by the Creative Commons Attribution 3.0 License // /** A base `INotification` implementation. PureMVC does not rely upon underlying event models such as the one provided with Flash, and ActionScript 3 does not have an inherent event model. The Observer Pattern as implemented within PureMVC exists to support event-driven communication between the application and the actors of the MVC triad. Notifications are not meant to be a replacement for Events in Flex/Flash/Apollo. Generally, `IMediator` implementors place event listeners on their view components, which they then handle in the usual way. This may lead to the broadcast of `Notification`s to trigger `ICommand`s or to communicate with other `IMediators`. `IProxy` and `ICommand` instances communicate with each other and `IMediator`s by broadcasting `INotification`s. A key difference between Flash `Event`s and PureMVC `Notification`s is that `Event`s follow the 'Chain of Responsibility' pattern, 'bubbling' up the display hierarchy until some parent component handles the `Event`, while PureMVC `Notification`s follow a 'Publish/Subscribe' pattern. PureMVC classes need not be related to each other in a parent/child relationship in order to communicate with one another using `Notification`s. `@see org.puremvc.swift.patterns.observer.Observer Observer` * */ public class Notification : INotification { // the name of the notification instance private var _name: String // the body of the notification instance private var _body: Any? // the type of the notification instance private var _type: String? /** Constructor. - parameter name: name of the `Notification` instance. (required) - parameter body: the `Notification` body. (optional) - parameter type: the type of the `Notification` (optional) */ public init(name: String, body: Any?=nil, type: String?=nil) { _name = name _body = body _type = type } /// Get the name of notification instance public var name: String { return _name } /// Get or set the body of notification instance public var body: Any? { get { return _body } set { _body = newValue } } /// Get or set the type of notification instance public var type: String? { get { return _type } set { _type = newValue } } /** Get the string representation of the `Notification` instance. - returns: the string representation of the `Notification` instance. */ public func description() -> String { return "Notification Name: \(self.name) \(self.body) \(self.type)" } }
bsd-3-clause
df7d7f165e30ace057de4048733c45ea
31.170455
86
0.697987
4.263554
false
false
false
false
marcelganczak/swift-js-transpiler
test/types/tuple.swift
1
594
let unnamedUntypedTuple = (4, 25) print(unnamedUntypedTuple.0) print(unnamedUntypedTuple.1) let unnamedTypedTuple:(Int, Int) = (4, 25) print(unnamedTypedTuple.0) print(unnamedTypedTuple.1) let unnamedUntypedVariadicTuple = (4, "string") print(unnamedUntypedVariadicTuple.0) print(unnamedUntypedVariadicTuple.1) let namedUntypedTuple = (a:4, count:25) print(namedUntypedTuple.a) print(namedUntypedTuple.count) let namedTypedTuple:(a:Int, count:Int) = (4, 25) print(namedTypedTuple.a) print(namedTypedTuple.count) let nestedTuple = (4, (12, 25)) print(nestedTuple.1.0) print(nestedTuple.1.1)
mit
5a9c27b54eff70d4741be928b4776b87
24.869565
48
0.784512
2.911765
false
false
false
false
gregomni/swift
test/refactoring/ConvertAsync/convert_function.swift
10
32579
// REQUIRES: concurrency // RUN: %empty-directory(%t) enum CustomError : Error { case Bad } func run(block: () -> Bool) -> Bool { return false } func makeOptionalError() -> Error? { return nil } func makeOptionalString() -> String? { return nil } func simple(_ completion: @escaping (String) -> Void) { } func simple() async -> String { } func simple2(arg: String, _ completion: @escaping (String) -> Void) { } func simple2(arg: String) async -> String { } func simpleErr(arg: String, _ completion: @escaping (String?, Error?) -> Void) { } func simpleErr(arg: String) async throws -> String { } func simpleRes(arg: String, _ completion: @escaping (Result<String, Error>) -> Void) { } func simpleRes(arg: String) async throws -> String { } // RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=ALREADY-ASYNC %s func alreadyAsync() async { simple { print($0) } } // ALREADY-ASYNC: func alreadyAsync() async { // ALREADY-ASYNC-NEXT: let val0 = await simple() // ALREADY-ASYNC-NEXT: print(val0) // ALREADY-ASYNC-NEXT: } // RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NESTED %s func nested() { simple { simple2(arg: $0) { str2 in print(str2) } } } // NESTED: func nested() async { // NESTED-NEXT: let val0 = await simple() // NESTED-NEXT: let str2 = await simple2(arg: val0) // NESTED-NEXT: print(str2) // NESTED-NEXT: } // Can't check for compilation since throws isn't added // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NO-THROWS %s func noThrowsAdded() { simpleErr(arg: "") { _, _ in } } // NO-THROWS: func noThrowsAdded() async { // NO-THROWS-NEXT: let _ = try await simpleErr(arg: "") // NO-THROWS-NEXT: } // RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+2):9 | %FileCheck -check-prefix=ATTRIBUTES %s @available(*, deprecated, message: "Deprecated") private func functionWithAttributes() { simple { str in print(str) } } // ATTRIBUTES: convert_function.swift [[# @LINE-6]]:1 -> [[# @LINE-1]]:2 // ATTRIBUTES-NEXT: @available(*, deprecated, message: "Deprecated") // ATTRIBUTES-NEXT: private func functionWithAttributes() async { // ATTRIBUTES-NEXT: let str = await simple() // ATTRIBUTES-NEXT: print(str) // ATTRIBUTES-NEXT: } // RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=MANY-NESTED %s func manyNested() throws { simple { str1 in print("simple") simple2(arg: str1) { str2 in print("simple2") simpleErr(arg: str2) { str3, err in print("simpleErr") guard let str3 = str3, err == nil else { return } simpleRes(arg: str3) { res in print("simpleRes") if case .success(let str4) = res { print("\(str1) \(str2) \(str3) \(str4)") print("after") } } } } } } // MANY-NESTED: func manyNested() async throws { // MANY-NESTED-NEXT: let str1 = await simple() // MANY-NESTED-NEXT: print("simple") // MANY-NESTED-NEXT: let str2 = await simple2(arg: str1) // MANY-NESTED-NEXT: print("simple2") // MANY-NESTED-NEXT: let str3 = try await simpleErr(arg: str2) // MANY-NESTED-NEXT: print("simpleErr") // MANY-NESTED-NEXT: let str4 = try await simpleRes(arg: str3) // MANY-NESTED-NEXT: print("simpleRes") // MANY-NESTED-NEXT: print("\(str1) \(str2) \(str3) \(str4)") // MANY-NESTED-NEXT: print("after") // MANY-NESTED-NEXT: } // RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=ASYNC-SIMPLE %s func asyncParams(arg: String, _ completion: @escaping (String?, Error?) -> Void) { simpleErr(arg: arg) { str, err in print("simpleErr") guard let str = str, err == nil else { completion(nil, err!) return } completion(str, nil) print("after") } } // ASYNC-SIMPLE: func {{[a-zA-Z_]+}}(arg: String) async throws -> String { // ASYNC-SIMPLE-NEXT: let str = try await simpleErr(arg: arg) // ASYNC-SIMPLE-NEXT: print("simpleErr") // ASYNC-SIMPLE-NEXT: {{^}}return str{{$}} // ASYNC-SIMPLE-NEXT: print("after") // ASYNC-SIMPLE-NEXT: } // RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=ASYNC-SIMPLE %s func asyncResErrPassed(arg: String, _ completion: @escaping (Result<String, Error>) -> Void) { simpleErr(arg: arg) { str, err in print("simpleErr") guard let str = str, err == nil else { completion(.failure(err!)) return } completion(.success(str)) print("after") } } // RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=ASYNC-ERR %s func asyncResNewErr(arg: String, _ completion: @escaping (Result<String, Error>) -> Void) { simpleErr(arg: arg) { str, err in print("simpleErr") guard let str = str, err == nil else { completion(.failure(CustomError.Bad)) return } completion(.success(str)) print("after") } } // ASYNC-ERR: func asyncResNewErr(arg: String) async throws -> String { // ASYNC-ERR-NEXT: do { // ASYNC-ERR-NEXT: let str = try await simpleErr(arg: arg) // ASYNC-ERR-NEXT: print("simpleErr") // ASYNC-ERR-NEXT: {{^}}return str{{$}} // ASYNC-ERR-NEXT: print("after") // ASYNC-ERR-NEXT: } catch let err { // ASYNC-ERR-NEXT: throw CustomError.Bad // ASYNC-ERR-NEXT: } // ASYNC-ERR-NEXT: } // RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=CALL-NON-ASYNC-IN-ASYNC %s func callNonAsyncInAsync(_ completion: @escaping (String) -> Void) { simple { str in let success = run { completion(str) return true } if !success { completion("bad") } } } // CALL-NON-ASYNC-IN-ASYNC: func callNonAsyncInAsync() async -> String { // CALL-NON-ASYNC-IN-ASYNC-NEXT: let str = await simple() // CALL-NON-ASYNC-IN-ASYNC-NEXT: return await withCheckedContinuation { continuation in // CALL-NON-ASYNC-IN-ASYNC-NEXT: let success = run { // CALL-NON-ASYNC-IN-ASYNC-NEXT: continuation.resume(returning: str) // CALL-NON-ASYNC-IN-ASYNC-NEXT: {{^}} return true{{$}} // CALL-NON-ASYNC-IN-ASYNC-NEXT: } // CALL-NON-ASYNC-IN-ASYNC-NEXT: if !success { // CALL-NON-ASYNC-IN-ASYNC-NEXT: continuation.resume(returning: "bad") // CALL-NON-ASYNC-IN-ASYNC-NEXT: } // CALL-NON-ASYNC-IN-ASYNC-NEXT: } // CALL-NON-ASYNC-IN-ASYNC-NEXT: } // RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=CALL-NON-ASYNC-IN-ASYNC-COMMENT %s func callNonAsyncInAsyncComment(_ completion: @escaping (String) -> Void) { // a simple { str in // b // c let success = run { // d completion(str) // e return true // f } // g if !success { // h completion("bad") // i } // j } // k } // CALL-NON-ASYNC-IN-ASYNC-COMMENT: func callNonAsyncInAsyncComment() async -> String { // CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: // a // CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: let str = await simple() // CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: // b // CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: // c // CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: return await withCheckedContinuation { continuation in // CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: let success = run { // CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: // d // CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: continuation.resume(returning: str) // CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: // e // CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: {{^}} return true{{$}} // CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: // f // CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: } // CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: // g // CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: if !success { // CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: // h // CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: continuation.resume(returning: "bad") // CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: // i // CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: } // CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: // j // CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: // k // CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: } // CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: } // RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix VOID-AND-ERROR-HANDLER %s func voidAndErrorCompletion(completion: @escaping (Void?, Error?) -> Void) { if .random() { completion((), nil) // Make sure we drop the () } else { completion(nil, CustomError.Bad) } } // VOID-AND-ERROR-HANDLER: func voidAndErrorCompletion() async throws { // VOID-AND-ERROR-HANDLER-NEXT: if .random() { // VOID-AND-ERROR-HANDLER-NEXT: return // Make sure we drop the () // VOID-AND-ERROR-HANDLER-NEXT: } else { // VOID-AND-ERROR-HANDLER-NEXT: throw CustomError.Bad // VOID-AND-ERROR-HANDLER-NEXT: } // VOID-AND-ERROR-HANDLER-NEXT: } // RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix TOO-MUCH-VOID-AND-ERROR-HANDLER %s func tooMuchVoidAndErrorCompletion(completion: @escaping (Void?, Void?, Error?) -> Void) { if .random() { completion((), (), nil) // Make sure we drop the ()s } else { completion(nil, nil, CustomError.Bad) } } // TOO-MUCH-VOID-AND-ERROR-HANDLER: func tooMuchVoidAndErrorCompletion() async throws { // TOO-MUCH-VOID-AND-ERROR-HANDLER-NEXT: if .random() { // TOO-MUCH-VOID-AND-ERROR-HANDLER-NEXT: return // Make sure we drop the ()s // TOO-MUCH-VOID-AND-ERROR-HANDLER-NEXT: } else { // TOO-MUCH-VOID-AND-ERROR-HANDLER-NEXT: throw CustomError.Bad // TOO-MUCH-VOID-AND-ERROR-HANDLER-NEXT: } // TOO-MUCH-VOID-AND-ERROR-HANDLER-NEXT: } // RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix VOID-RESULT-HANDLER %s func voidResultCompletion(completion: @escaping (Result<Void, Error>) -> Void) { if .random() { completion(.success(())) // Make sure we drop the .success(()) } else { completion(.failure(CustomError.Bad)) } } // VOID-RESULT-HANDLER: func voidResultCompletion() async throws { // VOID-RESULT-HANDLER-NEXT: if .random() { // VOID-RESULT-HANDLER-NEXT: return // Make sure we drop the .success(()) // VOID-RESULT-HANDLER-NEXT: } else { // VOID-RESULT-HANDLER-NEXT: throw CustomError.Bad // VOID-RESULT-HANDLER-NEXT: } // VOID-RESULT-HANDLER-NEXT: } // rdar://77789360 Make sure we don't print a double return statement. // RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=RETURN-HANDLING %s func testReturnHandling(_ completion: @escaping (String?, Error?) -> Void) { return completion("", nil) } // RETURN-HANDLING: func testReturnHandling() async throws -> String { // RETURN-HANDLING-NEXT: {{^}} return ""{{$}} // RETURN-HANDLING-NEXT: } // rdar://77789360 Make sure we don't print a double return statement and don't // completely drop completion(a). // Note we cannot use refactor-check-compiles here, as the placeholders mean we // don't form valid AST. // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=RETURN-HANDLING2 %s func testReturnHandling2(completion: @escaping (String) -> ()) { simpleErr(arg: "") { x, err in guard let _ = x else { let a = "" return completion(a) } let b = "" return completion(b) } } // RETURN-HANDLING2: func testReturnHandling2() async -> String { // RETURN-HANDLING2-NEXT: do { // RETURN-HANDLING2-NEXT: let x = try await simpleErr(arg: "") // RETURN-HANDLING2-NEXT: let b = "" // RETURN-HANDLING2-NEXT: {{^}}<#return#> b{{$}} // RETURN-HANDLING2-NEXT: } catch let err { // RETURN-HANDLING2-NEXT: let a = "" // RETURN-HANDLING2-NEXT: {{^}}<#return#> a{{$}} // RETURN-HANDLING2-NEXT: } // RETURN-HANDLING2-NEXT: } // RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=RETURN-HANDLING3 %s func testReturnHandling3(_ completion: @escaping (String?, Error?) -> Void) { return (completion("", nil)) } // RETURN-HANDLING3: func testReturnHandling3() async throws -> String { // RETURN-HANDLING3-NEXT: {{^}} return ""{{$}} // RETURN-HANDLING3-NEXT: } // RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=RETURN-HANDLING4 %s func testReturnHandling4(_ completion: @escaping (String?, Error?) -> Void) { simpleErr(arg: "xxx") { str, err in if str != nil { completion(str, err) return } print("some error stuff") completion(str, err) } } // RETURN-HANDLING4: func testReturnHandling4() async throws -> String { // RETURN-HANDLING4-NEXT: do { // RETURN-HANDLING4-NEXT: let str = try await simpleErr(arg: "xxx") // RETURN-HANDLING4-NEXT: return str // RETURN-HANDLING4-NEXT: } catch let err { // RETURN-HANDLING4-NEXT: print("some error stuff") // RETURN-HANDLING4-NEXT: throw err // RETURN-HANDLING4-NEXT: } // RETURN-HANDLING4-NEXT: } // RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=RDAR78693050 %s func rdar78693050(_ completion: @escaping () -> Void) { simple { str in print(str) } if .random() { return completion() } completion() } // RDAR78693050: func rdar78693050() async { // RDAR78693050-NEXT: let str = await simple() // RDAR78693050-NEXT: print(str) // RDAR78693050-NEXT: if .random() { // RDAR78693050-NEXT: return // RDAR78693050-NEXT: } // RDAR78693050-NEXT: return // RDAR78693050-NEXT: } // RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=DISCARDABLE-RESULT %s func withDefaultedCompletion(arg: String, completion: @escaping (String) -> Void = {_ in}) { completion(arg) } // DISCARDABLE-RESULT: @discardableResult // DISCARDABLE-RESULT-NEXT: func withDefaultedCompletion(arg: String) async -> String { // DISCARDABLE-RESULT-NEXT: return arg // DISCARDABLE-RESULT-NEXT: } // RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=DEFAULT-ARG %s func withDefaultArg(x: String = "") { } // DEFAULT-ARG: convert_function.swift [[# @LINE-2]]:1 -> [[# @LINE-1]]:2 // DEFAULT-ARG-NOT: @discardableResult // DEFAULT-ARG-NEXT: {{^}}func withDefaultArg(x: String = "") async // RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=IMPLICIT-RETURN %s func withImplicitReturn(completionHandler: @escaping (String) -> Void) { simple { completionHandler($0) } } // IMPLICIT-RETURN: func withImplicitReturn() async -> String { // IMPLICIT-RETURN-NEXT: let val0 = await simple() // IMPLICIT-RETURN-NEXT: return val0 // IMPLICIT-RETURN-NEXT: } // This code doesn't compile after refactoring because we can't return `nil` from the async function. // But there's not much else we can do here. // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NIL-RESULT-AND-NIL-ERROR %s func nilResultAndNilError(completion: @escaping (String?, Error?) -> Void) { completion(nil, nil) } // NIL-RESULT-AND-NIL-ERROR: func nilResultAndNilError() async throws -> String { // NIL-RESULT-AND-NIL-ERROR-NEXT: return nil // NIL-RESULT-AND-NIL-ERROR-NEXT: } // RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NIL-RESULT-AND-OPTIONAL-RELAYED-ERROR %s func nilResultAndOptionalRelayedError(completion: @escaping (String?, Error?) -> Void) { simpleErr(arg: "test") { (res, err) in completion(nil, err) } } // NIL-RESULT-AND-OPTIONAL-RELAYED-ERROR: func nilResultAndOptionalRelayedError() async throws -> String { // NIL-RESULT-AND-OPTIONAL-RELAYED-ERROR-NEXT: let res = try await simpleErr(arg: "test") // NIL-RESULT-AND-OPTIONAL-RELAYED-ERROR-EMPTY: // NIL-RESULT-AND-OPTIONAL-RELAYED-ERROR-NEXT: } // This code doesn't compile after refactoring because we can't throw an optional error returned from makeOptionalError(). // But it's not clear what the intended result should be either. // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NIL-RESULT-AND-OPTIONAL-COMPLEX-ERROR %s func nilResultAndOptionalComplexError(completion: @escaping (String?, Error?) -> Void) { completion(nil, makeOptionalError()) } // NIL-RESULT-AND-OPTIONAL-COMPLEX-ERROR: func nilResultAndOptionalComplexError() async throws -> String { // NIL-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: throw makeOptionalError() // NIL-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: } // RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NIL-RESULT-AND-NON-OPTIONAL-ERROR %s func nilResultAndNonOptionalError(completion: @escaping (String?, Error?) -> Void) { completion(nil, CustomError.Bad) } // NIL-RESULT-AND-NON-OPTIONAL-ERROR: func nilResultAndNonOptionalError() async throws -> String { // NIL-RESULT-AND-NON-OPTIONAL-ERROR-NEXT: throw CustomError.Bad // NIL-RESULT-AND-NON-OPTIONAL-ERROR-NEXT: } // In this case, we are previously ignoring the error returned from simpleErr but are rethrowing it in the refactored case. // That's probably fine although it changes semantics. // RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=OPTIONAL-RELAYED-RESULT-AND-NIL-ERROR %s func optionalRelayedResultAndNilError(completion: @escaping (String?, Error?) -> Void) { simpleErr(arg: "test") { (res, err) in completion(res, nil) } } // OPTIONAL-RELAYED-RESULT-AND-NIL-ERROR: func optionalRelayedResultAndNilError() async throws -> String { // OPTIONAL-RELAYED-RESULT-AND-NIL-ERROR-NEXT: let res = try await simpleErr(arg: "test") // OPTIONAL-RELAYED-RESULT-AND-NIL-ERROR-NEXT: return res // OPTIONAL-RELAYED-RESULT-AND-NIL-ERROR-NEXT: } // RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-RELAYED-ERROR %s func optionalRelayedResultAndOptionalRelayedError(completion: @escaping (String?, Error?) -> Void) { simpleErr(arg: "test") { (res, err) in completion(res, err) } } // OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-RELAYED-ERROR: func optionalRelayedResultAndOptionalRelayedError() async throws -> String { // OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-RELAYED-ERROR-NEXT: let res = try await simpleErr(arg: "test") // OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-RELAYED-ERROR-NEXT: return res // OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-RELAYED-ERROR-NEXT: } // RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR %s func optionalRelayedResultAndOptionalComplexError(completion: @escaping (String?, Error?) -> Void) { simpleErr(arg: "test") { (res, err) in completion(res, makeOptionalError()) } } // OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR: func optionalRelayedResultAndOptionalComplexError() async throws -> String { // OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: let res = try await simpleErr(arg: "test") // OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: if let error = makeOptionalError() { // OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: throw error // OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: } else { // OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: return res // OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: } // OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: } // RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=OPTIONAL-RELAYED-RESULT-AND-NON-OPTIONAL-ERROR %s func optionalRelayedResultAndNonOptionalError(completion: @escaping (String?, Error?) -> Void) { simpleErr(arg: "test") { (res, err) in completion(res, CustomError.Bad) } } // OPTIONAL-RELAYED-RESULT-AND-NON-OPTIONAL-ERROR: func optionalRelayedResultAndNonOptionalError() async throws -> String { // OPTIONAL-RELAYED-RESULT-AND-NON-OPTIONAL-ERROR-NEXT: let res = try await simpleErr(arg: "test") // OPTIONAL-RELAYED-RESULT-AND-NON-OPTIONAL-ERROR-NEXT: throw CustomError.Bad // OPTIONAL-RELAYED-RESULT-AND-NON-OPTIONAL-ERROR-NEXT: } // RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NON-OPTIONAL-RELAYED-RESULT-AND-NIL-ERROR %s func nonOptionalRelayedResultAndNilError(completion: @escaping (String?, Error?) -> Void) { simple { res in completion(res, nil) } } // NON-OPTIONAL-RELAYED-RESULT-AND-NIL-ERROR: func nonOptionalRelayedResultAndNilError() async throws -> String { // NON-OPTIONAL-RELAYED-RESULT-AND-NIL-ERROR-NEXT: let res = await simple() // NON-OPTIONAL-RELAYED-RESULT-AND-NIL-ERROR-NEXT: return res // NON-OPTIONAL-RELAYED-RESULT-AND-NIL-ERROR-NEXT: } // RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NON-OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR %s func nonOptionalRelayedResultAndOptionalComplexError(completion: @escaping (String?, Error?) -> Void) { simple { res in completion(res, makeOptionalError()) } } // NON-OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR: func nonOptionalRelayedResultAndOptionalComplexError() async throws -> String { // NON-OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: let res = await simple() // NON-OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: if let error = makeOptionalError() { // NON-OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: throw error // NON-OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: } else { // NON-OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: return res // NON-OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: } // NON-OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: } // RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NON-OPTIONAL-RELAYED-RESULT-AND-NON-OPTIONAL-ERROR %s func nonOptionalRelayedResultAndNonOptionalError(completion: @escaping (String?, Error?) -> Void) { simple { res in completion(res, CustomError.Bad) } } // NON-OPTIONAL-RELAYED-RESULT-AND-NON-OPTIONAL-ERROR: func nonOptionalRelayedResultAndNonOptionalError() async throws -> String { // NON-OPTIONAL-RELAYED-RESULT-AND-NON-OPTIONAL-ERROR-NEXT: let res = await simple() // NON-OPTIONAL-RELAYED-RESULT-AND-NON-OPTIONAL-ERROR-NEXT: throw CustomError.Bad // NON-OPTIONAL-RELAYED-RESULT-AND-NON-OPTIONAL-ERROR-NEXT: } // The refactored code doesn't compile because we can't return an optional String from the async function. // But it's not clear what the intended result should be either, because `error` is always `nil`. // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=OPTIONAL-COMPLEX-RESULT-AND-NIL-ERROR %s func optionalComplexResultAndNilError(completion: @escaping (String?, Error?) -> Void) { completion(makeOptionalString(), nil) } // OPTIONAL-COMPLEX-RESULT-AND-NIL-ERROR: func optionalComplexResultAndNilError() async throws -> String { // OPTIONAL-COMPLEX-RESULT-AND-NIL-ERROR-NEXT: return makeOptionalString() // OPTIONAL-COMPLEX-RESULT-AND-NIL-ERROR-NEXT: } // The refactored code doesn't compile because we can't return an optional // String from the async function. // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=OPTIONAL-COMPLEX-RESULT-AND-OPTIONAL-RELAYED-ERROR %s func optionalComplexResultAndOptionalRelayedError(completion: @escaping (String?, Error?) -> Void) { simpleErr(arg: "test") { (res, err) in completion(makeOptionalString(), err) } } // OPTIONAL-COMPLEX-RESULT-AND-OPTIONAL-RELAYED-ERROR: func optionalComplexResultAndOptionalRelayedError() async throws -> String { // OPTIONAL-COMPLEX-RESULT-AND-OPTIONAL-RELAYED-ERROR-NEXT: let res = try await simpleErr(arg: "test") // OPTIONAL-COMPLEX-RESULT-AND-OPTIONAL-RELAYED-ERROR-NEXT: return makeOptionalString() // OPTIONAL-COMPLEX-RESULT-AND-OPTIONAL-RELAYED-ERROR-NEXT: } // The refactored code doesn't compile because we can't return an optional // String or throw an optional Error from the async function. // RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=OPTIONAL-COMPLEX-RESULT-AND-OPTIONAL-COMPLEX-ERROR %s func optionalComplexResultAndOptionalComplexError(completion: @escaping (String?, Error?) -> Void) { completion(makeOptionalString(), makeOptionalError()) } // OPTIONAL-COMPLEX-RESULT-AND-OPTIONAL-COMPLEX-ERROR: func optionalComplexResultAndOptionalComplexError() async throws -> String { // OPTIONAL-COMPLEX-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: if let error = makeOptionalError() { // OPTIONAL-COMPLEX-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: throw error // OPTIONAL-COMPLEX-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: } else { // OPTIONAL-COMPLEX-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: return makeOptionalString() // OPTIONAL-COMPLEX-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: } // OPTIONAL-COMPLEX-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: } // RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=OPTIONAL-COMPLEX-RESULT-AND-NON-OPTIONAL-ERROR %s func optionalComplexResultAndNonOptionalError(completion: @escaping (String?, Error?) -> Void) { completion(makeOptionalString(), CustomError.Bad) } // OPTIONAL-COMPLEX-RESULT-AND-NON-OPTIONAL-ERROR: func optionalComplexResultAndNonOptionalError() async throws -> String { // OPTIONAL-COMPLEX-RESULT-AND-NON-OPTIONAL-ERROR-NEXT: throw CustomError.Bad // OPTIONAL-COMPLEX-RESULT-AND-NON-OPTIONAL-ERROR-NEXT: } // RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NON-OPTIONAL-RESULT-AND-NIL-ERROR %s func nonOptionalResultAndNilError(completion: @escaping (String?, Error?) -> Void) { completion("abc", nil) } // NON-OPTIONAL-RESULT-AND-NIL-ERROR: func nonOptionalResultAndNilError() async throws -> String { // NON-OPTIONAL-RESULT-AND-NIL-ERROR-NEXT: return "abc" // NON-OPTIONAL-RESULT-AND-NIL-ERROR-NEXT: } // RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NON-OPTIONAL-RESULT-AND-OPTIONAL-RELAYED-ERROR %s func nonOptionalResultAndOptionalRelayedError(completion: @escaping (String?, Error?) -> Void) { simpleErr(arg: "test") { (res, err) in completion("abc", err) } } // NON-OPTIONAL-RESULT-AND-OPTIONAL-RELAYED-ERROR: func nonOptionalResultAndOptionalRelayedError() async throws -> String { // NON-OPTIONAL-RESULT-AND-OPTIONAL-RELAYED-ERROR-NEXT: let res = try await simpleErr(arg: "test") // NON-OPTIONAL-RESULT-AND-OPTIONAL-RELAYED-ERROR-NEXT: return "abc" // NON-OPTIONAL-RESULT-AND-OPTIONAL-RELAYED-ERROR-NEXT: } // RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NON-OPTIONAL-RESULT-AND-OPTIONAL-COMPLEX-ERROR %s func nonOptionalResultAndOptionalComplexError(completion: @escaping (String?, Error?) -> Void) { completion("abc", makeOptionalError()) } // NON-OPTIONAL-RESULT-AND-OPTIONAL-COMPLEX-ERROR: func nonOptionalResultAndOptionalComplexError() async throws -> String { // NON-OPTIONAL-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: if let error = makeOptionalError() { // NON-OPTIONAL-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: throw error // NON-OPTIONAL-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: } else { // NON-OPTIONAL-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: return "abc" // NON-OPTIONAL-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: } // NON-OPTIONAL-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: } // RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NON-OPTIONAL-RESULT-AND-NON-OPTIONAL-ERROR %s func nonOptionalResultAndNonOptionalError(completion: @escaping (String?, Error?) -> Void) { completion("abc", CustomError.Bad) } // NON-OPTIONAL-RESULT-AND-NON-OPTIONAL-ERROR: func nonOptionalResultAndNonOptionalError() async throws -> String { // NON-OPTIONAL-RESULT-AND-NON-OPTIONAL-ERROR-NEXT: throw CustomError.Bad // NON-OPTIONAL-RESULT-AND-NON-OPTIONAL-ERROR-NEXT: } // RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=WRAP-COMPLETION-CALL-IN-PARENS %s func wrapCompletionCallInParenthesis(completion: @escaping (String?, Error?) -> Void) { simpleErr(arg: "test") { (res, err) in (completion(res, err)) } } // WRAP-COMPLETION-CALL-IN-PARENS: func wrapCompletionCallInParenthesis() async throws -> String { // WRAP-COMPLETION-CALL-IN-PARENS-NEXT: let res = try await simpleErr(arg: "test") // WRAP-COMPLETION-CALL-IN-PARENS-NEXT: return res // WRAP-COMPLETION-CALL-IN-PARENS-NEXT: } // RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=WRAP-RESULT-IN-PARENS %s func wrapResultInParenthesis(completion: @escaping (String?, Error?) -> Void) { simpleErr(arg: "test") { (res, err) in completion((res).self, err) } } // WRAP-RESULT-IN-PARENS: func wrapResultInParenthesis() async throws -> String { // WRAP-RESULT-IN-PARENS-NEXT: let res = try await simpleErr(arg: "test") // WRAP-RESULT-IN-PARENS-NEXT: return res // WRAP-RESULT-IN-PARENS-NEXT: } // RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=TWO-COMPLETION-HANDLER-CALLS %s func twoCompletionHandlerCalls(completion: @escaping (String?, Error?) -> Void) { simpleErr(arg: "test") { (res, err) in completion(res, err) completion(res, err) } } // TWO-COMPLETION-HANDLER-CALLS: func twoCompletionHandlerCalls() async throws -> String { // TWO-COMPLETION-HANDLER-CALLS-NEXT: let res = try await simpleErr(arg: "test") // TWO-COMPLETION-HANDLER-CALLS-NEXT: return res // TWO-COMPLETION-HANDLER-CALLS-NEXT: return res // TWO-COMPLETION-HANDLER-CALLS-NEXT: } // RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NESTED-IGNORED %s func nestedIgnored() throws { simple { _ in print("done") simple { _ in print("done") } } } // NESTED-IGNORED: func nestedIgnored() async throws { // NESTED-IGNORED-NEXT: let _ = await simple() // NESTED-IGNORED-NEXT: print("done") // NESTED-IGNORED-NEXT: let _ = await simple() // NESTED-IGNORED-NEXT: print("done") // NESTED-IGNORED-NEXT: } // RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=IGNORED-ERR %s func nestedIgnoredErr() throws { simpleErr(arg: "") { str, _ in if str == nil { print("error") } simpleErr(arg: "") { str, _ in if str == nil { print("error") } } } } // IGNORED-ERR: func nestedIgnoredErr() async throws { // IGNORED-ERR-NEXT: do { // IGNORED-ERR-NEXT: let str = try await simpleErr(arg: "") // IGNORED-ERR-NEXT: do { // IGNORED-ERR-NEXT: let str1 = try await simpleErr(arg: "") // IGNORED-ERR-NEXT: } catch { // IGNORED-ERR-NEXT: print("error") // IGNORED-ERR-NEXT: } // IGNORED-ERR-NEXT: } catch { // IGNORED-ERR-NEXT: print("error") // IGNORED-ERR-NEXT: } // IGNORED-ERR-NEXT: }
apache-2.0
fd1481d93638407dfe14b2a8bff580b6
46.980854
183
0.695202
3.200609
false
false
false
false
firebase/quickstart-ios
database/DatabaseExampleSwift/SignInViewController.swift
1
4970
// // Copyright (c) 2015 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 UIKit import FirebaseDatabase import FirebaseAuth @objc(SignInViewController) class SignInViewController: UIViewController, UITextFieldDelegate { @IBOutlet var emailField: UITextField! @IBOutlet var passwordField: UITextField! var ref: DatabaseReference! override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { view.endEditing(true) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if Auth.auth().currentUser != nil { performSegue(withIdentifier: "signIn", sender: nil) } ref = Database.database().reference() } // Saves user profile information to user database func saveUserInfo(_ user: FirebaseAuth.User, withUsername username: String) { // Create a change request showSpinner {} let changeRequest = Auth.auth().currentUser?.createProfileChangeRequest() changeRequest?.displayName = username // Commit profile changes to server changeRequest?.commitChanges { error in self.hideSpinner {} if let error = error { self.showMessagePrompt(error.localizedDescription) return } // [START basic_write] self.ref.child("users").child(user.uid).setValue(["username": username]) // [END basic_write] self.performSegue(withIdentifier: "signIn", sender: nil) } } @IBAction func didTapEmailLogin(_ sender: AnyObject) { guard let email = emailField.text, let password = passwordField.text else { showMessagePrompt("email/password can't be empty") return } showSpinner {} // Sign user in Auth.auth().signIn(withEmail: email, password: password, completion: { authResult, error in self.hideSpinner {} guard let user = authResult?.user, error == nil else { self.showMessagePrompt(error!.localizedDescription) return } self.ref.child("users").child(user.uid).observeSingleEvent(of: .value, with: { snapshot in // Check if user already exists guard !snapshot.exists() else { self.performSegue(withIdentifier: "signIn", sender: nil) return } // Otherwise, create the new user account self.showTextInputPrompt(withMessage: "Username:") { userPressedOK, username in guard let username = username else { self.showMessagePrompt("Username can't be empty") return } self.saveUserInfo(user, withUsername: username) } }) // End of observeSingleEvent }) // End of signIn } @IBAction func didTapSignUp(_ sender: AnyObject) { func getEmail(completion: @escaping (String) -> Void) { showTextInputPrompt(withMessage: "Email:") { userPressedOK, email in guard let email = email else { self.showMessagePrompt("Email can't be empty.") return } completion(email) } } func getUsername(completion: @escaping (String) -> Void) { showTextInputPrompt(withMessage: "Username:") { userPressedOK, username in guard let username = username else { self.showMessagePrompt("Username can't be empty.") return } completion(username) } } func getPassword(completion: @escaping (String) -> Void) { showTextInputPrompt(withMessage: "Password:") { userPressedOK, password in guard let password = password else { self.showMessagePrompt("Password can't be empty.") return } completion(password) } } // Get the credentials of the user getEmail { email in getUsername { username in getPassword { password in // Create the user with the provided credentials Auth.auth() .createUser(withEmail: email, password: password, completion: { authResult, error in guard let user = authResult?.user, error == nil else { self.showMessagePrompt(error!.localizedDescription) return } // Finally, save their profile self.saveUserInfo(user, withUsername: username) }) } } } } // MARK: - UITextFieldDelegate protocol methods func textFieldShouldReturn(_ textField: UITextField) -> Bool { didTapEmailLogin(textField) return true } }
apache-2.0
2d784a410c67a9a389897f41f1e1dcf9
29.490798
96
0.649095
4.774256
false
false
false
false
firebase/firebase-ios-sdk
FirebaseMLModelDownloader/Sources/ModelDownloader.swift
1
27475
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation import FirebaseCore import FirebaseInstallations /// Possible ways to get a custom model. public enum ModelDownloadType { /// Get local model stored on device if available. If no local model on device, this is the same as `latestModel`. case localModel /// Get local model on device if available and update to latest model from server in the background. If no local model on device, this is the same as `latestModel`. case localModelUpdateInBackground /// Get latest model from server. Does not make a network call for model file download if local model matches the latest version on server. case latestModel } /// Downloader to manage custom model downloads. public class ModelDownloader { /// Name of the app associated with this instance of ModelDownloader. private let appName: String /// Current Firebase app options. private let options: FirebaseOptions /// Installations instance for current Firebase app. private let installations: Installations /// User defaults for model info. private let userDefaults: UserDefaults /// Telemetry logger tied to this instance of model downloader. let telemetryLogger: TelemetryLogger? /// Number of retries in case of model download URL expiry. var numberOfRetries: Int = 1 /// Shared dictionary mapping app name to a specific instance of model downloader. // TODO: Switch to using Firebase components. private static var modelDownloaderDictionary: [String: ModelDownloader] = [:] /// Download task associated with the model currently being downloaded. private var currentDownloadTask: [String: ModelDownloadTask] = [:] /// DispatchQueue to manage download task dictionary. let taskSerialQueue = DispatchQueue(label: "downloadtask.serial.queue") /// Re-dispatch a function on the main queue. func asyncOnMainQueue(_ work: @autoclosure @escaping () -> Void) { DispatchQueue.main.async { work() } } /// Private init for model downloader. private init(app: FirebaseApp, defaults: UserDefaults = .firebaseMLDefaults) { appName = app.name options = app.options installations = Installations.installations(app: app) userDefaults = defaults // Respect Firebase-wide data collection setting. telemetryLogger = TelemetryLogger(app: app) // Notification of app deletion. let notificationName = "FIRAppDeleteNotification" NotificationCenter.default.addObserver( self, selector: #selector(deleteModelDownloader), name: Notification.Name(notificationName), object: nil ) } /// Handles app deletion notification. @objc private func deleteModelDownloader(notification: Notification) { let userInfoKey = "FIRAppNameKey" if let userInfo = notification.userInfo, let appName = userInfo[userInfoKey] as? String { ModelDownloader.modelDownloaderDictionary.removeValue(forKey: appName) // TODO: Clean up user defaults. // TODO: Clean up local instances of app. DeviceLogger.logEvent(level: .debug, message: ModelDownloader.DebugDescription.deleteModelDownloader, messageCode: .downloaderInstanceDeleted) } } /// Model downloader with default app. public static func modelDownloader() -> ModelDownloader { guard let defaultApp = FirebaseApp.app() else { fatalError(ModelDownloader.ErrorDescription.defaultAppNotConfigured) } return modelDownloader(app: defaultApp) } /// Model Downloader with custom app. public static func modelDownloader(app: FirebaseApp) -> ModelDownloader { if let downloader = modelDownloaderDictionary[app.name] { DeviceLogger.logEvent(level: .debug, message: ModelDownloader.DebugDescription.retrieveModelDownloader, messageCode: .downloaderInstanceRetrieved) return downloader } else { let downloader = ModelDownloader(app: app) modelDownloaderDictionary[app.name] = downloader DeviceLogger.logEvent(level: .debug, message: ModelDownloader.DebugDescription.createModelDownloader, messageCode: .downloaderInstanceCreated) return downloader } } /// Downloads a custom model to device or gets a custom model already on device, with an optional handler for progress. /// - Parameters: /// - modelName: The name of the model, matching Firebase console. /// - downloadType: ModelDownloadType used to get the model. /// - conditions: Conditions needed to perform a model download. /// - progressHandler: Optional. Returns a float in [0.0, 1.0] that can be used to monitor model download progress. /// - completion: Returns either a `CustomModel` on success, or a `DownloadError` on failure, at the end of a model download. public func getModel(name modelName: String, downloadType: ModelDownloadType, conditions: ModelDownloadConditions, progressHandler: ((Float) -> Void)? = nil, completion: @escaping (Result<CustomModel, DownloadError>) -> Void) { guard !modelName.isEmpty else { asyncOnMainQueue(completion(.failure(.emptyModelName))) return } switch downloadType { case .localModel: if let localModel = getLocalModel(modelName: modelName) { DeviceLogger.logEvent(level: .debug, message: ModelDownloader.DebugDescription.localModelFound, messageCode: .localModelFound) asyncOnMainQueue(completion(.success(localModel))) } else { getRemoteModel( modelName: modelName, conditions: conditions, progressHandler: progressHandler, completion: completion ) } case .localModelUpdateInBackground: if let localModel = getLocalModel(modelName: modelName) { DeviceLogger.logEvent(level: .debug, message: ModelDownloader.DebugDescription.localModelFound, messageCode: .localModelFound) asyncOnMainQueue(completion(.success(localModel))) telemetryLogger?.logModelDownloadEvent( eventName: .modelDownload, status: .scheduled, model: CustomModel(name: modelName, size: 0, path: "", hash: ""), downloadErrorCode: .noError ) // Update local model in the background. DispatchQueue.global(qos: .utility).async { [weak self] in self?.getRemoteModel( modelName: modelName, conditions: conditions, progressHandler: nil, completion: { result in switch result { case let .success(model): DeviceLogger.logEvent(level: .debug, message: ModelDownloader.DebugDescription .backgroundModelDownloaded, messageCode: .backgroundModelDownloaded) self?.telemetryLogger?.logModelDownloadEvent( eventName: .modelDownload, status: .succeeded, model: model, downloadErrorCode: .noError ) case .failure: DeviceLogger.logEvent(level: .debug, message: ModelDownloader.ErrorDescription .backgroundModelDownload, messageCode: .backgroundDownloadError) self?.telemetryLogger?.logModelDownloadEvent( eventName: .modelDownload, status: .failed, model: CustomModel(name: modelName, size: 0, path: "", hash: ""), downloadErrorCode: .downloadFailed ) } } ) } } else { getRemoteModel( modelName: modelName, conditions: conditions, progressHandler: progressHandler, completion: completion ) } case .latestModel: getRemoteModel( modelName: modelName, conditions: conditions, progressHandler: progressHandler, completion: completion ) } } /// Gets the set of all downloaded models saved on device. /// - Parameter completion: Returns either a set of `CustomModel` models on success, or a `DownloadedModelError` on failure. public func listDownloadedModels(completion: @escaping (Result<Set<CustomModel>, DownloadedModelError>) -> Void) { do { let modelURLs = try ModelFileManager.contentsOfModelsDirectory() var customModels = Set<CustomModel>() // Retrieve model name from URL. for url in modelURLs { guard let modelName = ModelFileManager.getModelNameFromFilePath(url) else { let description = ModelDownloader.ErrorDescription.parseModelName(url.path) DeviceLogger.logEvent(level: .debug, message: description, messageCode: .modelNameParseError) asyncOnMainQueue(completion(.failure(.internalError(description: description)))) return } // Check if model information corresponding to model is stored in UserDefaults. guard let modelInfo = getLocalModelInfo(modelName: modelName) else { let description = ModelDownloader.ErrorDescription.noLocalModelInfo(modelName) DeviceLogger.logEvent(level: .debug, message: description, messageCode: .noLocalModelInfo) asyncOnMainQueue(completion(.failure(.internalError(description: description)))) return } // Ensure that local model path is as expected, and reachable. guard let modelURL = ModelFileManager.getDownloadedModelFileURL( appName: appName, modelName: modelName ), ModelFileManager.isFileReachable(at: modelURL) else { DeviceLogger.logEvent(level: .debug, message: ModelDownloader.ErrorDescription.outdatedModelPath, messageCode: .outdatedModelPathError) asyncOnMainQueue(completion(.failure(.internalError(description: ModelDownloader .ErrorDescription.outdatedModelPath)))) return } let model = CustomModel(localModelInfo: modelInfo, path: modelURL.path) // Add model to result set. customModels.insert(model) } DeviceLogger.logEvent(level: .debug, message: ModelDownloader.DebugDescription.allLocalModelsFound, messageCode: .allLocalModelsFound) completion(.success(customModels)) } catch let error as DownloadedModelError { DeviceLogger.logEvent(level: .debug, message: ModelDownloader.ErrorDescription.listModelsFailed(error), messageCode: .listModelsError) asyncOnMainQueue(completion(.failure(error))) } catch { DeviceLogger.logEvent(level: .debug, message: ModelDownloader.ErrorDescription.listModelsFailed(error), messageCode: .listModelsError) asyncOnMainQueue(completion(.failure(.internalError(description: error .localizedDescription)))) } } /// Deletes a custom model file from device as well as corresponding model information saved in UserDefaults. /// - Parameters: /// - modelName: The name of the model, matching Firebase console and already downloaded to device. /// - completion: Returns a `DownloadedModelError` on failure. public func deleteDownloadedModel(name modelName: String, completion: @escaping (Result<Void, DownloadedModelError>) -> Void) { // Ensure that there is a matching model file on device, with corresponding model information in UserDefaults. guard let modelURL = ModelFileManager.getDownloadedModelFileURL( appName: appName, modelName: modelName ), let localModelInfo = getLocalModelInfo(modelName: modelName), ModelFileManager.isFileReachable(at: modelURL) else { DeviceLogger.logEvent(level: .debug, message: ModelDownloader.ErrorDescription.modelNotFound(modelName), messageCode: .modelNotFound) asyncOnMainQueue(completion(.failure(.notFound))) return } do { // Remove model file from device. try ModelFileManager.removeFile(at: modelURL) // Clear out corresponding local model info. localModelInfo.removeFromDefaults(userDefaults, appName: appName) DeviceLogger.logEvent(level: .debug, message: ModelDownloader.DebugDescription.modelDeleted, messageCode: .modelDeleted) telemetryLogger?.logModelDeletedEvent( eventName: .remoteModelDeleteOnDevice, isSuccessful: true ) asyncOnMainQueue(completion(.success(()))) } catch let error as DownloadedModelError { DeviceLogger.logEvent(level: .debug, message: ModelDownloader.ErrorDescription.modelDeletionFailed(error), messageCode: .modelDeletionFailed) telemetryLogger?.logModelDeletedEvent( eventName: .remoteModelDeleteOnDevice, isSuccessful: false ) asyncOnMainQueue(completion(.failure(error))) } catch { DeviceLogger.logEvent(level: .debug, message: ModelDownloader.ErrorDescription.modelDeletionFailed(error), messageCode: .modelDeletionFailed) telemetryLogger?.logModelDeletedEvent( eventName: .remoteModelDeleteOnDevice, isSuccessful: false ) asyncOnMainQueue(completion(.failure(.internalError(description: error .localizedDescription)))) } } } extension ModelDownloader { /// Get model information for model saved on device, if available. private func getLocalModelInfo(modelName: String) -> LocalModelInfo? { guard let localModelInfo = LocalModelInfo( fromDefaults: userDefaults, name: modelName, appName: appName ) else { let description = ModelDownloader.DebugDescription.noLocalModelInfo(modelName) DeviceLogger.logEvent(level: .debug, message: description, messageCode: .noLocalModelInfo) return nil } /// Local model info is only considered valid if there is a corresponding model file on device. guard let modelURL = ModelFileManager.getDownloadedModelFileURL( appName: appName, modelName: modelName ), ModelFileManager.isFileReachable(at: modelURL) else { let description = ModelDownloader.DebugDescription.noLocalModelFile(modelName) DeviceLogger.logEvent(level: .debug, message: description, messageCode: .noLocalModelFile) return nil } return localModelInfo } /// Get model saved on device, if available. private func getLocalModel(modelName: String) -> CustomModel? { guard let modelURL = ModelFileManager.getDownloadedModelFileURL( appName: appName, modelName: modelName ), let localModelInfo = getLocalModelInfo(modelName: modelName) else { return nil } let model = CustomModel(localModelInfo: localModelInfo, path: modelURL.path) return model } /// Download and get model from server, unless the latest model is already available on device. private func getRemoteModel(modelName: String, conditions: ModelDownloadConditions, progressHandler: ((Float) -> Void)? = nil, completion: @escaping (Result<CustomModel, DownloadError>) -> Void) { let localModelInfo = getLocalModelInfo(modelName: modelName) guard let projectID = options.projectID, let apiKey = options.apiKey else { DeviceLogger.logEvent(level: .debug, message: ModelDownloader.ErrorDescription.invalidOptions, messageCode: .invalidOptions) completion(.failure(.internalError(description: ModelDownloader.ErrorDescription .invalidOptions))) return } let modelInfoRetriever = ModelInfoRetriever( modelName: modelName, projectID: projectID, apiKey: apiKey, appName: appName, installations: installations, localModelInfo: localModelInfo, telemetryLogger: telemetryLogger ) let downloader = ModelFileDownloader(conditions: conditions) downloadInfoAndModel( modelName: modelName, modelInfoRetriever: modelInfoRetriever, downloader: downloader, conditions: conditions, progressHandler: progressHandler, completion: completion ) } /// Get model info and model file from server. func downloadInfoAndModel(modelName: String, modelInfoRetriever: ModelInfoRetriever, downloader: FileDownloader, conditions: ModelDownloadConditions, progressHandler: ((Float) -> Void)? = nil, completion: @escaping (Result<CustomModel, DownloadError>) -> Void) { modelInfoRetriever.downloadModelInfo { result in switch result { case let .success(downloadModelInfoResult): switch downloadModelInfoResult { // New model info was downloaded from server. case let .modelInfo(remoteModelInfo): // Progress handler for model file download. let taskProgressHandler: ModelDownloadTask.ProgressHandler = { progress in if let progressHandler = progressHandler { self.asyncOnMainQueue(progressHandler(progress)) } } // Completion handler for model file download. let taskCompletion: ModelDownloadTask.Completion = { result in switch result { case let .success(model): self.asyncOnMainQueue(completion(.success(model))) case let .failure(error): switch error { case .notFound: self.asyncOnMainQueue(completion(.failure(.notFound))) case .invalidArgument: self.asyncOnMainQueue(completion(.failure(.invalidArgument))) case .permissionDenied: self.asyncOnMainQueue(completion(.failure(.permissionDenied))) // This is the error returned when model download URL has expired. case .expiredDownloadURL: // Retry model info and model file download, if allowed. guard self.numberOfRetries > 0 else { self .asyncOnMainQueue( completion(.failure(.internalError(description: ModelDownloader .ErrorDescription .expiredModelInfo))) ) return } self.numberOfRetries -= 1 DeviceLogger.logEvent(level: .debug, message: ModelDownloader.DebugDescription.retryDownload, messageCode: .retryDownload) self.downloadInfoAndModel( modelName: modelName, modelInfoRetriever: modelInfoRetriever, downloader: downloader, conditions: conditions, progressHandler: progressHandler, completion: completion ) default: self.asyncOnMainQueue(completion(.failure(error))) } } self.taskSerialQueue.async { // Stop keeping track of current download task. self.currentDownloadTask.removeValue(forKey: modelName) } } self.taskSerialQueue.sync { // Merge duplicate requests if there is already a download in progress for the same model. if let downloadTask = self.currentDownloadTask[modelName], downloadTask.canMergeRequests() { downloadTask.merge( newProgressHandler: taskProgressHandler, newCompletion: taskCompletion ) DeviceLogger.logEvent(level: .debug, message: ModelDownloader.DebugDescription.mergingRequests, messageCode: .mergeRequests) if downloadTask.canResume() { downloadTask.resume() } // TODO: Handle else. } else { // Create download task for model file download. let downloadTask = ModelDownloadTask( remoteModelInfo: remoteModelInfo, appName: self.appName, defaults: self.userDefaults, downloader: downloader, progressHandler: taskProgressHandler, completion: taskCompletion, telemetryLogger: self.telemetryLogger ) // Keep track of current download task to allow for merging duplicate requests. self.currentDownloadTask[modelName] = downloadTask downloadTask.resume() } } /// Local model info is the latest model info. case .notModified: guard let localModel = self.getLocalModel(modelName: modelName) else { // This can only happen if either local model info or the model file was wiped out after model info request but before server response. self .asyncOnMainQueue(completion(.failure(.internalError(description: ModelDownloader .ErrorDescription.deletedLocalModelInfoOrFile)))) return } self.asyncOnMainQueue(completion(.success(localModel))) } // Error retrieving model info. case let .failure(error): self.asyncOnMainQueue(completion(.failure(error))) } } } } /// Possible errors with model downloading. public enum DownloadError: Error, Equatable { /// No model with this name exists on server. case notFound /// Invalid, incomplete, or missing permissions for model download. case permissionDenied /// Conditions not met to perform download. case failedPrecondition /// Requests quota exhausted. case resourceExhausted /// Not enough space for model on device. case notEnoughSpace /// Malformed model name or Firebase app options. case invalidArgument /// Model name is empty. case emptyModelName /// Other errors with description. case internalError(description: String) } /// Possible errors with locating a model file on device. public enum DownloadedModelError: Error { /// No model with this name exists on device. case notFound /// File system error. case fileIOError(description: String) /// Other errors with description. case internalError(description: String) } /// Extension to handle internally meaningful errors. extension DownloadError { /// Model download URL expired before model download. // Model info retrieval and download is retried `numberOfRetries` times before failing. static let expiredDownloadURL: DownloadError = DownloadError .internalError(description: "Expired model download URL.") } /// Possible debug and error messages while using model downloader. extension ModelDownloader { /// Debug descriptions. private enum DebugDescription { static let createModelDownloader = "Initialized with new downloader instance associated with this app." static let retrieveModelDownloader = "Initialized with existing downloader instance associated with this app." static let deleteModelDownloader = "Model downloader instance deleted due to app deletion." static let localModelFound = "Found local model on device." static let allLocalModelsFound = "Found and listed all local models." static let noLocalModelInfo = { (name: String) in "No local model info for model named: \(name)." } static let noLocalModelFile = { (name: String) in "No local model file for model named: \(name)." } static let backgroundModelDownloaded = "Downloaded latest model in the background." static let modelDeleted = "Model deleted successfully." static let mergingRequests = "Merging duplicate download requests." static let retryDownload = "Retrying download." } /// Error descriptions. private enum ErrorDescription { static let defaultAppNotConfigured = "Default Firebase app not configured." static let invalidOptions = "Unable to retrieve project ID and/or API key for Firebase app." static let modelDownloadFailed = { (error: Error) in "Model download failed with error: \(error)" } static let modelNotFound = { (name: String) in "Model deletion failed due to no model found with name: \(name)" } static let modelInfoRetrievalFailed = { (error: Error) in "Model info retrieval failed with error: \(error)" } static let backgroundModelDownload = "Failed to update model in background." static let expiredModelInfo = "Unable to update expired model info." static let listModelsFailed = { (error: Error) in "Unable to list models, failed with error: \(error)" } static let parseModelName = { (path: String) in "List models failed due to unexpected model file name at \(path)." } static let noLocalModelInfo = { (name: String) in "List models failed due to no local model info for model file named: \(name)." } static let deletedLocalModelInfoOrFile = "Model unavailable due to deleted local model info or model file." static let outdatedModelPath = "List models failed due to outdated model paths in local storage." static let modelDeletionFailed = { (error: Error) in "Model deletion failed with error: \(error)" } } } /// Model downloader extension for testing. extension ModelDownloader { /// Model downloader instance for testing. static func modelDownloaderWithDefaults(_ defaults: UserDefaults, app: FirebaseApp) -> ModelDownloader { let downloader = ModelDownloader(app: app, defaults: defaults) return downloader } }
apache-2.0
d9f31fea2755e7a6983c73f2d46638c4
42.131868
166
0.643094
5.479657
false
false
false
false
nixzhu/MonkeyKing
Sources/MonkeyKing/MonkeyKing+handleOpenURL.swift
1
18661
import UIKit import Security extension MonkeyKing { public class func handleOpenUserActivity(_ userActivity: NSUserActivity) -> Bool { guard userActivity.activityType == NSUserActivityTypeBrowsingWeb, let url = userActivity.webpageURL else { return false } var isHandled = false shared.accountSet.forEach { account in switch account { case .weChat(_, _, _, let wxUL): if let wxUL = wxUL, url.absoluteString.hasPrefix(wxUL) { isHandled = handleWechatUniversalLink(url) } case .qq(_, let qqUL): if let qqUL = qqUL, url.absoluteString.hasPrefix(qqUL) { isHandled = handleQQUniversalLink(url) } case .weibo(_, _, _, let wbUL): if let wbURL = wbUL, url.absoluteString.hasPrefix(wbURL) { isHandled = handleWeiboUniversalLink(url) } default: () } } lastMessage = nil return isHandled } // MARK: - Wechat Universal Links @discardableResult private class func handleWechatUniversalLink(_ url: URL) -> Bool { guard let comps = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return false } // MARK: - update token if let authToken = comps.valueOfQueryItem("wechat_auth_token"), !authToken.isEmpty { wechatAuthToken = authToken } // MARK: - refreshToken if comps.path.hasSuffix("refreshToken") { if let msg = lastMessage { deliver(msg, completionHandler: shared.deliverCompletionHandler ?? { _ in }) } return true } // MARK: - oauth if comps.path.hasSuffix("oauth"), let code = comps.valueOfQueryItem("code") { return handleWechatOAuth(code: code) } // MARK: - pay if comps.path.hasSuffix("pay"), let ret = comps.valueOfQueryItem("ret"), let retIntValue = Int(ret) { if retIntValue == 0 { shared.payCompletionHandler?(.success(())) return true } else { let response: [String: String] = [ "ret": ret, "returnKey": comps.valueOfQueryItem("returnKey") ?? "", "notifyStr": comps.valueOfQueryItem("notifyStr") ?? "" ] shared.payCompletionHandler?(.failure(.apiRequest(.unrecognizedError(response: response)))) return false } } // TODO: handle `resendContextReqByScheme` // TODO: handle `jointpay` // TODO: handle `offlinepay` // TODO: handle `cardPackage` // TODO: handle `choosecard` // TODO: handle `chooseinvoice` // TODO: handle `openwebview` // TODO: handle `openbusinesswebview` // TODO: handle `openranklist` // TODO: handle `opentypewebview` return handleWechatCallbackResultViaPasteboard() } private class func handleWechatOAuth(code: String) -> Bool { if code == "authdeny" { shared.oauthFromWeChatCodeCompletionHandler = nil return false } // Login succeed if let halfOauthCompletion = shared.oauthFromWeChatCodeCompletionHandler { halfOauthCompletion(.success(code)) shared.oauthFromWeChatCodeCompletionHandler = nil } else { fetchWeChatOAuthInfoByCode(code: code) { result in shared.oauthCompletionHandler?(result) } } return true } private class func handleWechatCallbackResultViaPasteboard() -> Bool { guard let data = UIPasteboard.general.data(forPasteboardType: "content"), let dict = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any] else { return false } guard let account = shared.accountSet[.weChat], let info = dict[account.appID] as? [String: Any], let result = info["result"] as? String, let resultCode = Int(result) else { return false } // OAuth Failed if let state = info["state"] as? String, state == "Weixinauth", resultCode != 0 { let error: Error = resultCode == -2 ? .userCancelled : .sdk(.other(code: result)) shared.oauthCompletionHandler?(.failure(error)) return false } let succeed = (resultCode == 0) // Share or Launch Mini App let messageExtKey = "messageExt" if succeed { if let messageExt = info[messageExtKey] as? String { shared.launchFromWeChatMiniAppCompletionHandler?(.success(messageExt)) } else { shared.deliverCompletionHandler?(.success(nil)) } } else { if let messageExt = info[messageExtKey] as? String { shared.launchFromWeChatMiniAppCompletionHandler?(.success(messageExt)) return true } else { let error: Error = resultCode == -2 ? .userCancelled : .sdk(.other(code: result)) shared.deliverCompletionHandler?(.failure(error)) } } return succeed } // MARK: - QQ Universal Links @discardableResult private class func handleQQUniversalLink(_ url: URL) -> Bool { guard let comps = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return false } var error: Error? if let actionInfoString = comps.queryItems?.first(where: { $0.name == "sdkactioninfo" })?.value, let data = Data(base64Encoded: actionInfoString), let actionInfo = NSKeyedUnarchiver.unarchiveObject(with: data) as? [String: Any] { // What for? // sck_action_query=appsign_bundlenull=2&source=qq&source_scheme=mqqapi&error=0&version=1 // sdk_action_path= // sdk_action_scheme=tencent101******8 // sdk_action_host=response_from_qq if let query = actionInfo["sdk_action_query"] as? String { if query.contains("error=0") { error = nil } else if query.contains("error=-4") { error = .userCancelled } else { // TODO: handle error_description=dGhlIHVzZXIgZ2l2ZSB1cCB0aGUgY3VycmVudCBvcGVyYXRpb24= error = .noAccount } } } guard handleQQCallbackResult(url: url, error: error) else { return false } return true } private class func handleQQCallbackResult(url: URL, error: Error?) -> Bool { guard let account = shared.accountSet[.qq] else { return false } // Share // Pasteboard is empty if let ul = account.universalLink, url.absoluteString.hasPrefix(ul), url.path.contains("response_from_qq") { let result = error.map(Result<ResponseJSON?, Error>.failure) ?? .success(nil) shared.deliverCompletionHandler?(result) return true } // OpenApi.m:131 getDictionaryFromGeneralPasteBoard guard let data = UIPasteboard.general.data(forPasteboardType: "com.tencent.tencent\(account.appID)"), let info = NSKeyedUnarchiver.unarchiveObject(with: data) as? [String: Any] else { shared.oauthCompletionHandler?(.failure(.sdk(.deserializeFailed))) return false } if url.path.contains("mqqsignapp") && url.query?.contains("generalpastboard=1") == true { // OpenApi.m:680 start universallink signature. guard let token = info["appsign_token"] as? String, let appSignRedirect = info["appsign_redirect"] as? String, var redirectComps = URLComponents(string: appSignRedirect) else { return false } qqAppSignToken = token redirectComps.queryItems?.append(.init(name: "appsign_token", value: qqAppSignToken)) if let callbackName = redirectComps.queryItems?.first(where: { $0.name == "callback_name" })?.value { qqAppSignTxid = callbackName redirectComps.queryItems?.append(.init(name: "appsign_txid", value: qqAppSignTxid)) } if let ul = account.universalLink, url.absoluteString.hasPrefix(ul) { redirectComps.scheme = "https" redirectComps.host = "qm.qq.com" redirectComps.path = "/opensdkul/mqqapi/share/to_fri" } // Try to open the redirect url provided above if let redirectUrl = redirectComps.url, UIApplication.shared.canOpenURL(redirectUrl) { UIApplication.shared.open(redirectUrl) } // Otherwise we just send last message again else if let msg = lastMessage { deliver(msg, completionHandler: shared.deliverCompletionHandler ?? { _ in }) } // The dictionary also contains "appsign_retcode=25105" and "appsign_bundlenull=2" // We don't have to handle them yet. return true } // OAuth is the only leftover guard let result = info["ret"] as? Int, result == 0 else { let error: Error if let errorDomatin = info["user_cancelled"] as? String, errorDomatin.uppercased() == "YES" { error = .userCancelled } else { error = .apiRequest(.unrecognizedError(response: nil)) } shared.oauthCompletionHandler?(.failure(error)) return false } shared.oauthCompletionHandler?(.success(info)) return true } // MARK: - Weibo Universal Links @discardableResult private class func handleWeiboUniversalLink(_ url: URL) -> Bool { guard let comps = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return false } if comps.path.hasSuffix("response") { return handleWeiboCallbackResultViaPasteboard() } return false } private class func handleWeiboCallbackResultViaPasteboard() -> Bool { let items = UIPasteboard.general.items var results = [String: Any]() for item in items { for (key, value) in item { if let valueData = value as? Data, key == "transferObject" { results[key] = NSKeyedUnarchiver.unarchiveObject(with: valueData) } } } guard let responseInfo = results["transferObject"] as? [String: Any], let type = responseInfo["__class"] as? String else { return false } guard let statusCode = responseInfo["statusCode"] as? Int else { return false } switch type { // OAuth case "WBAuthorizeResponse": if statusCode != 0 { shared.oauthCompletionHandler?(.failure(.apiRequest(.unrecognizedError(response: responseInfo)))) return false } shared.oauthCompletionHandler?(.success(responseInfo)) return true // Share case "WBSendMessageToWeiboResponse": let success = (statusCode == 0) if success { shared.deliverCompletionHandler?(.success(nil)) } else { let error: Error = statusCode == -1 ? .userCancelled : .sdk(.other(code: String(statusCode))) shared.deliverCompletionHandler?(.failure(error)) } return success default: return false } } // MARK: - OpenURL public class func handleOpenURL(_ url: URL) -> Bool { guard let urlScheme = url.scheme else { return false } // WeChat if urlScheme.hasPrefix("wx") { let urlString = url.absoluteString // OAuth if urlString.contains("state=") { let queryDictionary = url.monkeyking_queryDictionary guard let code = queryDictionary["code"] else { shared.oauthFromWeChatCodeCompletionHandler = nil return false } if handleWechatOAuth(code: code) { return true } } // SMS OAuth if urlString.contains("wapoauth") { let queryDictionary = url.monkeyking_queryDictionary guard let m = queryDictionary["m"] else { return false } guard let t = queryDictionary["t"] else { return false } guard let account = shared.accountSet[.weChat] else { return false } let appID = account.appID let urlString = "https://open.weixin.qq.com/connect/smsauthorize?appid=\(appID)&redirect_uri=\(appID)%3A%2F%2Foauth&response_type=code&scope=snsapi_message,snsapi_userinfo,snsapi_friend,snsapi_contact&state=xxx&uid=1926559385&m=\(m)&t=\(t)" addWebView(withURLString: urlString) return true } // Pay if urlString.contains("://pay/") { let queryDictionary = url.monkeyking_queryDictionary guard let ret = queryDictionary["ret"] else { shared.payCompletionHandler?(.failure(.apiRequest(.missingParameter))) return false } let result = (ret == "0") if result { shared.payCompletionHandler?(.success(())) } else { shared.payCompletionHandler?(.failure(.apiRequest(.unrecognizedError(response: queryDictionary)))) } return result } return handleWechatCallbackResultViaPasteboard() } // QQ if urlScheme.lowercased().hasPrefix("qq") || urlScheme.hasPrefix("tencent") { let errorDescription = url.monkeyking_queryDictionary["error"] ?? url.lastPathComponent var error: Error? var success = (errorDescription == "0") if success { error = nil } else { error = errorDescription == "-4" ? .userCancelled : .sdk(.other(code: errorDescription)) } // OAuth if url.path.contains("mqzone") { success = handleQQCallbackResult(url: url, error: error) } // Share else { if let error = error { shared.deliverCompletionHandler?(.failure(error)) } else { shared.deliverCompletionHandler?(.success(nil)) } } return success } // Weibo if urlScheme.hasPrefix("wb") { return handleWeiboCallbackResultViaPasteboard() } // Pocket OAuth if urlScheme.hasPrefix("pocketapp") { shared.oauthCompletionHandler?(.success(nil)) return true } // Alipay let account = shared.accountSet[.alipay] if let appID = account?.appID, urlScheme == "ap" + appID || urlScheme == "apoauth" + appID { let urlString = url.absoluteString if urlString.contains("//safepay/?") { guard let query = url.query, let response = query.monkeyking_urlDecodedString?.data(using: .utf8), let json = response.monkeyking_json, let memo = json["memo"] as? [String: Any], let status = memo["ResultStatus"] as? String else { shared.oauthCompletionHandler?(.failure(.apiRequest(.missingParameter))) shared.payCompletionHandler?(.failure(.apiRequest(.missingParameter))) return false } if status != "9000" { shared.oauthCompletionHandler?(.failure(.apiRequest(.invalidParameter))) shared.payCompletionHandler?(.failure(.apiRequest(.invalidParameter))) return false } if urlScheme == "apoauth" + appID { // OAuth let resultStr = memo["result"] as? String ?? "" let urlStr = "https://www.example.com?" + resultStr let resultDic = URL(string: urlStr)?.monkeyking_queryDictionary ?? [:] if let _ = resultDic["auth_code"], let _ = resultDic["scope"] { shared.oauthCompletionHandler?(.success(resultDic)) return true } shared.oauthCompletionHandler?(.failure(.apiRequest(.unrecognizedError(response: resultDic)))) return false } else { // Pay shared.payCompletionHandler?(.success(())) } return true } else { // Share guard let data = UIPasteboard.general.data(forPasteboardType: "com.alipay.openapi.pb.resp.\(appID)"), let dict = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any], let objects = dict["$objects"] as? NSArray, let result = objects[12] as? Int else { return false } let success = (result == 0) if success { shared.deliverCompletionHandler?(.success(nil)) } else { shared.deliverCompletionHandler?(.failure(.sdk(.other(code: String(result))))) // TODO: user cancelled } return success } } if let handler = shared.openSchemeCompletionHandler { handler(.success(url)) return true } return false } }
mit
c75fe251e98b20267941209541581a5e
35.662083
256
0.536734
5.187934
false
false
false
false
givingjan/SMTagView
TagViewSample/ViewController.swift
1
2137
// // ViewController.swift // TagViewSample // // Created by JaN on 2017/7/5. // Copyright © 2017年 givingjan. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet var m_tagViewSingle: SMTagView! @IBOutlet var m_tagViewMultiple: SMTagView! @IBOutlet var m_btnChange: UIButton! var m_bIsMultiple : Bool = true var tags : [String] = ["咖啡Q","聰明奶茶","笑笑乒乓","下雨天的紅茶","明天的綠茶","笨豆漿","過期的茶葉蛋","雲端奶茶","國際的小鳳梨","黑胡椒樹皮"] // MARK: Life Cycle override func viewDidLoad() { super.viewDidLoad() self.automaticallyAdjustsScrollViewInsets = false self.initView() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK:Init private func initMultiple() { self.m_tagViewMultiple.layer.cornerRadius = 15.0 self.m_tagViewMultiple.tagMainColor = UIColor.orange self.m_tagViewMultiple.setTagForMultiple(title: "選幾個喜歡的吧 ! (多選)", tagType: .fill, tags: tags, maximumSelect: 3, minimumSelect: 2) { (indexes) in print("done:\(indexes)") } } private func initSingle() { self.m_tagViewSingle.layer.cornerRadius = 15.0 self.m_tagViewSingle.tagMainColor = UIColor.orange self.m_tagViewSingle.setTagForSingle(title: "你要選哪個呢 ? (單選)", tagType: .border, tags: tags) { (index) in print(index) } } private func initView() { initMultiple() initSingle() updateView() } private func updateView() { self.m_tagViewSingle.isHidden = self.m_bIsMultiple self.m_tagViewMultiple.isHidden = !self.m_bIsMultiple } @IBAction func handleChange(_ sender: Any) { self.m_bIsMultiple = !self.m_bIsMultiple let title = self.m_bIsMultiple == true ? "Change to Single" : "Change to Multiple" self.m_btnChange.setTitle(title, for: .normal) self.updateView() } }
mit
d295e3904708646d7c2addf28672ab11
28.130435
152
0.620398
3.465517
false
false
false
false
ksco/swift-algorithm-club-cn
Combinatorics/Combinatorics.swift
1
2660
/* Calculates n! */ func factorial(n: Int) -> Int { var n = n var result = 1 while n > 1 { result *= n n -= 1 } return result } /* Calculates P(n, k), the number of permutations of n distinct symbols in groups of size k. */ func permutations(n: Int, _ k: Int) -> Int { var n = n var answer = n for _ in 1..<k { n -= 1 answer *= n } return answer } /* Prints out all the permutations of the given array. Original algorithm by Niklaus Wirth. See also Dr.Dobb's Magazine June 1993, Algorithm Alley */ func permuteWirth<T>(a: [T], _ n: Int) { if n == 0 { print(a) // display the current permutation } else { var a = a permuteWirth(a, n - 1) for i in 0..<n { swap(&a[i], &a[n]) permuteWirth(a, n - 1) swap(&a[i], &a[n]) } } } /* Prints out all the permutations of an n-element collection. The initial array must be initialized with all zeros. The algorithm uses 0 as a flag that indicates more work to be done on each level of the recursion. Original algorithm by Robert Sedgewick. See also Dr.Dobb's Magazine June 1993, Algorithm Alley */ func permuteSedgewick(a: [Int], _ n: Int, inout _ pos: Int) { var a = a pos += 1 a[n] = pos if pos == a.count - 1 { print(a) // display the current permutation } else { for i in 0..<a.count { if a[i] == 0 { permuteSedgewick(a, i, &pos) } } } pos -= 1 a[n] = 0 } /* Calculates C(n, k), or "n-choose-k", i.e. how many different selections of size k out of a total number of distinct elements (n) you can make. Doesn't work very well for large numbers. */ func combinations(n: Int, _ k: Int) -> Int { return permutations(n, k) / factorial(k) } /* Calculates C(n, k), or "n-choose-k", i.e. the number of ways to choose k things out of n possibilities. */ func quickBinomialCoefficient(n: Int, _ k: Int) -> Int { var result = 1 for i in 0..<k { result *= (n - i) result /= (i + 1) } return result } /* Calculates C(n, k), or "n-choose-k", i.e. the number of ways to choose k things out of n possibilities. Thanks to the dynamic programming, this algorithm from Skiena allows for the calculation of much larger numbers, at the cost of temporary storage space for the cached values. */ func binomialCoefficient(n: Int, _ k: Int) -> Int { var bc = Array2D(columns: n + 1, rows: n + 1, initialValue: 0) for i in 0...n { bc[i, 0] = 1 bc[i, i] = 1 } if n > 0 { for i in 1...n { for j in 1..<i { bc[i, j] = bc[i - 1, j - 1] + bc[i - 1, j] } } } return bc[n, k] }
mit
6f60291ffd46f473fefc63abe8b601b0
21.166667
74
0.586466
3.133098
false
false
false
false

IVA Swift GitHub Code Dataset - Curated - Validation

Dataset Description

This is the curated valid split of IVA Swift dataset extracted from GitHub. It contains curated Swift files gathered with the purpose to train & validate a code generation model.

The dataset only contains a valid split.

For validation and unspliced versions, please check the following links:

Information about dataset structure, data involved, licenses, and standard Dataset Card information is available that applies to this dataset also.

Considerations for Using the Data

The dataset comprises source code from various repositories, potentially containing harmful or biased code, along with sensitive information such as passwords or usernames.

Downloads last month
0

Models trained or fine-tuned on mvasiliniuc/iva-swift-codeint-clean-valid